<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
        xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
        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="101" author="jian">
        <sql dbms="mysql" endDelimiter=";;" splitStatements="true" stripComments="true">
            USE direct_delivery;;
            
            DROP PROCEDURE IF EXISTS sp_get_open_batch_count;;

            CREATE DEFINER='theorchard_dd'@'127.0.0.1' PROCEDURE sp_get_open_batch_count(IN dms_id INT, IN ord_type VARCHAR(50))
            BEGIN
                SELECT COUNT(DISTINCT db.delivery_batch_id) AS open_batches, 
                    SUM(IF(eqd.status IN ('ready_to_deliver','delivering','queued_for_delivery'), 1, 0)) AS open_jobs, 
                    MIN(db.priority) AS highest_priority
                FROM delivery_batch db
                INNER JOIN delivery_batch_detail dbd ON db.delivery_batch_id = dbd.delivery_batch_id
                INNER JOIN encoding_queue_detail eqd ON eqd.encoding_queue_detail_id = dbd.encoding_queue_detail_id
                WHERE db.dms_master_master_id = dms_id 
                    AND db.order_type = ord_type 
                    AND db.status = 'open';
            END;;
        </sql>
        <rollback>
            <sql dbms="mysql" endDelimiter=";;" splitStatements="true" stripComments="true">
                USE direct_delivery;;
                
                DROP PROCEDURE IF EXISTS sp_get_open_batch_count;;

                CREATE DEFINER='theorchard_dd'@'127.0.0.1' PROCEDURE sp_get_open_batch_count(IN dms_id INT, IN ord_type VARCHAR(50))
                BEGIN
                    SELECT COUNT(DISTINCT db.delivery_batch_id) AS open_batches, 
                        SUM(IF(eqd.status IN ('ready_to_deliver','delivering','queued_for_delivery'), 1, 0)) AS open_jobs
                    FROM delivery_batch db
                    INNER JOIN delivery_batch_detail dbd ON db.delivery_batch_id = dbd.delivery_batch_id
                    INNER JOIN encoding_queue_detail eqd ON eqd.encoding_queue_detail_id = dbd.encoding_queue_detail_id
                    WHERE db.dms_master_master_id = dms_id
                        AND db.order_type = ord_type
                        AND db.status = 'open';
                END;;
            </sql>
        </rollback>
    </changeSet>
</databaseChangeLog>
