DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `srt`.`expedition_in`(vBufferFk INT, OUT vExpeditionFk INT)
proc:BEGIN
	
	/**
	 * Ha entrado una caja en un buffer, por la zona de descarga.
	 *
	 * @param vBufferFk Identificador de srt.buffer
	 * 
	 * @return vExpeditionFk Identificador de srt.expedition	 * 
	 */
	
	DECLARE vMaxPosition INT;
	DECLARE vIsBufferFull BOOL;
	DECLARE vBufferTypeFk INT;
	DECLARE vBufferStateFk INT;
	
	SELECT el.expeditionFk INTO vExpeditionFk
		FROM srt.expeditionLoading el
		WHERE el.bufferFk = vBufferFk
		ORDER BY id
		LIMIT 1;
	
	IF vExpeditionFk THEN
	
		DELETE FROM srt.expeditionLoading 
			WHERE expeditionFk = vExpeditionFk;
		
		-- SET vExpeditionFk = srt.expedition_check(vExpeditionFk);
	
		INSERT INTO srt.expeditionLog (expeditionFk, bufferFk, `action`)
			VALUES(vExpeditionFk, vBufferFk, 'IN');
	
		SELECT MAX(e.position) INTO vMaxPosition
			FROM srt.expedition e
				WHERE e.bufferFk = vBufferFk;
			
		UPDATE srt.expedition e 
			JOIN srt.expeditionState es ON es.description = 'STORED'
			SET e.bufferFk = vBufferFk, 
				e.`position` = IFNULL(vMaxPosition,0) + 1,
				e.stateFk = es.id
			WHERE e.id = vExpeditionFk;
		
		SELECT bfl.freeLength < c.freeLength * 2 INTO vIsBufferFull
			FROM srt.bufferFreeLength bfl 
				JOIN srt.config c 
			WHERE bfl.bufferFk = vBufferFk;
		
		IF vIsBufferFull THEN
		
			CALL srt.buffer_setStateType(vBufferFk, 'FREE','ACCUMULATION');
		
		END IF;
	
	END IF;

	
		
END$$
DELIMITER ;