Beispiel #1
0
def entities_show_policy(request, c, entity, id, title, render_callback=None):
    # Get request context
    c = get_context(request, css_class='body-policies', title='')
    c['policy_uid'] = id

    # Get the budget breakdown
    c['breakdowns'] = {
      'functional': BudgetBreakdown(['function', 'programme']),
      'economic': BudgetBreakdown(['chapter', 'article', 'heading'])
    }
    get_budget_breakdown(   "fc.policy = %s and e.id = %s", [ id, entity.id ],
                            [ 
                                c['breakdowns']['functional'],
                                c['breakdowns']['economic']
                            ])

    # Additional data needed by the view
    show_side = 'expense'
    populate_level(c, entity.level)
    populate_entity_stats(c, entity)
    populate_entity_descriptions(c, entity, show_side)
    populate_years(c, c['breakdowns']['functional'])
    populate_budget_statuses(c, entity.id)
    populate_area_descriptions(c, ['functional', show_side])
    populate_csv_settings(c, 'policy', id)
    set_show_side(c, show_side)
    set_full_breakdown(c, False)
    c['entity'] = entity

    c['name'] = c['descriptions']['functional'].get(c['policy_uid'])
    c['title_prefix'] = c['name']

    return render(c, render_callback, 'policies/show.html')
Beispiel #2
0
def investments(request, render_callback=None):
    c = get_context(request,
                    css_class='body-investments',
                    title=_(u'Inversiones por distrito'))
    entity = get_main_entity(c)
    set_entity(c, entity)

    # Get the investments breakdown
    query = "e.id = %s"
    investments = Investment.objects.each_denormalized(query, [entity.id])
    c['area_breakdown'] = BudgetBreakdown(['area'])
    c['no_area_breakdown'] = BudgetBreakdown(['area'])
    for item in investments:
        column_name = year_column_name(item)
        if item.area in ['NN', 'NA']:
            c['no_area_breakdown'].add_item(column_name, item)
        else:
            c['area_breakdown'].add_item(column_name, item)

    # Get list of investment areas
    c['areas'] = GeographicCategory.objects.categories(entity)

    # Get additional information
    populate_stats(c)
    populate_entity_descriptions(c, entity)
    populate_years(c, c['area_breakdown'])
    populate_budget_statuses(c, entity.id)

    # The per-capita format in investment pages is misleading, as it refers to the whole
    # entity population, not the particular districts/neighborhoods/areas, so we hide it.
    c['hide_per_capita_format'] = True

    return render(c, render_callback, 'investments/index.html')
Beispiel #3
0
def budgets(request):
    # Get request context
    c = get_context(request, css_class='body-summary', title='')

    # Retrieve the entity to display
    main_entity = get_main_entity(c)

    # Income/expense breakdown
    c['functional_breakdown'] = BudgetBreakdown(['policy', 'programme'])
    c['economic_breakdown'] = BudgetBreakdown(['article', 'heading'])
    c['chapter_breakdown'] = BudgetBreakdown(['chapter'
                                              ])  # Used for indicators
    c['include_financial_chapters'] = hasattr(
        settings, 'INCLUDE_FINANCIAL_CHAPTERS_IN_BREAKDOWNS'
    ) and settings.INCLUDE_FINANCIAL_CHAPTERS_IN_BREAKDOWNS
    for item in BudgetItem.objects.each_denormalized("e.id = %s",
                                                     [main_entity.id]):
        column_name = year_column_name(item)
        c['chapter_breakdown'].add_item(column_name, item)
        if c['include_financial_chapters'] or not item.is_financial():
            c['functional_breakdown'].add_item(column_name, item)
            c['economic_breakdown'].add_item(column_name, item)

    # Additional data needed by the view
    populate_stats(c)
    populate_descriptions(c)
    populate_budget_statuses(c, main_entity)
    populate_years(c, 'functional_breakdown')

    c['income_nodes'] = json.dumps(settings.OVERVIEW_INCOME_NODES)
    c['expense_nodes'] = json.dumps(settings.OVERVIEW_EXPENSE_NODES)

    return render_to_response('budgets/index.html', c)
Beispiel #4
0
def entities_compare(request, c, entity_left, entity_right):
    c['entity_left'] = entity_left
    c['entity_right'] = entity_right

    # Get the budget breakdowns
    # XXX: No good functional data at this level so far
    # c['functional_breakdown_left'] = BudgetBreakdown(['policy'])
    c['breakdowns']['economic_left'] = BudgetBreakdown(['chapter', 'article'])
    get_budget_breakdown(   "e.name = %s and ec.chapter <> 'X'", [ entity_left.name ],
                            [ 
                                c['breakdowns']['economic_left']
                            ])

    c['breakdowns']['economic_right'] = BudgetBreakdown(['chapter', 'article'])
    get_budget_breakdown(   "e.name = %s and ec.chapter <> 'X'", [ entity_right.name ],
                            [ 
                                c['breakdowns']['economic_right']
                            ])

    # Additional data needed by the view
    populate_level(c, entity_left.level)
    populate_entity_stats(c, entity_left, 'stats_left')
    populate_entity_stats(c, entity_right, 'stats_right')
    populate_entity_descriptions(c, entity_left)
    populate_area_descriptions(c, ['income', 'expense'])
    populate_comparison_years(c, c['breakdowns']['economic_left'], c['breakdowns']['economic_right'])
    populate_entities(c, entity_left.level)

    return render_response('entities/compare.html', c)
Beispiel #5
0
def payments(request, render_callback=None):
    # Get request context
    c = get_context(request,
                    css_class='body-payments',
                    title='Inversiones y pagos')

    # Payments breakdown
    c['payee_breakdown'] = BudgetBreakdown(['payee', 'area', 'description'])
    c['area_breakdown'] = BudgetBreakdown(['area', 'payee', 'description'])

    for item in Payment.objects.each_denormalized():
        # We add the date to the description, if it exists:
        # TODO: I wanted the date to be in a separate column, but it's complicated right
        # now the way BudgetBreakdown works. Need to think about it
        if item.date:
            item.description = item.description + ' (' + str(item.date) + ')'

        c['payee_breakdown'].add_item(item.year, item)
        c['area_breakdown'].add_item(item.year, item)

    # Additional data needed by the view
    populate_stats(c)
    populate_years(c, 'area_breakdown')

    return render_to_response('payments/index.html', c)
Beispiel #6
0
def programmes_show(request, id, title, render_callback=None):
    # Get request context
    c = get_context(request, css_class='body-policies', title='')

    # Retrieve the entity to display
    main_entity = get_main_entity(c)

    # Extra request context info
    c['programme_id'] = id
    c['programme'] = FunctionalCategory.objects.filter(
        budget__entity=main_entity, programme=id)[0]
    c['policy'] = FunctionalCategory.objects.filter(
        budget__entity=main_entity,
        policy=c['programme'].policy,
        function__isnull=True)[0]

    # Ignore if possible the descriptions for execution data, they are truncated and ugly
    programme_descriptions = {}

    def _populate_programme_descriptions(column_name, item):
        if not item.actual or not item.uid() in programme_descriptions:
            programme_descriptions[item.uid()] = getattr(item, 'description')

    # Get the budget breakdown.
    # The functional breakdown is an empty one, as we're at the deepest level, but since
    # we're going to be displaying this data in the policy page we send a blank one
    c['functional_breakdown'] = BudgetBreakdown([])
    c['economic_breakdown'] = BudgetBreakdown(
        ['chapter', 'article', 'heading', 'uid'])
    c['funding_breakdown'] = BudgetBreakdown(['source', 'fund'])
    c['institutional_breakdown'] = BudgetBreakdown(
        [_year_tagged_institution, _year_tagged_department])
    get_budget_breakdown("fc.programme = %s and e.id = %s",
                         [id, main_entity.id], [
                             c['economic_breakdown'], c['funding_breakdown'],
                             c['institutional_breakdown']
                         ], _populate_programme_descriptions)

    # Note we don't modify the original descriptions, we're working on a copy (of the hash,
    # which is made of references to the hashes containing the descriptions themselves).
    c['descriptions'] = Budget.objects.get_all_descriptions(main_entity).copy()
    programme_descriptions.update(c['descriptions']['expense'])
    c['descriptions']['expense'] = programme_descriptions
    c['name'] = c['descriptions']['functional'].get(c['programme_id'])
    c['title_prefix'] = c['name']

    # Additional data needed by the view
    show_side = 'expense'
    populate_stats(c)
    populate_years(c, 'institutional_breakdown')
    populate_budget_statuses(c, main_entity.id)
    populate_area_descriptions(c, ['functional', 'funding', show_side])
    _populate_csv_settings(c, 'programme', id)
    _set_show_side(c, show_side)
    _set_full_breakdown(c, True)

    c['draftBudgetYear'] = draftBudgetYear

    return render(c, render_callback, 'policies/show.html')
Beispiel #7
0
def budgets(request):
    # Get request context
    c = get_context(request, css_class='body-summary', title='')

    # Retrieve the entity to display
    main_entity = get_main_entity(c)

    # Income/expense breakdown
    c['breakdowns'] = {
        'functional': BudgetBreakdown(['policy', 'programme']),
        'economic': BudgetBreakdown(['article', 'heading']),
        'chapter': BudgetBreakdown(['chapter'])  # Used for indicators
    }
    for item in BudgetItem.objects.each_denormalized("e.id = %s",
                                                     [main_entity.id]):
        column_name = year_column_name(item)
        c['breakdowns']['chapter'].add_item(column_name, item)
        if c['include_financial_chapters'] or not item.is_financial():
            c['breakdowns']['functional'].add_item(column_name, item)
            c['breakdowns']['economic'].add_item(column_name, item)

    # Additional data needed by the view
    populate_stats(c)
    populate_descriptions(c)
    populate_budget_statuses(c, main_entity)
    populate_years(c, c['breakdowns']['functional'])

    c['income_nodes'] = json.dumps(settings.OVERVIEW_INCOME_NODES)
    c['expense_nodes'] = json.dumps(settings.OVERVIEW_EXPENSE_NODES)

    if hasattr(settings, 'OVERVIEW_RELAX_FACTOR'):
        c['relax_factor'] = settings.OVERVIEW_RELAX_FACTOR
    if hasattr(settings, 'OVERVIEW_NODE_PADDING'):
        c['overview_node_padding'] = settings.OVERVIEW_NODE_PADDING
    if hasattr(settings, 'OVERVIEW_FORCE_ORDER'):
        c['overview_force_order'] = settings.OVERVIEW_FORCE_ORDER

    if hasattr(settings, 'OVERVIEW_LABELS_MIN_SIZE'):
        c['overview_labels_min_size'] = settings.OVERVIEW_LABELS_MIN_SIZE
    if hasattr(settings, 'OVERVIEW_LABELS_FONT_SIZE_MIN'):
        c['overview_labels_font_size_min'] = settings.OVERVIEW_LABELS_FONT_SIZE_MIN
    if hasattr(settings, 'OVERVIEW_LABELS_FONT_SIZE_MAX'):
        c['overview_labels_font_size_max'] = settings.OVERVIEW_LABELS_FONT_SIZE_MAX

    c['adjust_inflation_in_overview'] = True
    if hasattr(settings, 'ADJUST_INFLATION_IN_OVERVIEW'):
        c['adjust_inflation_in_overview'] = settings.ADJUST_INFLATION_IN_OVERVIEW

    c['show_overview_subtotals'] = False
    if hasattr(settings, 'SHOW_OVERVIEW_SUBTOTALS'):
        c['show_overview_subtotals'] = settings.SHOW_OVERVIEW_SUBTOTALS

    c['calculate_budget_indicators'] = True
    if hasattr(settings, 'CALCULATE_BUDGET_INDICATORS'):
        c['calculate_budget_indicators'] = settings.CALCULATE_BUDGET_INDICATORS

    return render_response('budgets/index.html', c)
Beispiel #8
0
def articles_show(request, id, title, show_side, render_callback=None):
    # Get request context
    c = get_context(request, css_class='body-policies', title='')

    # Retrieve the entity to display
    main_entity = get_main_entity(c)

    # Extra request context info
    c['article_id'] = id
    c['article'] = EconomicCategory.objects.filter(
        budget__entity=main_entity,
        article=id,
        expense=(show_side == 'expense'))[0]

    # Ignore if possible the descriptions for execution data, they are truncated and ugly
    article_descriptions = {}

    def _populate_article_descriptions(column_name, item):
        if not item.actual or not item.uid() in article_descriptions:
            article_descriptions[item.uid()] = getattr(item, 'description')

    # Get the budget breakdown.
    # The functional one is used only when showing expenses.
    c['functional_breakdown'] = BudgetBreakdown(['policy', 'programme'])
    c['economic_breakdown'] = BudgetBreakdown(['heading', 'uid'])
    c['funding_breakdown'] = BudgetBreakdown(['source', 'fund'])
    c['institutional_breakdown'] = BudgetBreakdown(
        [_year_tagged_institution, _year_tagged_department])
    get_budget_breakdown(
        "ec.article = %s and e.id = %s", [id, main_entity.id], [
            c['functional_breakdown'], c['economic_breakdown'],
            c['funding_breakdown'], c['institutional_breakdown']
        ], _populate_article_descriptions)

    # Note we don't modify the original descriptions, we're working on a copy (of the hash,
    # which is made of references to the hashes containing the descriptions themselves).
    c['descriptions'] = Budget.objects.get_all_descriptions(main_entity).copy()
    article_descriptions.update(c['descriptions'][show_side])
    c['descriptions'][show_side] = article_descriptions
    c['name'] = c['descriptions'][show_side].get(c['article_id'])
    c['title_prefix'] = c['name']

    # Additional data needed by the view
    populate_stats(c)
    populate_years(c, 'institutional_breakdown')
    populate_budget_statuses(c, main_entity.id)
    populate_area_descriptions(c, ['functional', 'funding', show_side])
    _populate_csv_settings(c, 'article', id)
    _set_show_side(c, show_side)
    _set_full_breakdown(c, True)

    c['draftBudgetYear'] = draftBudgetYear

    return render(c, render_callback, 'policies/show.html')
Beispiel #9
0
def entities_show_helper(request, c, entity, render_callback=None):
    # Prepare the budget breakdowns
    c['breakdowns'] = {
        'financial_expense': BudgetBreakdown(),
        'functional': BudgetBreakdown(['policy', 'programme']),
        'institutional': get_institutional_breakdown(c) if c['show_global_institutional_treemap'] else None
    }
    if entity.level == settings.MAIN_ENTITY_LEVEL:
        c['breakdowns']['economic'] = BudgetBreakdown(['article', 'heading'])

        # We assume here that all items are properly configured across all dimensions
        # (and why wouldn't they? see below). Note that this is a particular case of the
        # more complex logic below for small entities, and I used for a while the more 
        # general code for all scenarios, until I realised performance was much worse,
        # as we do two expensive denormalize-the-whole-db queries!
        get_budget_breakdown(   "e.id = %s", [ entity.id ],
                                [c['breakdowns']['economic']],
                                get_financial_breakdown_callback(c, \
                                    [c['breakdowns']['functional'], \
                                    c['breakdowns']['institutional']]) )
    else:
        # Small entities have a varying level of detail: often we don't have any breakdown below
        # chapter, so we have to start there. Also, to be honest, the heading level doesn't add
        # much to what you get with articles.
        c['breakdowns']['economic'] = BudgetBreakdown(['chapter', 'article'])

        # For small entities we sometimes have separate functional and economic breakdowns as
        # input, so we can't just get all the items and add them up, as we would double count
        # the amounts.
        get_budget_breakdown(   "e.id = %s and fc.area <> 'X'", [ entity.id ],
                                [],
                                get_financial_breakdown_callback(c, \
                                    [c['breakdowns']['functional'], \
                                    c['breakdowns']['institutional']]) )
        get_budget_breakdown(   "e.id = %s and ec.chapter <> 'X'", [ entity.id ],
                                [ c['breakdowns']['economic'] ] )

    # Additional data needed by the view
    populate_level(c, entity.level)
    populate_entity_stats(c, entity)
    # TODO: We're doing this also for Aragon, check performance!
    populate_entity_descriptions(c, entity)
    populate_years(c, c['breakdowns']['economic'])
    populate_budget_statuses(c, entity.id)
    populate_area_descriptions(c, ['functional', 'income', 'expense', 'institutional'])
    set_full_breakdown(c, entity.level == settings.MAIN_ENTITY_LEVEL)
    c['entity'] = entity

    # if parameter widget defined use policies/widget template instead of policies/show
    template = 'entities/show_widget.html' if isWidget(request) else 'entities/show.html'

    return render(c, render_callback, template)
Beispiel #10
0
def __populate_summary_breakdowns(c, entity, from_year, to_year):
    payments_count = 0
    total_amount = 0

    # Get the list of biggest payees
    c['payee_breakdown'] = BudgetBreakdown(['payee'])
    for payee in Payment.objects.get_biggest_payees(entity, from_year, to_year,
                                                    50):
        # Wrap the database result in an object, so it can be handled by BudgetBreakdown
        payment = MockPayment()
        payment.payee = payee[0]
        payment.expense = True
        payment.amount = int(payee[2])

        c['payee_breakdown'].add_item('pagos', payment)

    # Get the area breakdown
    c['area_breakdown'] = BudgetBreakdown(['area'])
    for area in Payment.objects.get_area_breakdown(entity, from_year, to_year):
        # Wrap the database result in an object, so it can be handled by BudgetBreakdown
        payment = MockPayment()
        payment.area = area[0]
        payment.expense = True
        payment.amount = int(area[2])

        # We calculate the overall stats using the area breakdown. The payee one
        # doesn't include anonymised data.
        total_amount += payment.amount
        payments_count += int(area[1])

        c['area_breakdown'].add_item('pagos', payment)

    # Get the department breakdown
    c['department_breakdown'] = BudgetBreakdown(['department'])
    for department in Payment.objects.get_department_breakdown(
            entity, from_year, to_year):
        # Wrap the database result in an object, so it can be handled by BudgetBreakdown
        payment = MockPayment()
        payment.department = department[0]
        payment.expense = True
        payment.amount = int(department[2])

        c['department_breakdown'].add_item('pagos', payment)

    # Get basic stats for the overall dataset
    c['payments_count'] = payments_count
    c['total_amount'] = total_amount
    c['is_summary'] = True
Beispiel #11
0
def welcome(request):
    c = get_context(request, css_class='body-welcome', title=_('Inicio'))
    c['formatter'] = add_thousands_separator

    # Retrieve front page examples
    populate_latest_budget(c)
    c['featured_programmes'] = list(
        FunctionalCategory.objects.filter(budget=c['latest_budget']).filter(
            programme__in=settings.FEATURED_PROGRAMMES))

    # Decide whether we're going to show budget or execution figures
    use_actual = False
    for programme in c['featured_programmes']:
        if (BudgetItem.objects.filter(functional_category=programme).filter(
                budget__status='')  # Don't use partially executed budgets
                .filter(actual=True).count()) > 0:
            use_actual = True
            break

    # Calculate subtotals for the selected programmes
    c['breakdown'] = BudgetBreakdown(['programme'])
    for programme in c['featured_programmes']:
        for item in programme.budgetitem_set.filter(actual=use_actual):
            c['breakdown'].add_item(c['latest_budget'].year, item)

    return render_to_response('welcome/index.html', c)
Beispiel #12
0
def investments_show(request, id, title, render_callback=None):
    c = get_context(request,
                    css_class='body-investments',
                    title=_(u'Inversiones por distrito'))
    entity = get_main_entity(c)
    set_entity(c, entity)

    # Get area name
    c['area'] = GeographicCategory.objects.filter(budget__entity=entity,
                                                  code=id)[0]

    # Get the investments breakdown
    query = "gc.code = %s and e.id = %s"
    investments = Investment.objects.each_denormalized(query, [id, entity.id])
    c['area_breakdown'] = BudgetBreakdown(['policy', 'description'])
    for item in investments:
        column_name = year_column_name(item)
        c['area_breakdown'].add_item(column_name, item)

    # Get additional information
    populate_stats(c)
    populate_entity_descriptions(c, entity)
    populate_years(c, c['area_breakdown'])
    populate_budget_statuses(c, entity.id)

    # The per-capita format in investment pages is misleading, as it refers to the whole
    # entity population, not the particular districts/neighborhoods/areas, so we hide it.
    c['hide_per_capita_format'] = True

    # if parameter widget defined use policies/widget template instead of policies/show
    template = 'investments/show_widget.html' if isWidget(
        request) else 'investments/show.html'

    return render(c, render_callback, template)
Beispiel #13
0
def welcome(request):
    c = get_context(request, css_class='body-welcome', title=_('Inicio'))
    c['formatter'] = add_thousands_separator

    # Retrieve setting for number of examples to display in homepage
    c['number_of_featured_programmes'] = 3
    if hasattr(settings, 'NUMBER_OF_FEATURED_PROGRAMMES'):
        c['number_of_featured_programmes'] = settings.NUMBER_OF_FEATURED_PROGRAMMES

    # Retrieve front page examples
    populate_latest_budget(c)
    c['featured_programmes'] = list(
        FunctionalCategory.objects.filter(budget=c['latest_budget']).filter(
            programme__in=settings.FEATURED_PROGRAMMES).filter(
                subprogramme=None))

    # Decide whether we're going to show budget or execution figures
    use_actual = (
        BudgetItem.objects.filter(budget=c['latest_budget']).filter(
            budget__status='')  # Don't use partially executed budgets
        .filter(actual=True).count() > 0)

    # Calculate subtotals for the selected programmes
    c['breakdown'] = BudgetBreakdown(['programme'])
    items = BudgetItem.objects \
                        .filter(budget=c['latest_budget']) \
                        .filter(functional_category__programme__in=settings.FEATURED_PROGRAMMES) \
                        .filter(actual=use_actual) \
                        .select_related('functional_category')
    for item in items:
        c['breakdown'].add_item(c['latest_budget'].year, item)

    return render_response('welcome/index.html', c)
Beispiel #14
0
def entities_show(request, c, entity, render_callback=None):
    # Prepare the budget breakdowns
    c['financial_expense_breakdown'] = BudgetBreakdown()
    c['functional_breakdown'] = BudgetBreakdown(['policy', 'programme'])
    c['include_financial_chapters'] = hasattr(settings, 'INCLUDE_FINANCIAL_CHAPTERS_IN_BREAKDOWNS') and settings.INCLUDE_FINANCIAL_CHAPTERS_IN_BREAKDOWNS
    if entity.level == settings.MAIN_ENTITY_LEVEL:
        c['economic_breakdown'] = BudgetBreakdown(['article', 'heading'])

        # We assume here that all items are properly configured across all dimensions
        # (and why wouldn't they? see below). Note that this is a particular case of the
        # more complex logic below for small entities, and I used for a while the more 
        # general code for all scenarios, until I realised performance was much worse,
        # as we do two expensive denormalize-the-whole-db queries!
        get_budget_breakdown(   "e.id = %s", [ entity.id ],
                                [c['economic_breakdown']],
                                get_financial_breakdown_callback(c) )
    else:
        # Small entities have a varying level of detail: often we don't have any breakdown below
        # chapter, so we have to start there. Also, to be honest, the heading level doesn't add
        # much to what you get with articles.
        c['economic_breakdown'] = BudgetBreakdown(['chapter', 'article'])

        # For small entities we sometimes have separate functional and economic breakdowns as
        # input, so we can't just get all the items and add them up, as we would double count
        # the amounts.
        get_budget_breakdown(   "e.id = %s and fc.area <> 'X'", [ entity.id ],
                                [],
                                get_financial_breakdown_callback(c) )
        get_budget_breakdown(   "e.id = %s and ec.chapter <> 'X'", [ entity.id ],
                                [ c['economic_breakdown'] ] )

    # Additional data needed by the view
    populate_level(c, entity.level)
    populate_entity_stats(c, entity)
    # TODO: We're doing this also for Aragon, check performance!
    populate_entity_descriptions(c, entity)
    populate_years(c, 'economic_breakdown')
    populate_budget_statuses(c, entity.id)
    populate_area_descriptions(c, ['functional', 'income', 'expense'])
    c['display_functional_view'] = True
    _set_full_breakdown(c, entity.level == settings.MAIN_ENTITY_LEVEL)
    c['entity'] = entity
    
    c['draftBudgetYear'] = draftBudgetYear

    return render(c, render_callback, 'entities/show.html')
Beispiel #15
0
def __populate_detailed_breakdowns(c, active_filters):
    # Read settings on how to structure the search results...
    breakdown_by_payee_criteria = ['payee', 'area', 'description']
    if hasattr(settings, 'PAYMENTS_BREAKDOWN_BY_PAYEE'):
        breakdown_by_payee_criteria = settings.PAYMENTS_BREAKDOWN_BY_PAYEE

    breakdown_by_area_criteria = ['area', 'payee', 'description']
    if hasattr(settings, 'PAYMENTS_BREAKDOWN_BY_AREA'):
        breakdown_by_area_criteria = settings.PAYMENTS_BREAKDOWN_BY_AREA

    breakdown_by_department_criteria = ['department', 'payee', 'description']

    # But, before moving forward, remove from the search results those criteria
    # that are being used to filter, as they are redundant.
    for filter in active_filters:
        if filter in breakdown_by_area_criteria:
            breakdown_by_area_criteria.remove(filter)
        if filter in breakdown_by_payee_criteria:
            breakdown_by_payee_criteria.remove(filter)
        if filter in breakdown_by_department_criteria:
            breakdown_by_department_criteria.remove(filter)

    # We're ready to create the breakdowns and move forward.
    c['payee_breakdown'] = BudgetBreakdown(breakdown_by_payee_criteria)
    c['area_breakdown'] = BudgetBreakdown(breakdown_by_area_criteria)
    c['department_breakdown'] = BudgetBreakdown(
        breakdown_by_department_criteria)

    payments_count = 0
    for item in c['payments']:
        # We add the date to the description, if it exists:
        # TODO: I wanted the date to be in a separate column, but it's complicated right
        # now the way BudgetBreakdown works. Need to think about it
        if item.date:
            item.description = item.description + ' (' + str(item.date) + ')'

        c['payee_breakdown'].add_item('pagos', item)
        c['area_breakdown'].add_item('pagos', item)
        c['department_breakdown'].add_item('pagos', item)
        payments_count += 1

    # Get basic stats for the overall dataset
    c['payments_count'] = payments_count
    c['total_amount'] = c['payee_breakdown'].total_expense[
        'pagos'] if payments_count > 0 else 0
    c['is_summary'] = False
Beispiel #16
0
def policies_show(request, id, title, render_callback=None):
    # Get request context
    c = get_context(request, css_class='body-policies', title='')
    c['policy_uid'] = id

    # Retrieve the entity to display
    main_entity = get_main_entity(c)

    # Get the budget breakdown
    c['functional_breakdown'] = BudgetBreakdown(['programme'])
    c['economic_breakdown'] = BudgetBreakdown(
        ['chapter', 'article', 'heading'])
    c['funding_breakdown'] = BudgetBreakdown(['source', 'fund'])
    c['institutional_breakdown'] = BudgetBreakdown(
        [_year_tagged_institution, _year_tagged_department])
    get_budget_breakdown(
        "fc.policy = %s and e.id = %s", [id, main_entity.id], [
            c['functional_breakdown'], c['economic_breakdown'],
            c['funding_breakdown'], c['institutional_breakdown']
        ])

    # Additional data needed by the view
    show_side = 'expense'
    populate_stats(c)
    populate_entity_descriptions(c, main_entity)
    populate_years(c, 'functional_breakdown')
    populate_budget_statuses(c, main_entity.id)
    populate_area_descriptions(c, ['functional', 'funding', show_side])
    _populate_csv_settings(c, 'policy', id)
    _set_show_side(c, show_side)
    _set_full_breakdown(c, True)

    c['name'] = c['descriptions']['functional'].get(c['policy_uid'])
    c['title_prefix'] = c['name']

    c['draftBudgetYear'] = draftBudgetYear

    return render(c, render_callback, 'policies/show.html')
Beispiel #17
0
def tax_receipt(request):
    c = get_context(request, css_class='body-tax-receipt', title='')

    # Get latest budget data
    populate_latest_budget(c)
    populate_descriptions(c)
    c['default_income'] = 30000

    # Get the budget breakdown
    c['breakdown'] = BudgetBreakdown(['policy', 'programme'])
    for item in BudgetItem.objects.each_denormalized("b.id = %s",
                                                     [c['latest_budget'].id]):
        c['breakdown'].add_item(c['latest_budget'].name(), item)

    return render_to_response('tax_receipt/index.html', c)
Beispiel #18
0
def tax_receipt(request):
    c = get_context(request, css_class='body-tax-receipt', title=_(u'Lo que tú aportas'))

    # Get latest budget data
    populate_latest_budget(c)
    populate_stats(c)
    populate_descriptions(c)
    c['default_income'] = 30000

    # Get the budget breakdown
    c['breakdown'] = BudgetBreakdown(['policy', 'programme'])
    for item in BudgetItem.objects.each_denormalized("b.id = %s", [c['latest_budget'].id]):
        if c['include_financial_chapters'] or not item.is_financial():
            c['breakdown'].add_item(c['latest_budget'].name(), item)

    return render_response('tax_receipt/index.html', c)
Beispiel #19
0
def entities_index(request, c, level, render_callback=None):
    # Get the budget breakdown
    c['economic_breakdown'] = BudgetBreakdown(['name'])
    # The top level entity has a nicely broken down budget, where each item is classified across
    # 4 dimensions. For smaller entities, however, we have two separate breakdowns as input,
    # that are loaded separately, with dummy values ('X') assigned to the three unknown dimensions.
    # To avoid double counting, we must calculate breakdowns along a dimension including only
    # those items for which we know the category (i.e. not 'X')
    get_budget_breakdown("e.level = %s and ec.chapter <> 'X'", [level],
                         [c['economic_breakdown']])

    # Additional data needed by the view
    populate_level(c, level)
    populate_level_stats(c, level)
    populate_years(c, 'economic_breakdown')
    populate_entities(c, level)

    # XXX: The percentage format in pages listing entities is tricky and confusing, partly because
    # we have many gaps in the data which vary each year, so I'm hiding the drop-down option for now.
    c['hide_percentage_format'] = True

    return render(c, render_callback, 'entities/index.html')
Beispiel #20
0
def sections_show(request, id, title, render_callback=None):
    # Get request context
    c = get_context(request, css_class='body-policies body-sections', title='')

    # Retrieve the entity to display
    main_entity = get_main_entity(c)

    # Extra request context info
    c['section_id'] = id
    c['section'] = InstitutionalCategory.objects.filter(
        budget__entity=main_entity, department=id)[0]

    # Ignore if possible the descriptions for execution data, they are truncated and ugly
    programme_descriptions = {}

    def _populate_programme_descriptions(column_name, item):
        item_uid = getattr(item, get_final_element_grouping(c))()
        if not item.actual or not item_uid in programme_descriptions:
            programme_descriptions[item_uid] = getattr(item, 'description')

    # Get the budget breakdown
    c['breakdowns'] = {
        'functional':
        BudgetBreakdown(['policy', 'programme']),
        'economic':
        BudgetBreakdown(
            ['chapter', 'article', 'heading',
             get_final_element_grouping(c)]),
        'institutional':
        None
    }
    get_budget_breakdown(
        "ic.department = %s and e.id = %s and i.expense = true",
        [id, main_entity.id], [
            c['breakdowns']['functional'],
            c['breakdowns']['economic'],
        ], _populate_programme_descriptions)

    # Note we don't modify the original descriptions, we're working on a copy (of the hash,
    # which is made of references to the hashes containing the descriptions themselves).
    c['descriptions'] = Budget.objects.get_all_descriptions(main_entity).copy()
    programme_descriptions.update(c['descriptions']['expense'])
    c['descriptions']['economic'] = programme_descriptions
    c['name'] = c['descriptions']['institutional'].get(c['section_id'])
    c['title_prefix'] = c['name']

    # Additional data needed by the view
    show_side = 'expense'
    populate_stats(c)
    populate_years(c, c['breakdowns']['economic'])
    populate_budget_statuses(c, main_entity.id)
    populate_area_descriptions(c, ['functional', show_side])
    populate_csv_settings(c, 'section', id)
    set_show_side(c, show_side)
    set_full_breakdown(c, True)
    set_starting_tab(c, 'functional')

    # Back button: specify which tab in the main page to go to
    c['back_to_tab'] = 'institutional'

    # if parameter widget defined use policies/widget template instead of policies/show
    template = 'policies/show_widget.html' if isWidget(
        request) else 'policies/show.html'

    return render(c, render_callback, template)
Beispiel #21
0
def subprogrammes_show(request, id, title, render_callback=None):
    # Get request context
    c = get_context(request, css_class='body-policies body-subprogrammes', title='')

    # Retrieve the entity to display
    main_entity = get_main_entity(c)

    # Extra request context info
    c['subprogramme_id'] = id
    subprogramme = FunctionalCategory.objects.filter(budget__entity=main_entity,
                                                        subprogramme=id)[0]
    c['programme'] = FunctionalCategory.objects.filter(budget__entity=main_entity,
                                                        programme=subprogramme.programme,
                                                        subprogramme__isnull=True)[0]
    # The policy object is needed for the breadcrumb only
    c['policy'] = FunctionalCategory.objects.filter(budget__entity=main_entity,
                                                    policy=subprogramme.policy,
                                                    programme__isnull=True)[0]

    # Ignore if possible the descriptions for execution data, they are truncated and ugly
    programme_descriptions = {}
    def _populate_programme_descriptions(column_name, item):
        item_uid = getattr(item, get_final_element_grouping(c))()
        if not item.actual or not item_uid in programme_descriptions:
            programme_descriptions[item_uid] = getattr(item, 'description')

    # Get the budget breakdown
    c['breakdowns'] = {
      'economic': BudgetBreakdown(['chapter', 'article', 'heading', get_final_element_grouping(c)]),
      'funding': BudgetBreakdown(['source', 'fund']) if c['show_funding_tab'] else None,
      'institutional': get_institutional_breakdown(c) if c['show_institutional_tab'] else None
    }
    get_budget_breakdown(   "fc.subprogramme = %s and e.id = %s", [ id, main_entity.id ],
                            [ 
                                c['breakdowns']['economic'],
                                c['breakdowns']['funding'],
                                c['breakdowns']['institutional']
                            ],
                            _populate_programme_descriptions)

    # Note we don't modify the original descriptions, we're working on a copy (of the hash,
    # which is made of references to the hashes containing the descriptions themselves).
    c['descriptions'] = Budget.objects.get_all_descriptions(main_entity).copy()
    programme_descriptions.update(c['descriptions']['expense'])
    c['descriptions']['economic'] = programme_descriptions
    c['name'] = c['descriptions']['functional'].get(c['subprogramme_id'])
    c['title_prefix'] = c['name']

    # Additional data needed by the view
    show_side = 'expense'
    populate_stats(c)
    populate_years(c, c['breakdowns']['economic'])
    populate_budget_statuses(c, main_entity.id)
    populate_area_descriptions(c, ['functional', 'funding', show_side])
    populate_csv_settings(c, 'subprogramme', id)
    set_show_side(c, show_side)
    set_full_breakdown(c, True)
    set_starting_tab(c, 'economic')

    # Back button: go back to parent programme
    c['back_button'] = {
        'url': reverse('budget_app.views.programmes_show', args=[subprogramme.programme, c['programme'].slug()]),
        'description': c['descriptions']['functional'].get(subprogramme.programme)
    }

    # if parameter widget defined use policies/widget template instead of policies/show
    template = 'policies/show_widget.html' if isWidget(request) else 'policies/show.html'

    return render(c, render_callback, template )
Beispiel #22
0
def budgets(request, render_callback=None):
    # Get request context
    c = get_context(request, css_class='body-summary', title=_(u'Visión global'))

    # Retrieve the entity to display
    main_entity = get_main_entity(c)

    # Income/expense breakdown
    c['breakdowns'] = {
        'functional': BudgetBreakdown(['policy', 'programme']),
        'economic': BudgetBreakdown(['article', 'heading']),
        'chapter': BudgetBreakdown(['chapter']) # Used for indicators
    }
    for item in BudgetItem.objects.each_denormalized("e.id = %s", [main_entity.id]):
        column_name = year_column_name(item)
        c['breakdowns']['chapter'].add_item(column_name, item)
        if c['include_financial_chapters'] or not item.is_financial():
            c['breakdowns']['functional'].add_item(column_name, item)
            c['breakdowns']['economic'].add_item(column_name, item)

    # Additional data needed by the view
    populate_stats(c)
    populate_descriptions(c)
    populate_budget_statuses(c, main_entity)
    populate_years(c, c['breakdowns']['functional'])

    # The percentage format in the Overview page is redundant for the Sankey and gets very
    # confusing when comparing budget vs actual figures, so we hide it.
    c['hide_percentage_format'] = True
    # XXX: Now, the per capita format may make sense, but since we're adding the format
    # controller late in the game (#602), we'll start just with nominal vs. real. Once the
    # infrastructure is in place it really wouldn't be that hard to add a third format.
    c['hide_per_capita_format'] = True


    c['income_nodes'] = json.dumps(settings.OVERVIEW_INCOME_NODES)
    c['expense_nodes'] = json.dumps(settings.OVERVIEW_EXPENSE_NODES)

    if hasattr(settings, 'OVERVIEW_RELAX_FACTOR'):
        c['relax_factor'] = settings.OVERVIEW_RELAX_FACTOR
    if hasattr(settings, 'OVERVIEW_NODE_PADDING'):
        c['overview_node_padding'] = settings.OVERVIEW_NODE_PADDING
    if hasattr(settings, 'OVERVIEW_FORCE_ORDER'):
        c['overview_force_order'] = settings.OVERVIEW_FORCE_ORDER

    if hasattr(settings, 'OVERVIEW_LABELS_MIN_SIZE'):
        c['overview_labels_min_size'] = settings.OVERVIEW_LABELS_MIN_SIZE
    if hasattr(settings, 'OVERVIEW_LABELS_FONT_SIZE_MIN'):
        c['overview_labels_font_size_min'] = settings.OVERVIEW_LABELS_FONT_SIZE_MIN
    if hasattr(settings, 'OVERVIEW_LABELS_FONT_SIZE_MAX'):
        c['overview_labels_font_size_max'] = settings.OVERVIEW_LABELS_FONT_SIZE_MAX

    c['show_overview_subtotals'] = False
    if hasattr(settings, 'SHOW_OVERVIEW_SUBTOTALS'):
        c['show_overview_subtotals'] = settings.SHOW_OVERVIEW_SUBTOTALS

    c['calculate_budget_indicators'] = True
    if hasattr(settings, 'CALCULATE_BUDGET_INDICATORS'):
        c['calculate_budget_indicators'] = settings.CALCULATE_BUDGET_INDICATORS

     # if parameter widget defined use widget template instead of standard one
    template = 'budgets/index_widget.html' if isWidget(request) else 'budgets/index.html'

    return render(c, render_callback, template)
Beispiel #23
0
def get_institutional_breakdown(c):
    consistent_institutional_codes = hasattr(settings, 'CONSISTENT_INSTITUTIONAL_CODES') and settings.CONSISTENT_INSTITUTIONAL_CODES
    if consistent_institutional_codes:
        return BudgetBreakdown(['institution', 'department'])
    else:
        return BudgetBreakdown([_get_year_tagged_institution, _get_year_tagged_department])
Beispiel #24
0
def entities_show_article(request, c, entity, id, title, show_side, render_callback=None):
    # Get request context
    c = get_context(request, css_class='body-policies', title='')
    c['article_id'] = id
    c['is_chapter'] = len(id) <= 1
    if c['is_chapter']:
        c['article'] = EconomicCategory.objects.filter( budget__entity=entity,
                                                        chapter=id, 
                                                        expense=(show_side=='expense'))[0]
    else:
        c['article'] = EconomicCategory.objects.filter( budget__entity=entity,
                                                        article=id, 
                                                        expense=(show_side=='expense'))[0]

    # Ignore if possible the descriptions for execution data, they are truncated and ugly
    article_descriptions = {}
    def _populate_article_descriptions(column_name, item):
        if not item.actual or not item.uid() in article_descriptions:
            article_descriptions[item.uid()] = getattr(item, 'description')

    # Get the budget breakdown.
    # The functional breakdown is an empty one because our small entity data is not fully broken.
    c['breakdowns'] = {
      'functional': None,
      'funding': BudgetBreakdown(['source', 'fund']) if c['show_funding_tab'] else None,
      'institutional': get_institutional_breakdown(c) if c['show_institutional_tab'] else None
    }
    if c['is_chapter']:
        # XXX: Some entities combine different levels of data detail along the years. Trying
        # to display detailed categories (articles, headings) looks bad on the visualization,
        # because some years just 'disappear'. So we take the 'safe route', just visualizing
        # the chapter total. We could try to be smarter here.
        c['breakdowns']['economic'] = BudgetBreakdown(['chapter', 'article'])
        query = "ec.chapter = %s and e.id = %s"
    else:
        c['breakdowns']['economic'] = BudgetBreakdown(['heading', 'uid'])
        query = "ec.article = %s and e.id = %s"
    get_budget_breakdown(   query, [ id, entity.id ],
                            [ 
                                c['breakdowns']['economic'],
                                c['breakdowns']['funding'],
                                c['breakdowns']['institutional']
                            ],
                            _populate_article_descriptions)

    # Note we don't modify the original descriptions, we're working on a copy (of the hash,
    # which is made of references to the hashes containing the descriptions themselves).
    # TODO: Review how we're handling descriptions here for smaller entities
    c['descriptions'] = Budget.objects.get_all_descriptions(entity).copy()
    article_descriptions.update(c['descriptions'][show_side])
    c['descriptions'][show_side] = article_descriptions
    c['name'] = c['descriptions'][show_side].get(c['article_id'])
    c['title_prefix'] = c['name'] + ' - ' + entity.name

    # Additional data needed by the view
    populate_level(c, entity.level)
    populate_entity_stats(c, entity)
    populate_years(c, c['breakdowns']['institutional'])
    populate_budget_statuses(c, entity.id)
    populate_area_descriptions(c, ['functional', 'funding', show_side])
    populate_csv_settings(c, 'article', id)
    set_show_side(c, show_side)
    set_full_breakdown(c, False)
    c['entity'] = entity

    return render(c, render_callback, 'policies/show.html')
Beispiel #25
0
def get_institutional_breakdown(c):
    if c['consistent_institutional_codes']:
        return BudgetBreakdown(['institution', 'department'])
    else:
        return BudgetBreakdown([_get_year_tagged_institution, _get_year_tagged_department])