USE `vn`;
DROP procedure IF EXISTS `ticketClosure`;

DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosure`()
BEGIN
/**
 * Realiza el cierre de todos los 
 * tickets de la table ticketClosure.
 */
	DECLARE vDone BOOL;
	DECLARE vClientFk INT;
	DECLARE vTicketFk INT;
	DECLARE vIsTaxDataChecked BOOL;
	DECLARE vCompanyFk INT;
	DECLARE vShipped DATE;
	DECLARE vPriority INT DEFAULT 1;
	DECLARE vReportDeliveryNote INT DEFAULT 1;
	DECLARE vNewInvoiceId INT;
	DECLARE vHasDailyInvoice BOOL;
	DECLARE vWithPackage BOOL;

	DECLARE cur CURSOR FOR
		SELECT ticketFk FROM tmp.ticketClosure;
		
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
	DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN
		RESIGNAL;
	END;

	DROP TEMPORARY TABLE IF EXISTS  tmp.ticketClosure2;
	CREATE TEMPORARY TABLE tmp.ticketClosure2
			SELECT ticketFk FROM tmp.ticketClosure;
	INSERT INTO tmp.ticketClosure 
			SELECT id FROM stowaway s 
				JOIN tmp.ticketClosure2 tc ON s.shipFk = tc.ticketFk;
	OPEN cur;

	proc: LOOP
		SET vDone = FALSE;
		
		FETCH cur INTO vTicketFk;

		IF vDone THEN
			LEAVE proc;
		END IF;

		-- ticketClosure start
		SELECT
				c.id,
				c.isTaxDataChecked,
				t.companyFk,
				t.shipped,
				co.hasDailyInvoice,
				w.isManaged
			INTO vClientFk,
				vIsTaxDataChecked,
				vCompanyFk, 
				vShipped,
				vHasDailyInvoice,
				vWithPackage
			FROM ticket t 
				JOIN `client` c ON c.id = t.clientFk
				JOIN province p ON p.id = c.provinceFk
				JOIN country co ON co.id = p.countryFk
				JOIN warehouse w ON w.id = t.warehouseFk
			WHERE t.id = vTicketFk;

		INSERT INTO ticketPackaging (ticketFk, packagingFk, quantity)
			(SELECT vTicketFk, p.id, COUNT(*)
				FROM expedition e 
					JOIN packaging p ON p.itemFk = e.itemFk
				WHERE e.ticketFk = vTicketFk AND p.isPackageReturnable
					AND vWithPackage
				GROUP BY p.itemFk);

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

			-- Facturacion rapida
			CALL ticketTrackingAdd(vTicketFk, 'DELIVERED', NULL);
			-- Facturar si está contabilizado
			IF vIsTaxDataChecked THEN
				CALL invoiceOut_newFromClient(
					vClientFk, 
					(SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')), 
					vShipped, 
					vCompanyFk, 
					NULL,
					vNewInvoiceId);
			END IF;
		ELSE
			-- Albaran_print
			CALL ticketTrackingAdd(vTicketFk, (SELECT vn.getAlert3State(vTicketFk)), NULL);
		END IF;
		
		-- ticketClosure end
	END LOOP;

	CLOSE cur;

	DROP TEMPORARY TABLE IF EXISTS  tmp.ticketClosure2;
END$$

DELIMITER ;

