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

DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `ticket_recalcComponentsForcePrice`(IN vTicketFk BIGINT, vIsTicketEditable BOOLEAN )
proc: BEGIN

/**
 * Este procedimiento trata de "rebionizar" un ticket, 
 * eliminando los componentes existentes e insertandolos de nuevo
 *
 * @param vTicketFk Id del ticket
 * @return tmp.buyUltimate
 */
	DECLARE vShipped DATE;
	DECLARE vWarehouseFk SMALLINT;
    DECLARE vAgencyModeFk INT;
    DECLARE vAddressFk INT;
    DECLARE vLanded DATE;
    DECLARE vZoneFk INTEGER;
    
    IF vIsTicketEditable IS NULL THEN
		SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE, t.zoneFk
			INTO vIsTicketEditable, vZoneFk
			FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket
			WHERE id = vTicketFk;
	END IF;
	SELECT warehouseFk, date(shipped), addressFk, agencyModeFk, landed
			INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded
		FROM ticket
		WHERE id = vTicketFk;
	
    CALL zone_getShipped (vLanded, vAddressFk, vAgencyModeFk, TRUE);
	
    CALL buyUltimate (vWarehouseFk, vShipped);  -- rellena la tabla buyUltimate con la ultima compra
	
    DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
    CREATE TEMPORARY TABLE tmp.ticketLot 
	SELECT vWarehouseFk warehouseFk, NULL available,
		s.itemFk, bu.buyFk, vZoneFk zoneFk
			FROM sale s
				LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk
			WHERE s.ticketFk = vTicketFk 
			GROUP BY s.itemFk;
	
	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 id saleFk, vWarehouseFk warehouseFk
                  FROM sale s
                  WHERE s.ticketFk = vTicketFk;  
                                    
	CALL ticketComponentUpdateSale(IF(vIsTicketEditable,1,6)); -- si el ticket esta facturado, respeta los precios
    
	IF vLanded IS NULL THEN

		CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk);
        
        UPDATE vn2008.Tickets t
			SET t.landing = (SELECT landed FROM tmp.zoneGetLanded) 
			WHERE Id_Ticket = vTicketFk;
            
		DROP TEMPORARY TABLE tmp.zoneGetLanded;

    END IF;
    
	DROP TEMPORARY TABLE tmp.buyUltimate;
    DROP TEMPORARY TABLE tmp.ticketComponentPrice;
    DROP TEMPORARY TABLE tmp.ticketComponent;
    DROP TEMPORARY TABLE tmp.sale;
END$$

DELIMITER ;

