CREATE PROCEDURE [dbo].[SP_PDF_GETNUCLEI]
	@Rete varchar (1) = null,
	@CodicePB varchar(6)  = null,
	@dataDa AS varchar(10) = null,
	@dataA AS varchar(10) = null,	
	@Archivio  bit = 0,	
	@cfiva as varchar(16) = null,
	@cognomeCliente as varchar(50) = null,
	@nomeCliente as varchar(50) = null, 
	@codMan as varchar(5) = null,	 
	@nomeNucleo as varchar(500) = NULL,
	@idPdf as BIGINT  = NULL
AS
begin
    CREATE TABLE #IDPDF  (	
		 DaNucleo BIGINT NULL,
		 DaCliente BIGINT NULL	  
	) 
	DECLARE @RicClienti AS BIT	 		
	IF @NomeCliente IS NOT NULL OR @CognomeCliente  IS NOT NULL OR @cfiva  IS NOT NULL OR @codMan  IS NOT NULL 
	BEGIN 
	    INSERT INTO #IDPDF 
	    SELECT 0,IdPdf FROM ClientiPdf WHERE ChiaveClientePb in 
	    (SELECT ChiaveclientePb FROM [CONSEVO].ConsulenzaBase.dbo.vInfoCliente WHERE  1=1
					AND (@NomeCliente IS NULL OR @NomeCliente = NomeCliente)
					AND (@CognomeCliente IS NULL OR @CognomeCliente = CognomeCliente OR @CognomeCliente = codMan)					 
					AND (@cfiva IS NULL OR @cfiva = CodFis OR @cfiva = pIva)
					AND (@codMan IS NULL OR @codMan = codMan))
		SET   @RicClienti = 1
	END
	IF @NomeNucleo IS NOT NULL
	 	BEGIN
			INSERT INTO #IDPDF 
			SELECT IdPdf,0 FROM NucleiPdf WHERE ChiaveNucleo in
				(SELECT ChiaveNucleo FROM [CONSEVO].ConsulenzaEvoluta.dbo.nucleo  WHERE 1=1
						AND NomeNucleo like '%'+ @NomeNucleo + '%')
	 	END
	SELECT 
		D.*		 
		,N.chiaveNucleo
		,(SELECT NomeNucleo FROM [CONSEVO].ConsulenzaEvoluta.dbo.nucleo WHERE chiaveNucleo = N.chiaveNucleo) as NomeNucleo
		FROM DocumentiPdf D 
		INNER JOIN NucleiPdf N on
		D.IdPdf = N.idPdf 
		WHERE 1=1
		AND (@idPdf is null OR  D.idPdf = @idPdf)
		AND D.TpReport = 8 
		AND D.idStato <> 'E'
		AND (@Rete IS NULL OR @Rete = D.Rete)
		AND (@CodicePB IS NULL OR @CodicePB = CodicePB) 
		AND (@dataDA is null OR  D.dtCreazione >=  @dataDA ) 		 
		AND (@dataA is null OR  D.dtCreazione <=  @dataA)	 
		--AND (@Archivio = 1 OR D.IdArchivio = 'O' OR D.IdArchivio = 'R')
		AND (@Archivio = 1 OR D.IdArchivio <> 'A' )
		AND (@NomeNucleo IS NULL OR D.IdPdf IN (SELECT DaNucleo FROM #IDPDF))
		AND (@RicClienti IS NULL OR D.IdPdf IN (SELECT DaCliente FROM #IDPDF))
end