# -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-03-16 05:11
from __future__ import unicode_literals

from django.db import migrations


class Migration(migrations.Migration):

    dependencies = [
        ('aims', '0055_currency_conversion_methods'),
    ]

    operations = [
        # View to hold Organisation Budgets by year & quarter, converted to USD
        migrations.RunSQL("""
            DROP VIEW IF EXISTS aims_organisation_budgets_usd;

            CREATE VIEW aims_organisation_budgets_usd AS (
                WITH budget_usd AS (
                    SELECT aims_organisation.code as code,
                        aims_activity.iati_identifier as iati_id,
                        aims_budget.id as budget_id, aims_budget.currency_id as curr_id,
                        DATE_PART('year', aims_budget.period_start) as year,
                        EXTRACT(QUARTER from date_trunc('quarter', aims_budget.period_start)) as quarter,
                        SUM(aims_budget.value) as tot_orig_value,
                        COALESCE(aims_currency_exchange_rate.rate, 1.00000000) as exch_rate_usd,
                        ROUND(COALESCE((SUM(aims_budget.value) * aims_currency_exchange_rate.rate), SUM(aims_budget.value)), 2) as tot_usd_value
                    FROM aims_organisation
                    JOIN aims_activity ON (aims_activity.reporting_organisation_id = aims_organisation.code)
                    JOIN aims_budget ON (aims_activity.iati_identifier = aims_budget.activity_id)
                    LEFT JOIN aims_budgetexchangerate ON (aims_budget.id = aims_budgetexchangerate.budget_id)
                    LEFT JOIN aims_currency_exchange_rate ON (aims_budgetexchangerate.exchangerate_id = aims_currency_exchange_rate.id)
                    GROUP BY code, aims_activity.iati_identifier, aims_budget.id, aims_budget.currency_id, aims_budget.period_start, aims_currency_exchange_rate.rate
                )
                SELECT  code,
                        to_char(year, '9999') as year,
                        to_char(quarter, '9') as quarter,
                        sum(tot_usd_value) as usd_value
                FROM budget_usd
                GROUP BY code, year, quarter
                ORDER BY year, quarter
            );
        """),
    ]
