DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`buy_beforeInsert`
	BEFORE INSERT ON `buy`
	FOR EACH ROW
trig: BEGIN
	DECLARE vWarehouse INT;
	DECLARE vLanding DATE;
	DECLARE vGrouping INT;
	DECLARE vGroupingMode VARCHAR(255);
	DECLARE vGenericFk INT;
	DECLARE vGenericInDate BOOL;
	DECLARE vBuyerFk INT;

	IF @isModeInventory THEN
		LEAVE trig;
	END IF;

	CALL entry_isEditable(NEW.entryFk);
	IF NEW.printedStickers <> 0 THEN
		CALL util.throw('it is not possible to create buy lines with printedstickers other than 0');
	END IF;

	SET NEW.editorFk = account.myUser_getId();

	SELECT it.workerFk INTO vBuyerFk
		FROM item i
			JOIN itemType it ON it.id = i.typeFk
		WHERE i.id = NEW.itemFk;

	SET NEW.buyerFk = vBuyerFk;

	CALL buy_checkGrouping(NEW.`grouping`);

	SELECT t.warehouseInFk, t.landed
		INTO vWarehouse, vLanding
		FROM entry e
			JOIN travel t ON t.id = e.travelFk
		WHERE e.id = NEW.entryFk;

	SELECT b.`grouping`, b.groupingMode
		INTO vGrouping, vGroupingMode
		FROM buy b
			JOIN entry e ON e.id = b.entryFk
			JOIN travel t ON t.id = e.travelFk
		WHERE t.landed <= vLanding
			AND b.itemFk = NEW.itemFk
			AND !b.isIgnored
		ORDER BY t.warehouseInFk = vWarehouse DESC,
			t.landed DESC,
			b.id DESC
		LIMIT 1;

	IF NEW.`grouping` IS NULL THEN
		SET NEW.`grouping` = vGrouping;
	END IF;

	IF NEW.groupingMode IS NULL THEN
		SET NEW.groupingMode = vGroupingMode;
	END IF;
	
	-- Generics
	SELECT i.genericFk INTO vGenericFk
		FROM item i
		WHERE i.id = NEW.itemFk;

	IF vGenericFk THEN
		SELECT COUNT(*) INTO vGenericInDate
			FROM genericAllocation ga
				JOIN entry e ON e.id = NEW.entryFk
				JOIN travel tr on tr.id = e.travelFk
			WHERE ga.itemFk = vGenericFk
				AND tr.landed BETWEEN ga.startDated AND ga.endDated;

		IF vGenericInDate THEN
			SET NEW.itemOriginalFk = NEW.itemFk;
			SET NEW.itemFk = vGenericFk;
		END IF;
	END IF;

	IF NEW.quantity < 0 THEN
		SET	NEW.isIgnored = TRUE;	
	END IF;

	IF NEW.weight AND NEW.packing
		AND (SELECT weightByPiece FROM item WHERE id = NEW.itemFk) IS NULL THEN

		UPDATE item
			SET weightByPiece = (NEW.weight * 1000) / NEW.packing
			WHERE id = NEW.itemFk;
	END IF;

END$$
DELIMITER ;
