
/*------ ATD 356778 ------*/
if EXISTS(SELECT  NAME FROM SYSOBJECTS WHERE NAME = 'fValidaRegimeEspecial' AND type = 'FN')
  DROP FUNCTION fValidaRegimeEspecial
go
CREATE FUNCTION fValidaRegimeEspecial(@NUMORD INT) RETURNS INT AS
BEGIN
  DECLARE @RETORNO INT, @UTILIZAREGIME INT, @SEMPROTOCOLO INT;
  SET @RETORNO = 1;
  SET @UTILIZAREGIME = 0;
  SET @SEMPROTOCOLO = 0;
  SELECT @UTILIZAREGIME = COUNT(*) FROM COMPLEMENTONFSAIDA CNFS
			JOIN NFSAIDACAD NFS ON NFS.NUMORD = CNFS.NUMORD AND LEFT(NFS.TPO, 1) = '2'  
			JOIN FILIALCAD FIL ON FIL.FILIAL = NFS.FILIAL
			JOIN ADITIVO ADT ON ADT.RITEM = FIL.OID AND ADT.RDEFINICAO = 37600 AND UPPER(RTRIM(SVALOR)) = 'S'
  WHERE CNFS.NUMORD = @NUMORD;
  IF @UTILIZAREGIME > 0
	   SELECT @SEMPROTOCOLO = COUNT(*) FROM COMPLEMENTONFSAIDA CNFS
			JOIN NFSAIDACAD NFS ON NFS.NUMORD = CNFS.NUMORD AND NFS.MODELONF = '55'  
	   WHERE 
		 CNFS.NUMORD IN (
			 SELECT ITEMCLICAD.NUMORDRET FROM ITEMCLICAD WHERE NUMORDFAT = @NUMORD AND NUMORDRET > 0
			 UNION
			 SELECT ITEMCLICAD.NUMORDTRANSF FROM ITEMCLICAD WHERE NUMORDFAT = @NUMORD AND NUMORDTRANSF > 0)
		 AND ISNULL(CNFS.NUMEROPROTOCOLO,0) = 0
		 AND LEN(ISNULL( CNFS.RECIBODPEC, '')) = 0;
		IF @SEMPROTOCOLO > 0
		   SET @RETORNO = 0;
  RETURN @RETORNO;
END
GO