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

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

/**
 * Este procedimiento recalcula los componentes de un ticket, 
 * eliminando los componentes existentes e insertandolos de nuevo
 *
 * @param vTicketFk Id del ticket
 * @param vIsTicketEditable si no se quiere forzar llamar con NULL
 */
	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 AND IFNULL(t.refFk,'') = ''
				INTO vIsTicketEditable
			FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket
			WHERE id = vTicketFk;
	END IF;

	SELECT t.warehouseFk, 
			t.shipped, 
			t.addressFk, 
            t.agencyModeFk, 
			t.landed,
			t.zoneFk
			INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded, vZoneFk
		FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket
		WHERE t.id = vTicketFk;

	IF vLanded IS NULL OR vZoneFk IS NULL THEN

		CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk, TRUE);

		IF (SELECT COUNT(*) FROM tmp.zoneGetLanded LIMIT 1) = 0 THEN
			CALL util.throw('There is no zone for these parameters');
		END IF;

		UPDATE ticket t
			SET t.landed = (SELECT landed FROM tmp.zoneGetLanded LIMIT 1) 
			WHERE t.id = vTicketFk AND t.landed IS NULL;

		IF vZoneFk IS NULL THEN
			SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetLanded LIMIT 1;
			UPDATE ticket t
				SET t.zoneFk = vZoneFk
				WHERE t.id = vTicketFk AND t.zoneFk IS NULL;
		END IF;
		DROP TEMPORARY TABLE tmp.zoneGetLanded;
		
	END IF;

	-- rellena la tabla buyUltimate con la ultima compra	
	CALL buyUltimate (vWarehouseFk, vShipped);  
	
    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;  
                  
	-- si el ticket esta facturado, respeta los precios                               
	CALL ticketComponentUpdateSale(IF(vIsTicketEditable, 1, 6)); 
    
    CALL catalog_componentPurge();
	DROP TEMPORARY TABLE 
		tmp.buyUltimate, 
		tmp.sale;
END$$

DELIMITER ;