DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`productionError_addCheckerPackager`(
	vDatedFrom DATETIME,
	vDatedTo DATETIME,
	vRol VARCHAR(50))
BEGIN
/**
 * Rellena la tabla vn.productionError con rol
 *
 * @param vDatedFrom Fecha desde
 * @param vDatedTo Fecha hasta
 * @param vRol rol a insertar
 */
	INSERT INTO productionError(userFk,
				firstname,
				lastname,
				rol,
				ticketNumber,
				lineNumber,
				error,
				volume,
				hourStart,
				hourEnd,
				hourWorked,
				dated)
		SELECT w.id,
				w.firstName,
				w.lastName,
				vRol,
				t.ticketCount totalTickets,
				t.lineCount,
				IFNULL(ec.errors,0) + IFNULL(ec2.errors,0) + IFNULL(pe.errors,0) errors,
				NULL volume,
				SUBSTRING(tc.tableTimed, 1, 5) hourStart,
				SUBSTRING(tc.tableTimed, LENGTH(tc.tableTimed)-4, 5) hourEnd,
				IFNULL(CAST(tc.timeWorkDecimal AS DECIMAL (10,2)) , 0) hourWorked,
				vDatedFrom dated
			FROM tmp.total t
				LEFT JOIN worker w ON w.id = t.workerFk
				LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = t.workerFk
				LEFT JOIN tmp.errorsByClaim ec ON ec.workerFk = t.workerFk
				LEFT JOIN tmp.volume v ON v.workerFk = t.workerFk
				LEFT JOIN tmp.errorsByChecker ec2 ON ec2.workerFk = t.workerFk
				LEFT JOIN tmp.expeditionErrors pe ON pe.workerFk = t.workerFk
			GROUP BY w.id;
END$$
DELIMITER ;
