DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`ticket_getMovable`(
	vTicketFk INT,
	vNewShipped DATETIME,
	vWarehouseFk INT
)
BEGIN
/**
 * Cálcula el stock movible para los artículos de un ticket
 * vNewShipped debe ser menor que vOldShipped, en los otros casos se
 * asume que siempre es posible
 *
 * @param vTicketFk -> Ticket
 * @param vNewShipped -> Nueva fecha
 * @return Sales con Movible
*/
    DECLARE vOldShipped DATETIME;

    SELECT t.shipped INTO vOldShipped
        FROM ticket t
        WHERE t.id = vTicketFk;

	-- Añadimos un dia más para calcular el stock hasta vNewShipped inclusive
    CALL item_getStock(vWarehouseFk, vNewShipped, NULL);
    CALL item_getMinacum(
		vWarehouseFk,
		vNewShipped,
		DATEDIFF(DATE_SUB(vOldShipped, INTERVAL 1 DAY), vNewShipped),
		NULL
	);

    SELECT s.id,
			s.itemFk,
			s.quantity,
			s.concept,
			s.price,
			s.foreignPrice,
			s.reserved,
			s.discount,
			i.image,
			i.subName,
			IFNULL(il.stock,0) + IFNULL(im.amount, 0) AS movable
        FROM ticket t
            JOIN sale s ON s.ticketFk = t.id
            JOIN item i ON i.id = s.itemFk
            LEFT JOIN tmp.itemMinacum im ON im.itemFk = s.itemFk
				AND im.warehouseFk = vWarehouseFk
            LEFT JOIN tmp.itemList il ON il.itemFk = s.itemFk
        WHERE t.id = vTicketFk;

    DROP TEMPORARY TABLE IF EXISTS
        tmp.itemList,
        tmp.itemMinacum;

END$$
DELIMITER ;
