DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `edi`.`ekt_refresh`(
	`vSelf` INT, vMailFk INT)
BEGIN
/**
 * Updates a transaction, generates it's barcode.
 */
	DECLARE vRewriteKop INT DEFAULT NULL;
	DECLARE vTruncatePutOrder INT DEFAULT NULL;
	DECLARE vBarcode CHAR(15) DEFAULT NULL;
	DECLARE vKop INT;
	DECLARE vPutOrderFk BIGINT;

	SELECT kop, putOrderFk
		INTO vKop, vPutOrderFk
		FROM ekt
		WHERE id = vSelf;

	-- Generates the barcode

	SELECT CONCAT(
				LPAD(IFNULL(auction,0), 3, 0),
				LPAD(IFNULL(klo, 99), 2, 0),
				LPAD(DAYOFYEAR(fec), 3, 0),
				COALESCE(agj, RIGHT(batchNumber,7), id))
			INTO vBarcode
		FROM ekt
		WHERE id = vSelf;

	-- Rewrites the kop parameter

	IF vKop IS NULL THEN
		SELECT defaultKop INTO vKop FROM exchangeConfig;
	END IF;

	SELECT e.kop INTO vRewriteKop
		FROM mailSender e
			JOIN mail m ON m.senderFk = e.id
		WHERE m.id = vMailFk;

	SET vKop = IFNULL(vRewriteKop, vKop);

	-- Format order id

	SET vTruncatePutOrder = vPutOrderFk MOD 1000000;

	-- Refresh EKT

	UPDATE ekt SET
		 barcode = vBarcode
		,kop = vKop
		,putOrderFk = vTruncatePutOrder
	WHERE id = vSelf;
END$$
DELIMITER ;
