CREATE OR REPLACE FUNCTION ITEM_VIGENTE_PADVOOTREM(
    P_CDFILIAL     IN PADVOOTREMDATA.CDFILIAL%TYPE,
    P_CDCIA        IN PADVOOTREMDATA.CDCIA%TYPE,
    P_NRVOO      IN PADVOOTREMDATA.NRVOO %TYPE,
    P_CDTRECHO     IN PADVOOTREMDATA.CDTRECHO%TYPE,
    P_DTHRPLAVOOPV IN DATE )
  RETURN NUMBER
AS
  V_DTINIVIGENCIA DATE;
  V_NRSEQPADVOOTREMDATA NUMBER;
BEGIN
   SELECT MAX(DTINIVIGENCIA)
      INTO V_DTINIVIGENCIA
            FROM PADVOOTREMDATA
            WHERE DTINIVIGENCIA <= P_DTHRPLAVOOPV
            AND CDFILIAL         = P_CDFILIAL
            AND CDCIA            = P_CDCIA
            AND NRVOO            = P_NRVOO
            AND CDTRECHO         = P_CDTRECHO;

   IF V_DTINIVIGENCIA IS NOT NULL THEN
      SELECT MAX(NRSEQPADVOOTREMDATA)
        INTO V_NRSEQPADVOOTREMDATA
        FROM PADVOOTREMDATA
       WHERE CDFILIAL = P_CDFILIAL
         AND CDCIA = P_CDCIA
         AND NRVOO = P_NRVOO
         AND CDTRECHO = P_CDTRECHO
         AND DTINIVIGENCIA = V_DTINIVIGENCIA;
      
      RETURN V_NRSEQPADVOOTREMDATA;
   END IF;

   RETURN NULL;
END;
/

CREATE OR REPLACE FUNCTION ITEM_VIGENTE_PADEQUIPM(
    P_CDFILIAL     IN PADEQUIPMDATA.CDFILIAL%TYPE,
    P_CDCIA        IN PADEQUIPMDATA.CDCIA%TYPE,
    P_CDEQUIP      IN PADEQUIPMDATA.CDEQUIP %TYPE,
    P_DTHRPLAVOOPV IN DATE )
  RETURN NUMBER
AS
  V_DTINIVIGENCIA DATE;
  V_NRSEQPADEQUIPMDATA NUMBER;
BEGIN
   SELECT MAX(DTINIVIGENCIA)
      INTO V_DTINIVIGENCIA
            FROM PADEQUIPMDATA
            WHERE DTINIVIGENCIA <= P_DTHRPLAVOOPV
            AND CDFILIAL         = P_CDFILIAL
            AND CDCIA            = P_CDCIA
            AND CDEQUIP          = P_CDEQUIP;

   IF V_DTINIVIGENCIA IS NOT NULL THEN
      SELECT MAX(NRSEQPADEQUIPMDATA)
        INTO V_NRSEQPADEQUIPMDATA
        FROM PADEQUIPMDATA
       WHERE CDFILIAL = P_CDFILIAL
         AND CDCIA = P_CDCIA
         AND CDEQUIP = P_CDEQUIP
         AND DTINIVIGENCIA = V_DTINIVIGENCIA;
      
      RETURN V_NRSEQPADEQUIPMDATA;
   END IF;

   RETURN NULL;
END;
/