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

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

	DECLARE vShipped DATE; 
	DECLARE vWarehouseFk SMALLINT;
    DECLARE vAddressFk INT;
    DECLARE vTicket BIGINT;
    DECLARE vItem BIGINT;
    DECLARE vZoneFk INT;    
    
    SELECT ticketFk, itemFk 
			INTO vTicket, vItem 
		FROM sale 
        WHERE id = vSale;
    	
	SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.zoneFk
			INTO vWarehouseFk, vShipped, vAddressFk, vZoneFk
		FROM agencyMode a 
			JOIN ticket t ON t.agencyModeFk = a.id
		WHERE t.id = vTicket;
  
    IF vZoneFk IS NULL THEN
		CALL util.throw('ticket without 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 catalog_componentPrepare();
	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(1); 

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

DELIMITER ;

