﻿-- =============================================
-- Author:		Atzeri Emanuele
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[RecuperaReportFisicoDaRepositoryMetadati]
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	--SET NOCOUNT ON;
	BEGIN TRANSACTION
		BEGIN TRY
			--riporto gli stati a "non storicizzato" prendendo i report dagli scarti
			--UPDATE repositorymetadati
			--SET flagstoricizzato = 0, repository = 1, repositoryprestorico = null --1,4,1
			--WHERE idinrepository in
			--(
			--	SELECT idReport FROM ScartiNonArchiviabili
			--)
			--inserisco da metadati in reportfisico prendendo i report dagli scarti
			--INSERT INTO c6reportfisico
			SELECT
				a.idinrepository as Identificativo
				,a.CodiceContratto
				,a.Rete
				,a.cod_fiscale as Cliente
				,a.nome as NomeCliente
				,a.cognome as CognomeCliente
				,(CASE
					b.tiporeport
					WHEN 'D'
						THEN 1
						ELSE 4
					END) as TipoReport
				,a.datagenerazione as Data
				,'1' as StatoVerifica
				,'1' as StatoLock
				,null as [Image]
				,a.cod_agente as CodicePB
				,c.nome as NomePB
				,c.cognome as CognomePB
				,b.NumeroPagine
				,null as IDPadre
				,0 as FlagPeriodico
			FROM repositorymetadati a
			INNER JOIN [10.10.32.203].c6stampecentralizzate.c6martperiodico.gestione_pdf_ftp b
			ON a.idinrepository = b.idreport
			LEFT JOIN [10.10.32.203].c6stampecentralizzate.C6MART.ANAG_PROMOTORI c
			ON a.rete = c.rete
			AND a.cod_agente = c.ID_PROMOTORE
			WHERE a.idinrepository in
			(
				SELECT idReport FROM ScartiNonArchiviabili
			)
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		DECLARE @Msg NVARCHAR(MAX)  
		SELECT @Msg=ERROR_MESSAGE() 
		RAISERROR('Descrizione errore: %s', 20, 101,@msg) WITH LOG
	END CATCH
END