SET serveroutput on

DECLARE

	operatore			varchar2(10);
	dir_out         	varchar2(255);
	
	
	
  	CURSOR cur_operatori is
	  SELECT desc_olo, aom_out 
	  FROM mnp_olo_report 
	  where flag_attivo = 1
	  and desc_olo not in ('TIMT', 'TIMG','BLUI')
	  order by desc_olo;


BEGIN

	OPEN cur_operatori;
	
   LOOP
		FETCH cur_operatori INTO operatore, dir_out;
		EXIT WHEN cur_operatori%NOTFOUND;
		
   DECLARE
		
		codiceric  			varchar2(23);
		msisdn 				varchar2(15);
		operatoredon    	varchar2(4);
		datavalidmax		varchar2(10);
		datainvio			Date;
		file1           	UTL_FILE.file_type;
		
  
		
		CURSOR cur_res is
		select a.id_richiesta, a.msisdn, a.codice_operatore_donating, to_char(a.data_validazione_max,'DD/MM/YYYY'),b.data_invio
  		from mnp_gestione_richiesta_rec a,mnp_xml_out b, mnp_xml_richiesta_out c
		where a.id_richiesta = c.id_richiesta
		and c.nome_file = b.nome_file
		and  a.stato = 6 
		and a.codice_operatore_donating = operatore
		and trunc(decode(to_char(b.data_invio,'D'),1,b.data_invio+5, b.data_invio+7)) < trunc(sysdate)
		and to_char(b.data_invio,'dd/mm') not in(select to_char(data_festiva,'dd/mm')from mnp_date_festive)
		and exists (select max(id_prog)
								from mnp_xml_richiesta_out c
								where c.id_richiesta = a.id_richiesta);
		
		
		
		
	
  BEGIN		
  	
  		
		file1 := UTL_FILE.fopen (dir_out, 'TIMG_to_'|| upper(operatore)||'_MANCATEVALIDAZIONI_'||to_char(sysdate,'yyyyMMdd')||'.csv', 'w');
		
			     
			     UTL_FILE.put_line (file1,'Codice richiesta;   Msisdn;   Operatore Donating;   Data validazione attesa;');
			     UTL_FILE.put_line (file1,' ');
            
		OPEN cur_res;
   		LOOP
			FETCH cur_res INTO codiceric, msisdn,operatoredon,datavalidmax, datainvio;
			EXIT WHEN cur_res%NOTFOUND;
			
				UTL_FILE.put_line (file1,codiceric ||'  ;  '|| msisdn ||'  ;  ' || operatoredon || ' ; ' || datavalidmax || ' ;');
		 	
      	END LOOP;
      	CLOSE cur_res;
      	UTL_FILE.fflush   (file1);
    		UTL_FILE.fclose   (file1);
  end; 	
 END LOOP;
 CLOSE cur_operatori;

	exception
   	 when others then
         DBMS_OUTPUT.PUT_LINE(sqlerrm);

END;
/
exit;
