<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
        xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
        xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.0.xsd
        http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd">
    <changeSet id="1" author="nlevkovich">
        <sql dbms="mysql" endDelimiter=";;" splitStatements="true" stripComments="true">
            <![CDATA[
                DROP PROCEDURE IF EXISTS `FlattenAndPopulateDigitalSales`;;

                CREATE DEFINER=`theorchard`@`10.10.%` PROCEDURE `FlattenAndPopulateDigitalSales`( IN loadPeriodID INTEGER )
                    DETERMINISTIC
                BEGIN
                    TRUNCATE TABLE TEMP_dig_sales_statements;
                    TRUNCATE TABLE TEMP_dig_sales_processed;
                    INSERT INTO TEMP_dig_sales_statements ( `statement_detail_id`, `statement_id`, `date`, `upc`, `cd`, `track_id`, `isrc`, `track_name`, `qty`, `unit_price`, `total`, `trans_type`, `retail_price`, `retail`, `period_id`, `customer_id`, `dms_name`, `vendor_id`, `owner`, `owner_id`, `activity_rate`, `original_currency_id` )
                        SELECT
                            dsd.*, IF(dsd.retail_price IS NULL OR dsd.retail_price = 0, 2*dsd.total, dsd.qty*dsd.retail_price) AS retail
                            , ds.period_id
                            , cm.customer_id
                            , cm.name AS dms_name
                            , v.vendor_id
                            , v.owner
                            , o.owner_id
                            , ds.activity_rate
                            , ds.original_currency_id
                        FROM dig_sales_detail dsd
                        LEFT JOIN processed_dig_sales pds ON pds.statement_detail_id = dsd.statement_detail_id AND pds.period_id = loadPeriodID
                        LEFT JOIN dig_sales_errors dse ON dse.statement_detail_id = dsd.statement_detail_id AND dse.period_id = loadPeriodID
                        INNER JOIN dig_sales ds ON dsd.statement_id = ds.statement_id
                        INNER JOIN customer_master cm ON cm.customer_id = ds.dms_customer_id
                        LEFT JOIN releases r ON dsd.upc = r.upc
                        LEFT JOIN artist_info a ON a.artist_id = r.artist_id
                        LEFT JOIN vendor v ON a.vendor_id = v.vendor_id
                        LEFT JOIN owner o ON o.owner_abbrivation = v.owner
                        WHERE ds.paid = 'Y' AND ds.period_id = loadPeriodID AND pds.statement_detail_id IS NULL AND dse.statement_detail_id IS NULL
                        GROUP BY dsd.statement_detail_id
                        ORDER BY o.owner_id, v.vendor_id, r.upc;
                    INSERT INTO TEMP_dig_sales_processed (`statement_detail_id`)
                        SELECT statement_detail_id FROM TEMP_dig_sales_statements;
                END;;
            ]]>
        </sql>
        <rollback>
            <sql dbms="mysql" endDelimiter=";;" splitStatements="true" stripComments="true">
                <![CDATA[
                DROP PROCEDURE IF EXISTS `FlattenAndPopulateDigitalSales`;;

                CREATE DEFINER=`ketan`@`10.10.%` PROCEDURE `FlattenAndPopulateDigitalSales`( IN loadPeriodID INTEGER )
                    DETERMINISTIC
                BEGIN
                    TRUNCATE TABLE TEMP_dig_sales_statements;
                    TRUNCATE TABLE TEMP_dig_sales_processed;
                    INSERT INTO TEMP_dig_sales_statements ( `statement_detail_id`, `statement_id`, `date`, `upc`, `cd`, `track_id`, `isrc`, `track_name`, `qty`, `unit_price`, `total`, `trans_type`, `retail_price`, `retail`, `period_id`, `customer_id`, `dms_name`, `vendor_id`, `owner`, `owner_id`, `activity_rate`, `original_currency_id` )
                        SELECT
                            dsd.*, IF(dsd.retail_price IS NULL OR dsd.retail_price = 0, 2*dsd.total, dsd.qty*dsd.retail_price) AS retail
                            , ds.period_id
                            , cm.customer_id
                            , cm.name AS dms_name
                            , v.vendor_id
                            , v.owner
                            , o.owner_id
                            , ds.activity_rate
                            , ds.original_currency_id
                        FROM dig_sales_detail dsd
                        LEFT JOIN processed_dig_sales pds ON pds.statement_detail_id = dsd.statement_detail_id AND pds.period_id = loadPeriodID
                        LEFT JOIN dig_sales_errors dse ON dse.statement_detail_id = dsd.statement_detail_id AND dse.period_id = loadPeriodID
                        INNER JOIN dig_sales ds ON dsd.statement_id = ds.statement_id
                        INNER JOIN customer_master cm ON cm.customer_id = ds.dms_customer_id
                        LEFT JOIN releases r ON dsd.upc = r.upc
                        LEFT JOIN artist_info a ON a.artist_id = r.artist_id
                        LEFT JOIN vendor v ON a.vendor_id = v.vendor_id
                        LEFT JOIN owner o ON o.owner_abbrivation = v.owner
                        WHERE ds.paid = 'Y' AND ds.period_id = loadPeriodID AND pds.statement_detail_id IS NULL AND dse.statement_detail_id IS NULL
                        GROUP BY dsd.statement_detail_id
                        ORDER BY o.owner_id, v.vendor_id, r.upc;
                    INSERT INTO TEMP_dig_sales_processed (`statement_detail_id`)
                        SELECT statement_detail_id FROM TEMP_dig_sales_statements;
                END;;
            ]]>
            </sql>
        </rollback>
    </changeSet>
    <changeSet id="2" author="nlevkovich">
        <sql dbms="mysql" endDelimiter=";;" splitStatements="true" stripComments="true">
            <![CDATA[
            DROP FUNCTION IF EXISTS `calculateFxSpread`;;
            CREATE DEFINER=`theorchard`@`10.10.%` FUNCTION calculateFxSpread(original INT, payout INT) RETURNS decimal(18,6)
                NO SQL
                DETERMINISTIC
                COMMENT 'Calculate Fx spread'
            BEGIN
                DECLARE output DECIMAL(18,6) DEFAULT 0.00;
                CASE
                    WHEN payout = original THEN SET output = 0.00;
                    WHEN ( ( payout = 5 AND original = 4 ) OR ( original = 5 AND payout = 4 ) ) THEN SET output = 0.02;
                    ELSE SET output = 0.05;
                END CASE;
            RETURN output;
            END;;
            ]]>
        </sql>
        <rollback>
            <sql dbms="mysql" endDelimiter=";;" splitStatements="true" stripComments="true">
                <![CDATA[
            DROP FUNCTION IF EXISTS `calculateFxSpread`;;
            CREATE DEFINER=`ketan`@`10.10.%` FUNCTION calculateFxSpread(original INT, payout INT) RETURNS decimal(18,6)
                NO SQL
                DETERMINISTIC
                COMMENT 'Calculate Fx spread'
            BEGIN
                DECLARE output DECIMAL(18,6) DEFAULT 0.00;
                CASE
                    WHEN payout = original THEN SET output = 0.00;
                    WHEN ( ( payout = 5 AND original = 4 ) OR ( original = 5 AND payout = 4 ) ) THEN SET output = 0.02;
                    ELSE SET output = 0.05;
                END CASE;
            RETURN output;
            END;;
            ]]>
            </sql>
        </rollback>
    </changeSet>
    <changeSet id="3" author="nlevkovich">
        <sql dbms="mysql" endDelimiter=";;" splitStatements="true" stripComments="true">
            <![CDATA[
            DROP FUNCTION IF EXISTS getCurrencyIDFromISOCode;;
            CREATE DEFINER=`theorchard`@`10.10.%` FUNCTION getCurrencyIDFromISOCode(IsoCode VARCHAR(10) ) RETURNS int(11)
                READS SQL DATA
                DETERMINISTIC
                COMMENT 'Given ISO code, function returns the currencyID'
            BEGIN
                DECLARE output INTEGER;
                SET output = ( SELECT id FROM currencies WHERE ISO_4217_code = IsoCode );
                RETURN output;
            END;;
            ]]>
        </sql>
        <rollback>
            <sql dbms="mysql" endDelimiter=";;" splitStatements="true" stripComments="true">
                <![CDATA[
            DROP FUNCTION IF EXISTS getCurrencyIDFromISOCode;;
            CREATE DEFINER=`ketan`@`10.10.%` FUNCTION getCurrencyIDFromISOCode(IsoCode VARCHAR(10) ) RETURNS int(11)
                READS SQL DATA
                DETERMINISTIC
                COMMENT 'Given ISO code, function returns the currencyID'
            BEGIN
                DECLARE output INTEGER;
                SET output = ( SELECT id FROM currencies WHERE ISO_4217_code = IsoCode );
                RETURN output;
            END;;
            ]]>
            </sql>
        </rollback>
    </changeSet>
    <changeSet id="4" author="nlevkovich">
        <sql dbms="mysql" endDelimiter=";;" splitStatements="true" stripComments="true">
            <![CDATA[
            DROP FUNCTION IF EXISTS getExchangeRate;;
            CREATE DEFINER=`theorchard`@`10.10.%` FUNCTION getExchangeRate(input_period_id INT, from_currency INT, to_currency INT ) RETURNS decimal(18,6)
                READS SQL DATA
                DETERMINISTIC
                COMMENT 'Get the exchange rate for a single period given a from and to cu'
            BEGIN
                DECLARE output DECIMAL(18,6) DEFAULT 0.00;
                DECLARE message VARCHAR(255);

                IF ( from_currency = to_currency ) THEN
                    RETURN 1.00;
                END IF;
                SET output = ( SELECT exchange_rate FROM currency_exchange_rates WHERE period_id = input_period_id AND currency_from_id = from_currency AND currency_to_id = to_currency );

                IF ABS( output ) < 0.000001 THEN
                    SET output = ( SELECT exchange_rate FROM currency_exchange_rates WHERE period_id = input_period_id AND currency_from_id = to_currency AND currency_to_id = from_currency );
                END IF;


                IF ABS( output ) < 0.000001 THEN
                    SET message = CONCAT( 'Trigger Error: Currency exchange rate ', getISOValue( from_currency ), '(', from_currency, ')', ' to ', getISOValue( to_currency ), '(', to_currency,')' ' not found for period id = ', input_period_id );
                    SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = message;
                END IF;
                RETURN output;
            END;;
            ]]>
        </sql>
        <rollback>
            <sql dbms="mysql" endDelimiter=";;" splitStatements="true" stripComments="true">
            <![CDATA[
            DROP FUNCTION IF EXISTS getExchangeRate;;
            CREATE DEFINER=`ketan`@`10.10.%` FUNCTION getExchangeRate(input_period_id INT, from_currency INT, to_currency INT ) RETURNS decimal(18,6)
                READS SQL DATA
                DETERMINISTIC
                COMMENT 'Get the exchange rate for a single period given a from and to cu'
            BEGIN
                DECLARE output DECIMAL(18,6) DEFAULT 0.00;
                DECLARE message VARCHAR(255);

                IF ( from_currency = to_currency ) THEN
                    RETURN 1.00;
                END IF;
                SET output = ( SELECT exchange_rate FROM currency_exchange_rates WHERE period_id = input_period_id AND currency_from_id = from_currency AND currency_to_id = to_currency );

                IF ABS( output ) < 0.000001 THEN
                    SET output = ( SELECT exchange_rate FROM currency_exchange_rates WHERE period_id = input_period_id AND currency_from_id = to_currency AND currency_to_id = from_currency );
                END IF;


                IF ABS( output ) < 0.000001 THEN
                    SET message = CONCAT( 'Trigger Error: Currency exchange rate ', getISOValue( from_currency ), '(', from_currency, ')', ' to ', getISOValue( to_currency ), '(', to_currency,')' ' not found for period id = ', input_period_id );
                    SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = message;
                END IF;
                RETURN output;
            END;;
            ]]>
            </sql>
        </rollback>
    </changeSet>
    <changeSet id="5" author="nlevkovich">
        <sql dbms="mysql" endDelimiter=";;" splitStatements="true" stripComments="true">
            <![CDATA[
            DROP FUNCTION IF EXISTS getISOValue;;
            CREATE DEFINER=`theorchard`@`10.10.%` FUNCTION getISOValue(currency_id INT) RETURNS varchar(10) CHARSET utf8
                READS SQL DATA
                DETERMINISTIC
                COMMENT 'Given currencyID, returns ISO code'
            BEGIN
                DECLARE output VARCHAR(10);
                SET output = ( SELECT ISO_4217_code FROM currencies WHERE id = currency_id );
                RETURN output;
            END;;
            ]]>
        </sql>
        <rollback>
            <sql dbms="mysql" endDelimiter=";;" splitStatements="true" stripComments="true">
                <![CDATA[
            DROP FUNCTION IF EXISTS getISOValue;;
            CREATE DEFINER=`ketan`@`10.10.%` FUNCTION getISOValue(currency_id INT) RETURNS varchar(10) CHARSET utf8
                READS SQL DATA
                DETERMINISTIC
                COMMENT 'Given currencyID, returns ISO code'
            BEGIN
                DECLARE output VARCHAR(10);
                SET output = ( SELECT ISO_4217_code FROM currencies WHERE id = currency_id );
                RETURN output;
            END;;
            ]]>
            </sql>
        </rollback>
    </changeSet>
</databaseChangeLog>