--select * from c6mart.vcontrattic6 where cod_fiscale='MSTMLN76S62H501P'
--select * from  [C6Mart].[vContrattiC6] where codicecontratto = '582372CO806'
CREATE VIEW [C6Mart].[vContrattiC6_20240412]
AS
SELECT    DISTINCT
	b.chiaveClientePB, 	
	case
		when(isnull(ltrim(rtrim(codman)),'') <> '') 
			then 'FF@'+codman
		when (isnull(codfis,'') <> '')
			then codfis
		else
			c.piva
	end as Cod_fiscale,	
	c.codMan AS COD_MANDATO,	
	case when(isnull(ltrim(rtrim(codman)),'') <> '') then c.piva else '' END AS PIVA_FIDUCIARIA,   
 --   case when datediff(dd,isnull(z.dtaggiornamento,'1900-01-01 00:00:00.000'),getDate()) > 7
	--	 then  f.pb 
	--else
	--	case when(isnull(ltrim(rtrim(d.codage)),'') <> '') 
	--		then  d.codage
	--		else f.pb 
	--	END 
	--END AS COD_AGENTE, 
	isnull(d.codage,f.pb) as COD_AGENTE, -- modifica Ale
    d.rete, 
    a.codiceContratto, 
    a.flagRol, 
    a.address AS INDIRIZZO, 
    a.cap, 
    a.city AS CITTA, 
    a.province AS PROVINCIA, 
    a.nation AS NAZIONE, 
    a.presso, 
    a.email, 
    a.freqRepDia AS FREQ_DIAGNOSI, 
    a.freqRepMon AS FREQ_MONITORAGGIO, 
    a.genReport AS GENERAZIONEREPORT, 
    a.dtFirmaBase AS DATA_INIZIOBASE, 
    a.dtEndBase AS DATA_FINEBASE, 
    a.dtProcBase as DATA_PERF_BASE, 
	a.dtProcAv as DATA_PERF,
    a.dtFirmaSei AS DATA_INZIOAVANZATO, 
    a.dtEndSei AS DATA_FINEAVANZATO,   
	CASE 
	WHEN a.status = 'DADVISORY' THEN 3 --controlla prima questo
    WHEN e.tipcontratto = 'A' THEN 1
    WHEN e.tipcontratto = 'P' THEN 2
    ELSE 0 
END AS TIP_CONTRATTO,
	CASE WHEN e.riattivazione = 1 THEN 1 ELSE 0  END AS RIATTIVAZIONE,
	a.TipoConsulenza
FROM                               
	[CONSUNI].[consulenzaUnica].dbo.Contratto a
JOIN 
	[CONSUNI].[consulenzaUnica].dbo.ClientePB b 
	ON b.chiaveClientePB = a.chiaveClientePB 
	and a.status in ('SEI','AVANZATOBASE','REVOCASEI','DADVISORY')
JOIN [CONSUNI].[consulenzaUnica].dbo.Cliente c 
	ON b.chiaveCliente = c.chiaveCliente 
JOIN [CONSUNI].[consulenzaUnica].dbo.PromotoreBancario d 
	ON b.chiavePB = d.chiavePB
 JOIN --[CONSUNI].[consulenzaBaseFL].dbo.cbs_dbcontrattosei e
	 (
	  SELECT *,row_number() over (partition by COD_CONF  order by DATA_CHIUSURA_C6 DESC )  AS ordine 
	  FROM [CONSUNI].[consulenzaUnicaFL].dbo.cbs_dbcontrattosei	 
	 ) e
	ON a.codiceContratto = e.cod_conf AND e.ordine = 1
JOIN [CONSUNI].[consulenzaUnicaFL].dbo.cbs_dbcontrattobase f
	ON a.codiceContratto = f.cod_conf
--12/12/2014 - INIZIO
--left join  [CONSUNI].ConsulenzaUnica.dbo.Pianificazione z
--     on z.chiaveClientePB = a.chiaveClientePB 
----12/12/2014 - FINE