
DROP procedure IF EXISTS `vn`.`clean`;

DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`clean`()
BEGIN
	DECLARE vDateShort DATETIME;
	DECLARE vOneYearAgo DATE;
	DECLARE vFourYearsAgo DATE;
	DECLARE v18Month DATE;
    DECLARE v26Month DATE;
    DECLARE v3Month DATE;
    
	SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE());
	SET vOneYearAgo = TIMESTAMPADD(YEAR,-1,CURDATE());
	SET vFourYearsAgo = TIMESTAMPADD(YEAR,-4,CURDATE());
    SET v18Month = TIMESTAMPADD(MONTH, -18,CURDATE());
	SET v26Month = TIMESTAMPADD(MONTH, -26,CURDATE());
    SET v3Month = TIMESTAMPADD(MONTH, -3, CURDATE());
    
	DELETE FROM `message` WHERE sendDate < vDateShort;
	DELETE FROM messageInbox WHERE sendDate < vDateShort;
	DELETE FROM messageInbox WHERE sendDate < vDateShort;
	DELETE FROM workerTimeControl WHERE timed < vFourYearsAgo;
	DELETE FROM itemShelving WHERE created < CURDATE() AND visible = 0;
	DELETE FROM ticketDown WHERE created < TIMESTAMPADD(DAY,-1,CURDATE());
    DELETE FROM entryLog WHERE creationDate < vDateShort;
    DELETE FROM expedition WHERE created < v26Month;
    DELETE FROM sms WHERE created < v18Month;
    DELETE FROM saleTracking WHERE created < vDateShort;
    DELETE tobs FROM ticketObservation tobs 
		JOIN ticket t ON tobs.shipped = t.id WHERE t.shipped < vDateShort;
	DELETE FROM sharingCart where ended < vDateShort;
    DELETE FROM sharingClient where ended < vDateShort;
    DELETE tw.* FROM ticketWeekly tw 
		LEFT JOIN sale s ON s.ticketFk = tw.ticketFk WHERE s.itemFk IS NULL;
	DELETE FROM claim WHERE ticketCreated < v18Month;
	DELETE FROM message WHERE sendDate < vDateShort;
    DELETE sc FROM saleChecked sc 
		JOIN sale s ON mc.Id_Movimiento = s.id WHERE s.created < vDateShort;
	DELETE bm
		FROM buyMark bm 
			JOIN buy b ON b.id = bm.id 
			JOIN entry e ON e.id = b.entryFk
			JOIN travel t ON t.id = e.travelFk
		WHERE t.landed <= vDateShort;
	DELETE FROM stowaway WHERE created < v3Month;
	CALL shelving_clean;
			
	CALL ticketPackagingRecovery;
    
END$$

DELIMITER ;

