DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`entry_fixMisfit`(
	vSelf INT
)
BEGIN
/**
 * Arregla el descuadre de una entrada, agregando registros en vn.buy
 * para compensar la diferencia * entre las etiquetas impresas y las esperadas
 *
 * @param vSelf Identificador de la entrada
 */
	INSERT INTO vn.buy(entryFk, itemFk)
		SELECT vSelf, i.id
			FROM vn.item i
			WHERE i.description = 'MISFIT'
			LIMIT 1;

	INSERT INTO vn.buy(
			entryFk,
			itemFk,
			quantity,
			buyingValue,
			freightValue,
			isIgnored,
			stickers,
			packing,
			`grouping`,
			groupingMode,
			comissionValue,
			packageValue,
			location,
			packagingFk,
			price1,
			price2,
			price3,
			minPrice,
			weight)
		SELECT vSelf,
				itemFk,
				SUM(CAST(printedStickers AS INT) - stickers) * packing quantity,
				buyingValue,
				freightValue,
				TRUE isIgnored,
				CAST(printedStickers AS INT) - stickers,
				packing,
				`grouping`,
				groupingMode,
				comissionValue,
				packageValue,
				location,
				packagingFk,
				price1,
				price2,
				price3,
				minPrice,
				weight
			FROM buy b
			WHERE b.entryFk = vSelf
				AND b.printedStickers <> b.stickers
			GROUP BY itemFk
			HAVING quantity;
END$$
DELIMITER ;