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

DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateClon`(IN vTicketNew INT, vTicketOld INT)
BEGIN
/*
 * Recalcula los componentes un ticket clonado,
 * las lineas a precio cero fuerza para que tengan precio, el resto lo respeta
 * @param vTicketNew nuevo ticket clonado
 * @param vTicketOld icket original, a partir del qual se clonara el nuevo
*/
	DECLARE vShipped DATE;
	DECLARE vClient INT;
	DECLARE vWarehouse SMALLINT;
	DECLARE vAgencyMode INT;
	DECLARE vAddress INT;
	DECLARE vLanded DATE;
	DECLARE vAgency INT;
	DECLARE vZoneFk INT;

	REPLACE INTO orderTicket(orderFk,ticketFk)
		SELECT orderFk, vTicketNew 
			FROM orderTicket 
            WHERE ticketFk = vTicketOld;
    
	SELECT t.clientFk, t.warehouseFk, date(t.shipped), t.addressFk, t.agencyModeFk, t.landed, a.agencyFk, t.zoneFk
		INTO vClient, vWarehouse, vShipped, vAddress, vAgencyMode, vLanded, vAgency, vZoneFk
	FROM agencyMode a
		JOIN ticket t ON t.agencyModeFk = a.id
	WHERE t.id = vTicketNew;

	IF vLanded IS NULL THEN
		CALL zone_getLanded(vShipped, vAddress, vAgency, vWarehouse);
		UPDATE ticket t
				JOIN tmp.zoneGetLanded zgl ON t.warehouseFk = zgl.warehouseFk 
			SET t.landed = zgl.landed,
				t.zone = zgl.zoneFk
			WHERE t.id = vTicketNew;
		
		SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetLanded LIMIT 1;
		DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded;
	END IF;

	-- rellena la tabla tmp.buyUltimate con la ultima compra
	CALL buyUltimate(vWarehouse, vShipped);  

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
	CREATE TEMPORARY TABLE tmp.ticketLot 
		SELECT vWarehouse 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 = vTicketOld GROUP BY s.itemFk;
					
	CALL catalog_componentPrepare();            
	CALL catalog_componentCalculate(vZoneFk, vAddress, vAgencyMode, vWarehouse);

	-- Bionizamos lineas con Preu = 0
	DROP TEMPORARY TABLE IF EXISTS tmp.sale;
	CREATE TEMPORARY TABLE tmp.sale
				(PRIMARY KEY (saleFk)) ENGINE = MEMORY
			SELECT s.id saleFk, vWarehouse warehouseFk 
				FROM sale s
					JOIN ticket t on t.id = s.ticketFk WHERE s.ticketFk =  vTicketNew AND s.price = 0;
				
	CALL ticketComponentUpdateSale(1);

	-- Bionizamos lineas con Preu > 0
	DROP TEMPORARY TABLE IF EXISTS tmp.sale;
	CREATE TEMPORARY TABLE tmp.sale
				(PRIMARY KEY (saleFk)) ENGINE = MEMORY
			SELECT s.id saleFk, vWarehouse warehouseFk 
				FROM sale s 
					JOIN ticket t on t.id = s.ticketFk WHERE s.ticketFk =  vTicketNew
					AND s.price > 0;
				
	CALL ticketComponentUpdateSale(6);

	-- Log
	CALL `logAdd`(vTicketNew, 'update', ' ticket' , 'Bioniza Ticket');

	-- Limpieza
	CALL catalog_componentPurge();
	DROP TEMPORARY TABLE IF EXISTS 
		tmp.buyUltimate, 
		tmp.sale, 
		tmp.zoneGetLanded;
    
END$$

DELIMITER ;

