CREATE OR REPLACE FUNCTION TIPOPARAM_DRO( P_CDFILIAL  IN FILIAL.CDFILIAL%TYPE )RETURN VARCHAR2
AS
   V_CDFILIPDR       VARCHAR2(4);
   V_IDUTPADRROPFIL  VARCHAR2(1);
   V_COUNT           INT;
BEGIN

   SELECT COUNT(*)
     INTO V_COUNT
     FROM PARAMGERAL
     WHERE IDUTPADRROP = 'S';

   IF V_COUNT > 0 THEN
      V_CDFILIPDR := 'P';
   ELSE
      V_CDFILIPDR := NULL;
   END IF;

   IF V_CDFILIPDR = 'P' THEN
      RETURN(V_CDFILIPDR);
   ELSE
      SELECT COUNT(*)
        INTO V_COUNT
        FROM PARFILIALROP
        WHERE NVL(IDUTPADRROPFIL,'N') = 'S'
          AND CDFILIAL = P_CDFILIAL;

      IF V_COUNT > 0 THEN
         V_CDFILIPDR := 'P';
      ELSE
         V_CDFILIPDR := NULL;
      END IF;

      IF V_CDFILIPDR = 'P' THEN
        RETURN(V_CDFILIPDR);
      ELSE
         BEGIN
            SELECT CDFILIAL
              INTO V_CDFILIPDR
              FROM
                  (SELECT P.CDFILIAL
                    FROM FILIAL F, PARFILIALROP P
                   WHERE F.CDFILIAL = P_CDFILIAL
                     AND F.CDFILIAL = P.CDFILIAL
                     AND CDFILCENTPME IS NULL

                  UNION ALL

                  SELECT F.CDFILIAL
                    FROM FILIAL F, PARFILIALROP P
                   WHERE F.CDFILIAL = P_CDFILIAL
                     AND CDFILCENTPME = P.CDFILIAL(+)
                     AND NVL(P.IDFILIALAGRROP,'N') = 'N'
                     AND CDFILCENTPME IS NOT NULL);

         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_CDFILIPDR := Null;
         END;


         IF V_CDFILIPDR  IS NOT NULL THEN
            RETURN(V_CDFILIPDR);
         ELSE

            SELECT MAX(CDFILCENTPME), MAX(IDUTPADRROPFIL)
              INTO V_CDFILIPDR, V_IDUTPADRROPFIL
              FROM FILIAL F, PARFILIALROP P
              WHERE F.CDFILIAL   = P_CDFILIAL
                AND CDFILCENTPME = P.CDFILIAL
                AND NVL(P.IDFILIALAGRROP,'N') = 'S';

            IF V_IDUTPADRROPFIL = 'S' THEN
               RETURN('P') ;

            ELSE RETURN(V_CDFILIPDR);

            END IF;
         END IF;
      END IF;
   END IF;
END;
/

-- VERSAO --
BEGIN ATUVEROBJ('TIPOPARAM_DRO','5.09.xxx'); END;
/

