def get_enrolled_children_data_chart(domain,
                                     config,
                                     loc_level,
                                     show_test=False):
    config['month'] = datetime(*config['month'])

    chart_data = AggChildHealthMonthly.objects.filter(**config).values(
        'month', 'age_tranche', '%s_name' % loc_level).annotate(
            valid=Sum('valid_in_month'), ).order_by('month')

    if not show_test:
        chart_data = apply_exclude(domain, chart_data)

    chart = OrderedDict()
    chart.update({'0-1 month': 0})
    chart.update({'1-6 months': 0})
    chart.update({'6-12 months': 0})
    chart.update({'1-3 years': 0})
    chart.update({'3-6 years': 0})

    all = 0
    best_worst = {}
    for row in chart_data:
        location = row['%s_name' % loc_level]

        if not row['age_tranche']:
            continue

        age = int(row['age_tranche'])
        valid = row['valid']
        all += valid
        chart[match_age(age)] += valid

        if location in best_worst:
            best_worst[location] += valid
        else:
            best_worst[location] = valid

    return {
        "chart_data": [{
            "values": [{
                'x': key,
                'y': value,
                'all': all
            } for key, value in six.iteritems(chart)],
            "key":
            "Children (0-6 years) who are enrolled",
            "strokeWidth":
            2,
            "classed":
            "dashed",
            "color":
            ChartColors.BLUE
        }],
        "location_type":
        loc_level.title()
        if loc_level != LocationTypes.SUPERVISOR else 'Sector'
    }
def get_enrolled_children_data_chart(domain, config, loc_level, show_test=False):
    config['month'] = datetime(*config['month'])

    chart_data = AggChildHealthMonthly.objects.filter(
        **config
    ).values(
        'month', 'age_tranche', '%s_name' % loc_level
    ).annotate(
        valid=Sum('valid_in_month'),
    ).order_by('month')

    if not show_test:
        chart_data = apply_exclude(domain, chart_data)

    chart = OrderedDict()
    chart.update({'0-1 month': 0})
    chart.update({'1-6 months': 0})
    chart.update({'6-12 months': 0})
    chart.update({'1-3 years': 0})
    chart.update({'3-6 years': 0})

    all = 0
    best_worst = {}
    for row in chart_data:
        location = row['%s_name' % loc_level]

        if not row['age_tranche']:
            continue

        age = int(row['age_tranche'])
        valid = row['valid']
        all += valid
        chart[match_age(age)] += valid

        if location in best_worst:
            best_worst[location] += valid
        else:
            best_worst[location] = valid

    return {
        "chart_data": [
            {
                "values": [
                    {
                        'x': key,
                        'y': value,
                        'all': all
                    } for key, value in six.iteritems(chart)
                ],
                "key": "Children (0-6 years) who are enrolled",
                "strokeWidth": 2,
                "classed": "dashed",
                "color": ChartColors.BLUE
            }
        ],
        "location_type": loc_level.title() if loc_level != LocationTypes.SUPERVISOR else 'Sector'
    }
def get_awc_report_demographics(domain, config, month, show_test=False):
    selected_month = datetime(*month)

    chart = AggChildHealthMonthly.objects.filter(
        month=selected_month,
        **config).values('age_tranche', 'aggregation_level').annotate(
            valid=Sum('valid_in_month')).order_by('age_tranche')

    if not show_test:
        chart = apply_exclude(domain, chart)

    chart_data = OrderedDict()
    chart_data.update({'0-1 month': 0})
    chart_data.update({'1-6 months': 0})
    chart_data.update({'6-12 months': 0})
    chart_data.update({'1-3 years': 0})
    chart_data.update({'3-6 years': 0})

    for chart_row in chart:
        if chart_row['age_tranche']:
            age = int(chart_row['age_tranche'])
            valid = chart_row['valid']
            chart_data[match_age(age)] += valid

    def get_data_for(query_class, filters):
        queryset = query_class.objects.filter(
            **filters).values('aggregation_level').annotate(
                household=Sum('cases_household'),
                child_health=Sum('cases_child_health'),
                child_health_all=Sum('cases_child_health_all'),
                ccs_pregnant=Sum('cases_ccs_pregnant'),
                ccs_pregnant_all=Sum('cases_ccs_pregnant_all'),
                css_lactating=Sum('cases_ccs_lactating'),
                css_lactating_all=Sum('cases_ccs_lactating_all'),
                person_adolescent=(Sum('cases_person_adolescent_girls_11_14') +
                                   Sum('cases_person_adolescent_girls_15_18')),
                person_adolescent_all=(
                    Sum('cases_person_adolescent_girls_11_14_all') +
                    Sum('cases_person_adolescent_girls_15_18_all')),
                person_aadhaar=Sum('cases_person_has_aadhaar'),
                all_persons=Sum('cases_person_beneficiary'))

        if not show_test:
            queryset = apply_exclude(domain, queryset)
        return queryset

    yesterday = datetime.now() - relativedelta(days=1)
    two_days_ago = yesterday - relativedelta(days=1)
    now = datetime.utcnow()
    previous_month = selected_month - relativedelta(months=1)
    if selected_month.month == now.month and selected_month.year == now.year:
        config['date'] = yesterday
        data = get_data_for(AggAwcDailyView, config)
        config['date'] = two_days_ago
        prev_data = get_data_for(AggAwcDailyView, config)
        frequency = 'day'
    else:
        config['month'] = selected_month
        data = get_data_for(AggAwcMonthly, config)
        config['month'] = previous_month
        prev_data = get_data_for(AggAwcMonthly, config)
        frequency = 'month'

    return {
        'chart': [{
            'key':
            'Children (0-6 years)',
            'values': [[key, value] for key, value in chart_data.iteritems()],
            "classed":
            "dashed",
        }],
        'kpi':
        [[{
            'label':
            _('Registered Households'),
            'help_text':
            _("Total number of households registered"),
            'percent':
            percent_increase(
                'household',
                data,
                prev_data,
            ),
            'color':
            'green'
            if percent_increase('household', data, prev_data) > 0 else 'red',
            'value':
            get_value(data, 'household'),
            'all':
            '',
            'format':
            'number',
            'frequency':
            frequency
        },
          {
              'label':
              _('Percent Adhaar-seeded Beneficiaries'),
              'help_text':
              _('Percentage of ICDS beneficiaries whose Adhaar identification has been captured'
                ),
              'percent':
              percent_diff('person_aadhaar', data, prev_data, 'all_persons'),
              'value':
              get_value(data, 'person_aadhaar'),
              'all':
              get_value(data, 'all_persons'),
              'format':
              'percent_and_div',
              'frequency':
              frequency
          }],
         [{
             'label':
             _('Children (0-6 years)'),
             'help_text':
             _('Total number of children registered between the age of 0 - 6 years'
               ),
             'percent':
             percent_increase('child_health_all', data, prev_data),
             'color':
             'green'
             if percent_increase('child_health_all', data, prev_data) > 0 else
             'red',
             'value':
             get_value(data, 'child_health_all'),
             'all':
             None,
             'format':
             'number',
             'frequency':
             frequency,
         }, {
             'label':
             _('Children (0-6 years) enrolled for ICDS services'),
             'help_text':
             _(("Total number of children registered between the age of 0 - 6 years "
                "and enrolled for ICDS services")),
             'percent':
             percent_increase('child_health', data, prev_data),
             'color':
             'green' if percent_increase('child_health', data, prev_data) > 0
             else 'red',
             'value':
             get_value(data, 'child_health'),
             'all':
             None,
             'format':
             'number',
             'frequency':
             frequency
         }],
         [
             {
                 'label':
                 _('Pregnant Women'),
                 'help_text':
                 _("Total number of pregnant women registered"),
                 'percent':
                 percent_increase(
                     'ccs_pregnant_all',
                     data,
                     prev_data,
                 ),
                 'color':
                 'green'
                 if percent_increase('ccs_pregnant_all', data, prev_data) > 0
                 else 'red',
                 'value':
                 get_value(data, 'ccs_pregnant_all'),
                 'all':
                 '',
                 'format':
                 'number',
                 'frequency':
                 frequency
             },
             {
                 'label':
                 _('Pregnant Women enrolled for ICDS services'),
                 'help_text':
                 _('Total number of pregnant women registered and enrolled for ICDS services'
                   ),
                 'percent':
                 percent_increase('ccs_pregnant', data, prev_data),
                 'color':
                 'green'
                 if percent_increase('ccs_pregnant', data, prev_data) > 0 else
                 'red',
                 'value':
                 get_value(data, 'ccs_pregnant'),
                 'all':
                 None,
                 'format':
                 'number',
                 'frequency':
                 frequency
             },
         ],
         [
             {
                 'label':
                 _('Lactating Mothers'),
                 'help_text':
                 _('Total number of lactating women registered'),
                 'percent':
                 percent_increase('css_lactating_all', data, prev_data),
                 'color':
                 'green'
                 if percent_increase('css_lactating_all', data, prev_data) > 0
                 else 'red',
                 'value':
                 get_value(data, 'css_lactating_all'),
                 'all':
                 '',
                 'format':
                 'number',
                 'frequency':
                 frequency
             },
             {
                 'label':
                 _('Lactating Women enrolled for ICDS services'),
                 'help_text':
                 _('Total number of lactating women registered and enrolled for ICDS services'
                   ),
                 'percent':
                 percent_increase('css_lactating', data, prev_data),
                 'color':
                 'green'
                 if percent_increase('css_lactating', data, prev_data) > 0 else
                 'red',
                 'value':
                 get_value(data, 'css_lactating'),
                 'all':
                 None,
                 'format':
                 'number',
                 'frequency':
                 frequency
             },
         ],
         [{
             'label':
             _('Adolescent Girls (11-18 years)'),
             'help_text':
             _('Total number of adolescent girls (11 - 18 years) who are registered'
               ),
             'percent':
             percent_increase(
                 'person_adolescent_all',
                 data,
                 prev_data,
             ),
             'color':
             'green'
             if percent_increase('person_adolescent_all', data, prev_data) > 0
             else 'red',
             'value':
             get_value(data, 'person_adolescent_all'),
             'all':
             '',
             'format':
             'number',
             'frequency':
             frequency
         }, {
             'label':
             _('Adolescent Girls (11-18 years) enrolled for ICDS services'),
             'help_text':
             _(("Total number of adolescent girls (11 - 18 years) "
                "who are registered and enrolled for ICDS services")),
             'percent':
             percent_increase('person_adolescent', data, prev_data),
             'color':
             'green'
             if percent_increase('person_adolescent', data, prev_data) > 0 else
             'red',
             'value':
             get_value(data, 'person_adolescent'),
             'all':
             None,
             'format':
             'number',
             'frequency':
             frequency
         }]]
    }
def get_awc_report_demographics(domain,
                                config,
                                now_date,
                                month,
                                show_test=False,
                                beta=False):
    selected_month = datetime(*month)
    now_date = datetime(*now_date)
    chart = AggChildHealthMonthly.objects.filter(
        month=selected_month,
        **config).values('age_tranche', 'aggregation_level').annotate(
            valid=Sum('valid_in_month')).order_by('age_tranche')

    if not show_test:
        chart = apply_exclude(domain, chart)

    chart_data = OrderedDict()
    chart_data.update({'0-1 month': 0})
    chart_data.update({'1-6 months': 0})
    chart_data.update({'6-12 months': 0})
    chart_data.update({'1-3 years': 0})
    chart_data.update({'3-6 years': 0})

    for chart_row in chart:
        if chart_row['age_tranche']:
            age = int(chart_row['age_tranche'])
            valid = chart_row['valid']
            chart_data[match_age(age)] += valid

    def get_data_for(query_class, filters):
        queryset = query_class.objects.filter(
            **filters).values('aggregation_level').annotate(
                household=Sum('cases_household'),
                child_health=Sum('cases_child_health'),
                child_health_all=Sum('cases_child_health_all'),
                ccs_pregnant=Sum('cases_ccs_pregnant'),
                ccs_pregnant_all=Sum('cases_ccs_pregnant_all'),
                css_lactating=Sum('cases_ccs_lactating'),
                css_lactating_all=Sum('cases_ccs_lactating_all'),
                person_adolescent=Sum('cases_person_adolescent_girls_11_14'),
                person_adolescent_all=Sum(
                    'cases_person_adolescent_girls_11_14_all'),
                person_aadhaar=Sum(person_has_aadhaar_column(beta)),
                all_persons=Sum(person_is_beneficiary_column(beta)))

        if not show_test:
            queryset = apply_exclude(domain, queryset)
        return queryset

    yesterday = now_date - relativedelta(days=1)
    two_days_ago = yesterday - relativedelta(days=1)
    previous_month = selected_month - relativedelta(months=1)
    if selected_month.month == now_date.month and selected_month.year == now_date.year:
        config['date'] = yesterday
        data = get_data_for(AggAwcDailyView, config)
        config['date'] = two_days_ago
        prev_data = get_data_for(AggAwcDailyView, config)
        if not data:
            data = prev_data
            config['date'] = (two_days_ago - relativedelta(days=1)).date()
            prev_data = get_data_for(AggAwcDailyView, config)
        frequency = 'day'
    else:
        config['month'] = selected_month
        data = get_data_for(AggAwcMonthly, config)
        config['month'] = previous_month
        prev_data = get_data_for(AggAwcMonthly, config)
        frequency = 'month'

    return {
        'chart': [{
            'key':
            'Children (0-6 years)',
            'values':
            [[key, value] for key, value in six.iteritems(chart_data)],
            "classed":
            "dashed",
        }],
        'kpi':
        [[{
            'label':
            _('Registered Households'),
            'help_text':
            _("Total number of households registered"),
            'percent':
            percent_increase(
                'household',
                data,
                prev_data,
            ),
            'color':
            'green'
            if percent_increase('household', data, prev_data) > 0 else 'red',
            'value':
            get_value(data, 'household'),
            'all':
            '',
            'format':
            'number',
            'frequency':
            frequency
        },
          {
              'label':
              _('Percent Aadhaar-seeded Beneficiaries'),
              'help_text':
              _('Of the total number of ICDS beneficiaries, the percentage whose Adhaar identification '
                'has been captured. '),
              'percent':
              percent_diff('person_aadhaar', data, prev_data, 'all_persons'),
              'color':
              'green' if percent_diff('person_aadhaar', data, prev_data,
                                      'all_persons') > 0 else 'red',
              'value':
              get_value(data, 'person_aadhaar'),
              'all':
              get_value(data, 'all_persons'),
              'format':
              'percent_and_div',
              'frequency':
              frequency
          }],
         [{
             'label':
             _('Percent children (0-6 years) enrolled for Anganwadi Services'),
             'help_text':
             _('Of the total number of children between 0-6 years, the percentage '
               'of children who are enrolled for Anganwadi Services'),
             'percent':
             percent_diff('child_health', data, prev_data, 'child_health_all'),
             'color':
             'green' if percent_diff('child_health_all', data, prev_data,
                                     'child_health_all') > 0 else 'red',
             'value':
             get_value(data, 'child_health'),
             'all':
             get_value(data, 'child_health_all'),
             'format':
             'percent_and_div',
             'frequency':
             frequency,
         }, {
             'label':
             _('Percent pregnant women enrolled for Anganwadi Services'),
             'help_text':
             _('Of the total number of pregnant women, the percentage of pregnant '
               'women enrolled for Anganwadi Services'),
             'percent':
             percent_diff('ccs_pregnant', data, prev_data, 'ccs_pregnant_all'),
             'color':
             'green' if percent_diff('ccs_pregnant', data, prev_data,
                                     'ccs_pregnant_all') > 0 else 'red',
             'value':
             get_value(data, 'ccs_pregnant'),
             'all':
             get_value(data, 'ccs_pregnant_all'),
             'format':
             'percent_and_div',
             'frequency':
             frequency
         }],
         [{
             'label':
             _('Percent lactating women enrolled for Anganwadi Services'),
             'help_text':
             _('Of the total number of lactating women, the percentage of '
               'lactating women enrolled for Anganwadi Services'),
             'percent':
             percent_diff('css_lactating', data, prev_data,
                          'css_lactating_all'),
             'color':
             'green' if percent_diff('css_lactating', data, prev_data,
                                     'css_lactating_all') > 0 else 'red',
             'value':
             get_value(data, 'css_lactating'),
             'all':
             get_value(data, 'css_lactating_all'),
             'format':
             'percent_and_div',
             'frequency':
             frequency
         }, {
             'label':
             _('Percent adolescent girls (11-14 years) enrolled for Anganwadi Services'
               ),
             'help_text':
             _(("Of the total number of adolescent girls (aged 11-14 years), the percentage "
                "of girls enrolled for Anganwadi Services")),
             'percent':
             percent_diff('person_adolescent', data, prev_data,
                          'person_adolescent_all'),
             'color':
             'green' if percent_diff('person_adolescent', data, prev_data,
                                     'person_adolescent_all') > 0 else 'red',
             'value':
             get_value(data, 'person_adolescent'),
             'all':
             get_value(data, 'person_adolescent_all'),
             'format':
             'percent_and_div',
             'frequency':
             frequency
         }]]
    }