CREATE OR REPLACE FUNCTION CTB_HIST_PAG(
   P_CDHISTPADR IN HISTPADR.CDHISTPADR%TYPE,
   P_CDFILIAL IN FILIAL.CDFILIAL%TYPE,
   P_NRLANCTONF IN NOTAFISCAL.NRLANCTONF%TYPE,
   P_NRSEQVENPAG IN CONTAPAGAR.NRSEQVENPAG%TYPE,
   P_NRPARCELAPAG IN CONTAPAGAR.NRPARCELAPAG%TYPE,
   P_CDAJUCTPAG IN TIPOAJPAGAR.CDAJUCTPAG%TYPE
) RETURN VARCHAR2
AS
   V_DSHISTPADR VARCHAR2(5000);
   V_DSAJUSTE TIPOAJPAGAR.DSAJUCTPAG%TYPE;
   V_STCHEQUE VARCHAR2(6);

BEGIN

   BEGIN
      SELECT DSHISTPADR
        INTO V_DSHISTPADR
        FROM HISTPADR
       WHERE CDHISTPADR = P_CDHISTPADR;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_DSHISTPADR :=  NULL;
   END;

   FOR C_HIST IN
      (SELECT F.NMRAZSOCFORN, F.NMFANTFORN, F.NRINSJURFORN, NF.CDFILIRECE, NF.NRNOTAFISC,
              NF.NRLANCTONF, TP.DSTPCTPAGAR, CT.DSCONTAPAG, BX.NRCHEQUE
         FROM CONTAPAGAR CT, TIPOCTPAGAR TP, NOTAFISCAL NF, FORNECEDOR F, BOLETPAGAR BP, BAIXAPAGA BX
        WHERE CT.CDFILIAL     = P_CDFILIAL
          AND CT.NRLANCTONF   = P_NRLANCTONF
          AND CT.NRSEQVENPAG  = P_NRSEQVENPAG
          AND CT.NRPARCELAPAG = P_NRPARCELAPAG
          AND CT.CDTPCTPAGAR  = TP.CDTPCTPAGAR
          AND CT.CDFILIAL     = NF.CDFILIAL
          AND CT.NRLANCTONF   = NF.NRLANCTONF
          AND NF.CDFORNECED   = F.CDFORNECED
          AND CT.CDFILIBPAG   = BP.CDFILIAL(+)
          AND CT.NRLANBOLPAG  = BP.NRLANBOLPAG(+)
          AND BP.CDFILIBAIPAG = BX.CDFILIAL(+)
          AND BP.NRBAIXAPAG   = BX.NRBAIXAPAG(+)) LOOP

      IF (C_HIST.NRCHEQUE IS NULL) THEN
         V_STCHEQUE := '---';
      ELSE
         V_STCHEQUE := C_HIST.NRCHEQUE;
      END IF;

      V_DSHISTPADR := REPLACE(V_DSHISTPADR, '[#CHQ]', V_STCHEQUE);
      V_DSHISTPADR := REPLACE(V_DSHISTPADR, '[FIL]', C_HIST.CDFILIRECE);
      V_DSHISTPADR := REPLACE(V_DSHISTPADR, '[DOC]', C_HIST.NRNOTAFISC);
      V_DSHISTPADR := REPLACE(V_DSHISTPADR, '[SEQ]', C_HIST.NRLANCTONF);
      V_DSHISTPADR := REPLACE(V_DSHISTPADR, '[TCP]', C_HIST.DSTPCTPAGAR);
      V_DSHISTPADR := REPLACE(V_DSHISTPADR, '[DCP]', C_HIST.DSCONTAPAG);
      V_DSHISTPADR := REPLACE(V_DSHISTPADR, '[FOR]', C_HIST.NRINSJURFORN);
      V_DSHISTPADR := REPLACE(V_DSHISTPADR, '[NFF]', C_HIST.NMFANTFORN);
      V_DSHISTPADR := REPLACE(V_DSHISTPADR, '[RSF]', C_HIST.NMRAZSOCFORN);
      V_DSHISTPADR := REPLACE(V_DSHISTPADR, '[NCP]', C_HIST.DSTPCTPAGAR);
   END LOOP;

   IF P_CDAJUCTPAG IS NOT NULL THEN
      BEGIN
         SELECT DSAJUCTPAG
           INTO V_DSAJUSTE
           FROM TIPOAJPAGAR
          WHERE CDAJUCTPAG = P_CDAJUCTPAG;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_DSAJUSTE := NULL;
      END;
   END IF;


   V_DSHISTPADR := REPLACE(V_DSHISTPADR, '[TAP]', P_CDAJUCTPAG);
   V_DSHISTPADR := REPLACE(V_DSHISTPADR, '[DAP]', V_DSAJUSTE);

   RETURN SUBSTR(V_DSHISTPADR, 1, 200);
END;
/

-- VERSAO --
BEGIN ATUVEROBJ('CTB_HIST_PAG','5.50.000'); END;
/
