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

DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateSale`(IN vSale BIGINT)
proc: BEGIN

/*
Este procedimiento bioniza una linea de movimiento
*/
	DECLARE vShipped DATE; 
	DECLARE vWarehouse SMALLINT;
    DECLARE vAgencyMode INT;
    DECLARE vAddress INT;
    DECLARE vTicket BIGINT;
    DECLARE vItem BIGINT;
    DECLARE vLanded DATE; 
    DECLARE vTicketFree BOOLEAN DEFAULT TRUE;
    
	SELECT FALSE
			INTO vTicketFree
		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
			AND (t.refFk != "" OR (ts.alertLevel > 0 AND s.price != 0))
		LIMIT 1;
        
    SELECT ticketFk, itemFk 
			INTO vTicket, vItem 
		FROM sale 
        WHERE id = vSale;
    	
	SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.agencyModeFk, t.landed
			INTO vWarehouse, vShipped, vAddress, vAgencyMode, vLanded
		FROM agencyMode a 
			JOIN ticket t ON t.agencyModeFk = a.id
		WHERE t.id = vTicket;
	
	DROP TEMPORARY TABLE IF EXISTS tmp.agencyHourGetShipped;
	CREATE TEMPORARY TABLE tmp.agencyHourGetShipped	ENGINE = MEMORY
		SELECT vWarehouse warehouseFk, vShipped shipped, vLanded landed;
    
    CALL buyUltimate (vWarehouse, vShipped);  -- rellena la tabla tmp.buyUltimate con la ultima compra
    
	DELETE FROM tmp.buyUltimate WHERE itemFk != vItem;
    
    DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
    CREATE TEMPORARY TABLE tmp.ticketLot 
		SELECT vWarehouse warehouseFk, NULL available, vItem itemFk, buyFk
				FROM tmp.buyUltimate
				WHERE itemFk = vItem;
                
	CALL ticketComponentCalculate(vAddress, vAgencyMode);

    DROP TEMPORARY TABLE IF EXISTS tmp.sale;
	CREATE TEMPORARY TABLE tmp.sale
					(PRIMARY KEY (saleFk)) ENGINE = MEMORY
		SELECT vSale saleFk,vWarehouse warehouseFk;
                
	CALL ticketComponentUpdateSale(IF(vTicketFree,1,6)); -- si el ticket esta facturado, respeta los precios

	-- Log
	INSERT INTO vn.ticketLog (originFk, userFk, `action`, description)
		VALUES (vTicket, account.userGetId(), 'update', CONCAT('Bionizo linea id ', vSale));

	-- Limpieza
	DROP TEMPORARY TABLE tmp.buyUltimate;
END$$

DELIMITER ;