CREATE OR REPLACE FUNCTION RETORNA_CFOP_CS_DMA (
   P_CDLIVROMAG    IN NOTAFISCAL.NRLANCTONF%TYPE,
   P_CFOP          IN NOTAFISCAL.CDFILIAL%TYPE,
   P_IDENTRSAID    IN NOTAFISCAL.IDENTRSAIDOP%TYPE) RETURN VARCHAR
AS
   V_CFOP          VARCHAR2(04);
BEGIN
   V_CFOP := '0000';
   IF P_IDENTRSAID = 'E' THEN
      SELECT MAX(CDCFOPLMAG)
        INTO V_CFOP
        FROM CFOPLIVROMAG
       WHERE CDLIVROMAG  = P_CDLIVROMAG
         AND CDLAYOUTLMAG  NOT IN ('007','008','009','017','018','019','024','025','026')
         AND CDCFOPLMAG = P_CFOP;
   ELSE
      SELECT MAX(CDCFOPLMAG)
        INTO V_CFOP
        FROM CFOPLIVROMAG
       WHERE CDLIVROMAG  = P_CDLIVROMAG
         AND ((CDLAYOUTLMAG  NOT IN ('107','117','124')) OR (CDCFOPLMAG = '5927'))
         AND CDCFOPLMAG = P_CFOP;
   END IF;

   RETURN(V_CFOP);
END;
/
