DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`clean`(IN `v_full` TINYINT(1))
proc: BEGIN
	DECLARE vDate DATETIME;
	DECLARE vDate18 DATETIME;
	DECLARE vDate26 DATETIME;
	DECLARE vDate8 DATE;
	DECLARE vDate6 DATE;
	DECLARE vDate3 DATE;
	DECLARE vDate2000 DATE;
	DECLARE vRangeDeleteTicket INT;
	DECLARE vStrtable VARCHAR(15) DEFAULT NULL;

	SET vDate = util.VN_CURDATE() - INTERVAL 2 MONTH;
	SET vDate18 = util.VN_CURDATE() - INTERVAL 18 MONTH;
	SET vDate26 = util.VN_CURDATE() - INTERVAL 26 MONTH;
	SET vDate3 = util.VN_CURDATE() - INTERVAL 3 MONTH;
	SET vDate8 = util.VN_CURDATE() - INTERVAL 8 DAY;
	SET vDate6 = util.VN_CURDATE() - INTERVAL 6 DAY;
	SET vDate2000 = util.VN_CURDATE() + INTERVAL (2000 - YEAR(util.VN_CURDATE())) YEAR;
	SET vRangeDeleteTicket = 60;

	DELETE FROM cdr WHERE calldate < vDate18;
	DELETE FROM mail WHERE DATE_ODBC < vDate;
	DELETE FROM Movimientos_mark WHERE odbc_date < vDate;
	DELETE FROM Splits WHERE Fecha < vDate18;

	DELETE tobs
		FROM movement_label tobs
			JOIN Movimientos m ON tobs.Id_Movimiento = m.Id_Movimiento
			JOIN vn.ticket t ON m.Id_Ticket = t.id 
		WHERE t.shipped < vDate;

	DELETE FROM Remesas WHERE `Fecha Remesa` < vDate18;

	DELETE tw.*
		FROM vn.ticketWeekly tw
			LEFT JOIN vn.sale s USING(ticketFk)
		WHERE s.id IS NULL;

	DELETE FROM cl_main WHERE Fecha < vDate18;
	DELETE FROM hedera.`order` WHERE date_send < vDate18;
	DELETE FROM vn.message WHERE sendDate < vDate;

	DELETE FROM cache.departure_limit WHERE Fecha < util.VN_CURDATE() - INTERVAL 1 MONTH;

	DELETE cm
		FROM Compres_mark cm
			JOIN Compres c ON c.Id_Compra = cm.Id_Compra
			JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada
			JOIN travel t ON t.id = e.travel_id
		WHERE t.landing <= vDate;

	IF v_full THEN
		CREATE OR REPLACE TEMPORARY TABLE tTicketDelete
			SELECT DISTINCT tl.originFk ticketFk
				FROM vn.ticketLog tl
					JOIN (SELECT MAX(tl.id)ids
						FROM vn.ticket t
							JOIN vn.ticketLog tl ON tl.originFk = t.id
						WHERE t.shipped BETWEEN '2000-01-01' AND '2000-12-31' 
							AND t.isDeleted
						GROUP BY t.id
					)sub ON sub.ids = tl.id 
				WHERE tl.creationDate <= util.VN_CURDATE() - INTERVAL 60 DAY;

		DELETE t
			FROM vn.ticket t
				JOIN tTicketDelete tmp ON tmp.ticketFk = t.id;

		DROP TEMPORARY TABLE tTicketDelete;
	END IF;

	-- Tickets Nulos PAK 11/10/2016
	UPDATE vn.ticket
		SET companyFk = 965
		WHERE clientFk = 31
			AND companyFk != 965;
END$$
DELIMITER ;
