DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`ticket_close`()
BEGIN
/**
 * Realiza el cierre de todos los
 * tickets de la tabla tmp.ticket_close.
 *
 * @table tmp.ticket_close(ticketFk) Identificadores de los tickets a cerrar
 */
	DECLARE vDone BOOL;
	DECLARE vClientFk INT;
    DECLARE vCurTicketFk INT;
	DECLARE vIsTaxDataChecked BOOL;
	DECLARE vCompanyFk INT;
	DECLARE vShipped DATE;
	DECLARE vNewInvoiceId INT;
	DECLARE vHasDailyInvoice BOOL;
	DECLARE vWithPackage BOOL;
    DECLARE vHasToInvoice BOOL;
	DECLARE vSerial VARCHAR(2);
	DECLARE vStateCode VARCHAR(45);

	DECLARE cur CURSOR FOR
		SELECT ticketFk FROM tmp.ticket_close;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
	DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN
		RESIGNAL;
	END;

	OPEN cur;

	proc: LOOP
		SET vDone = FALSE;

		FETCH cur INTO vCurTicketFk;

		IF vDone THEN
			LEAVE proc;
		END IF;

		SELECT
				c.id,
				c.isTaxDataChecked,
				t.companyFk,
				t.shipped,
				c.hasDailyInvoice,
				w.isManaged,
				c.hasToInvoice
			INTO vClientFk,
				vIsTaxDataChecked,
				vCompanyFk,
				vShipped,
				vHasDailyInvoice,
				vWithPackage,
				vHasToInvoice
			FROM ticket t
				JOIN `client` c ON c.id = t.clientFk
				JOIN warehouse w ON w.id = t.warehouseFk
			WHERE t.id = vCurTicketFk;

		INSERT INTO ticketPackaging (ticketFk, packagingFk, quantity)
			(SELECT vCurTicketFk, p.id, COUNT(*)
				FROM expedition e
					JOIN packaging p ON p.id = e.packagingFk
					JOIN ticket t ON t.id = e.ticketFk
					LEFT JOIN agencyMode am ON am.id = t.agencyModeFk
					LEFT JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
				WHERE e.ticketFk = vCurTicketFk AND p.isPackageReturnable
					AND vWithPackage
					AND NOT dm.`code`= 'PICKUP'
				GROUP BY p.itemFk);

		-- No retornables o no catalogados
		INSERT INTO sale (itemFk, ticketFk, concept, quantity, price, isPriceFixed)
			(SELECT e.freightItemFk, vCurTicketFk, i.name, COUNT(*) AS amount, getSpecialPrice(e.freightItemFk, vClientFk), 1
				FROM expedition e
					JOIN item i ON i.id = e.freightItemFk
					LEFT JOIN packaging p ON p.itemFk = i.id
				WHERE e.ticketFk = vCurTicketFk AND IFNULL(p.isPackageReturnable, 0) = 0
					AND getSpecialPrice(e.freightItemFk, vClientFk) > 0
				GROUP BY e.freightItemFk);


		IF vHasDailyInvoice AND vHasToInvoice THEN
			SET vStateCode = 'DELIVERED';
		ELSE
			SELECT vn.getAlert3State(vCurTicketFk) INTO vStateCode;
		END IF;
		CALL ticket_setState(vCurTicketFk, vStateCode);

	END LOOP;

	CLOSE cur;
END$$
DELIMITER ;
