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

DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateSale`(IN vSale BIGINT)
proc: BEGIN
-- OBSOLETO USAR: sale_calculateComponent(vSale, NULL)
	DECLARE vShipped DATE; 
	DECLARE vWarehouseFk SMALLINT;
    DECLARE vAgencyModeFk INT;
    DECLARE vAddressFk INT;
    DECLARE vTicket BIGINT;
    DECLARE vItem BIGINT;
    DECLARE vLanded DATE; 
    DECLARE vTicketFree BOOLEAN DEFAULT TRUE;
    DECLARE vZoneFk INTEGER;
    
	SELECT  NOT (t.refFk IS NOT NULL OR ts.alertLevel > 0) OR s.price = 0, s.ticketFk, s.itemFk , t.zoneFk
			INTO vTicketFree, vTicket, vItem, vZoneFk
		FROM vn.ticket t
			JOIN vn.sale s ON s.ticketFk = t.id
			LEFT JOIN vn.ticketState ts ON ts.ticketFk = t.id
		WHERE s.id = vSale
		LIMIT 1;
    	
	SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.agencyModeFk, t.landed
			INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded
		FROM agencyMode a 
			JOIN ticket t ON t.agencyModeFk = a.id
		WHERE t.id = vTicket;

    IF IFNULL(vZoneFk,0) = 0 THEN
		CALL util.throw('ticket dont have zone');
    END IF;
    
    CALL buyUltimate (vWarehouseFk, vShipped);  
    
	DELETE FROM tmp.buyUltimate WHERE itemFk != vItem;
    
    DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
    CREATE TEMPORARY TABLE tmp.ticketLot 
		SELECT vWarehouseFk warehouseFk, NULL available, vItem itemFk, buyFk, vZoneFk zoneFk
				FROM tmp.buyUltimate
				WHERE itemFk = vItem;
                
    CALL vn.catalog_componentCalculate;            
	CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk);

    DROP TEMPORARY TABLE IF EXISTS tmp.sale;
	CREATE TEMPORARY TABLE tmp.sale
					(PRIMARY KEY (saleFk)) ENGINE = MEMORY
		SELECT vSale saleFk,vWarehouseFk warehouseFk;
                
	CALL ticketComponentUpdateSale(IF(vTicketFree,1,6)); 

	INSERT INTO vn.ticketLog (originFk, userFk, `action`, description)
		VALUES (vTicket, account.userGetId(), 'update', CONCAT('Bionizo linea id ', vSale));
	
	DROP TEMPORARY TABLE tmp.buyUltimate;
    DROP TEMPORARY TABLE IF EXISTS tmp.sale;
    CALL catalog_componentPurge();
    
END$$

DELIMITER ;

