DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`stockBuyedByWorker`(
	vDated DATE,
	vWorker INT
)
BEGIN
/**
 * Inserta el volumen de compra de un comprador
 * en stockBuyed de acuerdo con la fecha.
 *
 * @param vDated Fecha de compra
 * @param vWorker Id de trabajador
 */
	CREATE OR REPLACE TEMPORARY TABLE tStockBuyed
		(INDEX (userFk))
		ENGINE = MEMORY
		SELECT requested, reserved, userFk
			FROM stockBuyed
			WHERE dated = vDated
				AND userFk = vWorker;

	DELETE FROM stockBuyed
		WHERE dated = vDated
			AND userFk = vWorker;

	CALL stockTraslation(vDated);

	INSERT INTO stockBuyed(userFk, buyed, `dated`, reserved, requested, description)
		SELECT it.workerFk,
				SUM((ti.quantity / b.packing) * buy_getVolume(b.id)) / vc.palletM3 / 1000000,
				vDated,
				sb.reserved,
				sb.requested,
				u.name
			FROM itemType it
				JOIN item i ON i.typeFk = it.id
				LEFT JOIN tmp.item ti ON ti.itemFk = i.id
				JOIN itemCategory ic ON ic.id = it.categoryFk
				JOIN warehouse wh ON wh.code = 'VNH'
				JOIN tmp.buyUltimate bu ON bu.itemFk = i.id
					AND bu.warehouseFk = wh.id
				JOIN buy b ON b.id = bu.buyFk
				JOIN volumeConfig vc
				JOIN account.`user` u ON u.id = it.workerFk
				LEFT JOIN tStockBuyed sb ON sb.userFk = it.workerFk
			WHERE ic.display
				AND it.workerFk = vWorker;

	SELECT b.entryFk Id_Entrada,
			i.id Id_Article,
			i.name Article,
			ti.quantity Cantidad,
			(ac.conversionCoefficient * (ti.quantity / b.packing) * buy_getVolume(b.id))
				/ (vc.trolleyM3 * 1000000) buyed,
			b.packagingFk id_cubo,
			b.packing
		FROM tmp.item ti
			JOIN item i ON i.id = ti.itemFk
			JOIN itemType it ON i.typeFk = it.id
			JOIN itemCategory ic ON ic.id = it.categoryFk
			JOIN worker w ON w.id = it.workerFk
			JOIN auctionConfig ac
			JOIN tmp.buyUltimate bu ON bu.itemFk = i.id
				AND bu.warehouseFk = ac.warehouseFk
			JOIN buy b ON b.id = bu.buyFk
			JOIN volumeConfig vc
		WHERE ic.display
			AND w.id = vWorker;

	DROP TEMPORARY TABLE tmp.buyUltimate,
		tmp.item,
		tStockBuyed;
END$$
DELIMITER ;
