 DELIMITER $$


DROP PROCEDURE IF EXISTS `pr_autoprod2`$$

CREATE DEFINER=`root`@`localhost` PROCEDURE `pr_autoprod2`(
IN _MODE VARCHAR(38),
IN _PARAM_A VARCHAR(250),
IN _PARAM_B VARCHAR(250),
IN _PARAM_C VARCHAR(250)
)
BEGIN
 DECLARE _SQLText TEXT;
 DECLARE _SQLText2 TEXT;

 
 
 
 
IF _MODE = 'PREPARE' THEN

SET @idn=0;
SET @datazabroper = (SELECT ValueD FROM IReg WHERE IdKey ='DataZabrOper'); 

CALL raport_minusy_na_dzien('PREPARE','','','','');

DROP TEMPORARY TABLE IF EXISTS braki_zlec_aut ;    

CREATE TEMPORARY TABLE braki_zlec_aut
SELECT  
@idn := @idn+1 AS idn,
t.datawplywu,t.idntowr,magazyn,tn.symbol,t.ilosc,
(SELECT r.idnng FROM rcpo r WHERE t.idntowr=r.idntowr AND r.przychod=1 LIMIT 1) AS recepturaguid 
FROM temp_stannadzien2 t 
LEFT JOIN TowrNg tn ON t.idntowr=tn.guid 
WHERE 
tn.katcol4=1 AND t.minus=1 AND t.ilosc<>0  
AND datawplywu<= CURRENT_DATE 
AND datawplywu>=@datazabroper
AND magazyn NOT IN (300)
ORDER BY datawplywu ;
END IF;


IF _MODE = 'BUILD_ZLEC' THEN

  BEGIN
		DECLARE _Local_SRCGUID VARCHAR(38);
  
		
		DECLARE _done BOOL DEFAULT FALSE;
		DECLARE _c_proc CURSOR FOR
			SELECT 
				idn
			FROM braki_zlec_aut;
			
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET _done = TRUE;
		OPEN _c_proc;
			loop_auto_prod: LOOP
				FETCH _c_proc INTO
					_Local_SRCGUID
				;
				IF _done THEN
					LEAVE loop_auto_prod;
				ELSE
    
SELECT idntowr,recepturaguid,ilosc*-1,datawplywu,magazyn INTO  @idntowr,@recepturaguid,@ilosc,@datawplywu,@magazyn FROM braki_zlec_aut WHERE  idn=_Local_SRCGUID;
CALL pr_build_zlecprod_tools("ZLEC.PROD.CREATE.for.TowrNg", @idntowr,@recepturaguid,@ilosc, "", "",@datawplywu,@magazyn) ;   
    
			END IF;
			END LOOP;
			
		CLOSE _c_proc;
	END;
END IF;


IF _MODE = 'REAL_ZLEC' THEN

DROP TEMPORARY TABLE IF EXISTS to_autoprod;

SET @datazabroper = (SELECT ValueD FROM IReg WHERE IdKey ='DataZabrOper'); 


CREATE TEMPORARY TABLE to_autoprod
SELECT  guid FROM zmng WHERE rodzaj=73 AND ilepoz<>ilepozzreal AND guid LIKE 'Towr%' AND  terminrealizacji>=@datazabroper;

  BEGIN
		DECLARE _Local_SRCGUID VARCHAR(38);
  
		DECLARE _done BOOL DEFAULT FALSE;
		DECLARE _c_proc CURSOR FOR
			SELECT 
				guid
			FROM to_autoprod;
			
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET _done = TRUE;
		OPEN _c_proc;
			loop_auto_prod: LOOP
				FETCH _c_proc INTO
					_Local_SRCGUID
				;
				IF _done THEN
					LEAVE loop_auto_prod;
				ELSE
    
CALL fr_ht_zest_transbud("Workowanie", _Local_SRCGUID,"","","","","","","","","","");  
    
			END IF;
			END LOOP;
			
		CLOSE _c_proc;
	END;
END IF;

	

END$$

DELIMITER ;

/*
$Log$
*/
