DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerTimeControl_repair`()
proc: BEGIN
/**
 * Corrige las fichadas
 *
 */

/*1- poner todos a middle*/
UPDATE vn.workerTimeControl SET direction = 'middle';

/*2- poner los out*/
UPDATE vn.workerTimeControl wtc 
	JOIN 
		(SELECT userFk,MAX(timed) maxTimed FROM
				(SELECT id, userFk, timed, date(timed) dated
					FROM vn.workerTimeControl 
				) sub 
		GROUP BY userFk,dated
		)sub
	SET direction = "out"
	WHERE   wtc.userFk = sub.userFk 
		AND wtc.timed =  sub.maxTimed;
        
 /*3- poner los in*/       
UPDATE vn.workerTimeControl wtc 
	JOIN 
		(SELECT userFk,MIN(timed) maxTimed FROM
				(SELECT id, userFk, timed, date(timed) dated
					FROM vn.workerTimeControl 
				) sub 
		GROUP BY userFk,dated
		)sub
	SET direction = "in"
	WHERE   wtc.userFk = sub.userFk 
		AND wtc.timed =  sub.maxTimed ;   
	
END$$
DELIMITER ;
