<table xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_trascmdint_umpletemporar</obj_name>
  <obj_hashval>619c3f1f4303c690928aaf222306cdad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_trascmdint_umpletemporar()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  V_BC  RECORD;
  V_RP  RECORD;
  V_NP  RECORD;
  cnp   numeric;
  cbc   numeric;
  crp   numeric;
BEGIN
  --Adina 11.05.2021 - alstart, alstop
  --Adina 13.01.2021 tichet 42151 - add PARTITION BY C1.CODCOMANDA1 ORDER BY C.DATADOC la ROW_NUMBER() OVER()
  --Florin 15.09.2020
  CALL PRC_AL_CHECK('tarifeman1', 0);

  DELETE FROM TMP_TRASCMDINT;
  DELETE FROM TMP_TRASNP;
  DELETE FROM TMP_TRASBC;
  DELETE FROM TMP_TRASRP;

  IF NOT current_setting('PKG_LIST_SELECTPERIOADA.vOpt1', TRUE)::NUMERIC = 1 THEN
    INSERT INTO TMP_TRASNP(CODCOMANDA1, PRODUS, SERIEPRODUS, IOARTPRODUS, CANTPRODUS, PRETPRODUS, VALPRODUS, COD, CODCMDPRODMAT)
    SELECT C1.CODCOMANDA1, O.DENUMIRE, SER.SERIE, IO.DEN_IOART,
           SUM(CASE WHEN NSE.CODNIRSTOC IS NULL  THEN NS.CANTNIR ELSE NSE.CANTNIR END),
           NS.PRET, SUM(NSE.CANTNIR * NS.PRET), ROW_NUMBER() OVER(PARTITION BY C1.CODCOMANDA1 ORDER BY C.DATADOC) AS ROWNUM, L.CODLINIECOMANDA
    FROM COMANDA1 C1
         INNER JOIN COMANDA      C   ON  C1.CODCOMANDA  = C.CODCOMANDA
         INNER JOIN INTRARI1     I1  ON  I1.CODCMDINT1  = C1.CODCOMANDA1
         INNER JOIN INTRARI      I   ON  I1.CODINTR     = I.CODINTR
         INNER JOIN NIR              ON  I.CODINTR      = NIR.CODINTR
         INNER JOIN NIRSTOC      NS  ON  NS.CODNIR      = NIR.CODNIR AND  I1.CODINTR1 = NS.CODINTR1
         INNER JOIN NARTOBJ      O   ON  I1.CODOBIECT   = O.CODOBIECT
         INNER JOIN IOART        IO  ON  NS.CODIOART    = IO.CODIOART
         LEFT  JOIN NIRSER       NSE ON  NSE.CODNIRSTOC = NS.CODNIRSTOC
         LEFT  JOIN NSERII       SER ON  SER.CODSERIE   = NSE.CODSERIE
         LEFT  JOIN INTRPRODLINK L   ON  I1.CODINTR1    = L.CODINTR1
    WHERE
       I.OPERAT = 1 AND  I.ANULAT = 0 AND  C.ANULAT = 0 AND  C.OPERAT = 1 AND  C.TIPDOC = 53
       AND C.DATADOC BETWEEN to_date(current_setting('PKG_LIST_SELECTPERIOADA.vDATAINI', TRUE), 'dd.mm.yyyy')
                         AND to_date(current_setting('PKG_LIST_SELECTPERIOADA.vDATAFIN', TRUE), 'dd.mm.yyyy')
    GROUP BY C1.CODCOMANDA1, O.DENUMIRE, SER.SERIE, IO.DEN_IOART, NS.PRET, C.DATADOC, L.CODLINIECOMANDA;

    INSERT INTO TMP_TRASBC(CODCOMANDA1, MATERIAL, SERIEMATERIAL, IOARTMATERIAL, CANTMATERIAL, PRETMATERIAL, VALMATERIAL, COD, CODCMDPRODMAT)
    SELECT C1.CODCOMANDA1, O.DENUMIRE, STRING_AGG(SER.SERIE,','), IO.DEN_IOART, SUM(L1.CANT),
           SUM(NS.PRET * L1.CANT) / SUM(L1.CANT), SUM(L1.CANT * NS.PRET),
           ROW_NUMBER() OVER(PARTITION BY C1.CODCOMANDA1 ORDER BY C.DATADOC) AS ROWNUM, LI.CODCMDPRODMAT
    FROM COMANDA1               C1
         INNER JOIN COMANDA     C   ON  C.CODCOMANDA  = C1.CODCOMANDA
         INNER JOIN IESIRI1     I1  ON  I1.CODCMDINT1 = C1.CODCOMANDA1
         INNER JOIN IESIRI      I   ON  I1.CODIES     = I.CODIES
         INNER JOIN LIVR        L   ON  L.CODIES      = I.CODIES
         INNER JOIN LIVR1       L1  ON  L.CODLIVR     = L1.CODLIVR AND  L1.CODIES1 = I1.CODIES1
         INNER JOIN NIRSTOC     NS  ON  NS.CODNIRSTOC = L1.CODNIRSTOC
         INNER JOIN IOART       IO  ON  IO.CODIOART   = NS.CODIOART
         INNER JOIN NARTOBJ     O   ON  O.CODOBIECT   = I1.CODOBIECT
         LEFT  JOIN NIRSER      NSE ON  NSE.CODNIRSER = L1.CODNIRSER
         LEFT  JOIN NSERII      SER ON  SER.CODSERIE  = NSE.CODSERIE
         LEFT  JOIN IESPRODLINK LI  ON  I1.CODIES1    = LI.CODIES1
    WHERE I.OPERAT = 1 AND  I.ANULAT = 0 AND  C.ANULAT = 0 AND  C.OPERAT = 1 AND  C.TIPDOC = 53
          AND C.DATADOC BETWEEN to_date(current_setting('PKG_LIST_SELECTPERIOADA.vDATAINI', TRUE), 'dd.mm.yyyy')
                            AND to_date(current_setting('PKG_LIST_SELECTPERIOADA.vDATAFIN', TRUE), 'dd.mm.yyyy')
    GROUP BY C1.CODCOMANDA1, O.DENUMIRE, IO.DEN_IOART, C.DATADOC, LI.CODCMDPRODMAT;

    INSERT INTO TMP_TRASRP(CODCOMANDA1, OPERATIE, NROP, VALOP, COD, CODCMDPRODMAN)
    SELECT C1.CODCOMANDA1, O.DENUMIRE, SUM(R2.REALIZAT), SUM(T1.TARIF * R2.REALIZAT * R2.TU / 60),
           ROW_NUMBER() OVER(PARTITION BY C1.CODCOMANDA1 ORDER BY C.DATADOC) AS ROWNUM, MAN.CODCMDPRODMAN
    FROM  COMANDA1               C1
          INNER JOIN COMANDA     C   ON  C.CODCOMANDA      = C1.CODCOMANDA
          INNER JOIN CMDPRODMAN  MAN ON  MAN.CODCOMANDA1   = C1.CODCOMANDA1
          INNER JOIN MANPRODLINK L   ON  MAN.CODCMDPRODMAN = L.CODCMDPRODMAN
          INNER JOIN RAPORTP2    R2  ON  R2.CODRAPORTP2    = L.CODRAPORTP2
          INNER JOIN RAPORTP1    R1  ON  R2.CODRAPORTP1    = R1.CODRAPORTP1
          INNER JOIN RAPORTP     R   ON  R1.CODRAPORTP     = R.CODRAPORTP
          INNER JOIN NOPER       O   ON  O.CODOP           = R2.CODOP
          INNER JOIN TARIFEMAN1  T1  ON  T1.CODTARIF       = R2.CODTARIF AND (R.AN * 12 + R.LUNA) BETWEEN T1.ALSTART AND T1.ALSTOP
    WHERE C.ANULAT = 0 AND  C.OPERAT = 1 AND  C.TIPDOC = 53
          AND C.DATADOC BETWEEN to_date(current_setting('PKG_LIST_SELECTPERIOADA.vDATAINI', TRUE), 'dd.mm.yyyy')
                            AND to_date(current_setting('PKG_LIST_SELECTPERIOADA.vDATAFIN', TRUE), 'dd.mm.yyyy')
--          AND  T1.ANSTART * 12 + T1.LUNASTART = (SELECT MAX(T2.ANSTART * 12 + T2.LUNASTART)
--                                                 FROM TARIFEMAN1 T2
--                                                 WHERE T2.CODTARIF = T1.CODTARIF AND  T2.ANSTART * 12 + T2.LUNASTART &lt;= R.AN * 12 + R.LUNA
--                                                )
    GROUP BY C1.CODCOMANDA1, O.DENUMIRE, C.DATADOC, MAN.CODCMDPRODMAN;

    FOR V_REC IN (SELECT C1.CODCOMANDA1
                  FROM COMANDA1 C1
                       INNER JOIN COMANDA C ON  C1.CODCOMANDA = C.CODCOMANDA
                  WHERE C.DATADOC BETWEEN to_date(current_setting('PKG_LIST_SELECTPERIOADA.vDATAINI', TRUE), 'dd.mm.yyyy')
                                      AND TO_date(current_setting('PKG_LIST_SELECTPERIOADA.vDATAFIN', TRUE), 'dd.mm.yyyy')
                        AND  C.TIPDOC = 53 AND  C.OPERAT = 1 AND  C.ANULAT = 0
                 )
    LOOP
      CNP := 0; CBC := 0; CRP := 0;
      SELECT COUNT(*) INTO CNP FROM TMP_TRASNP WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;
      SELECT COUNT(*) INTO CBC FROM TMP_TRASBC WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;
      SELECT COUNT(*) INTO CRP FROM TMP_TRASRP WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;

      IF  cnp &gt;= cbc and  cnp &gt;= crp THEN
        INSERT INTO TMP_TRASCMDINT(COD, CODCOMANDA1, PRODUS, SERIEPRODUS, IOARTPRODUS, CANTPRODUS, PRETPRODUS, VALPRODUS)
        SELECT COD, CODCOMANDA1, PRODUS, SERIEPRODUS, IOARTPRODUS, CANTPRODUS, PRETPRODUS, VALPRODUS
        FROM TMP_TRASNP
        WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;

        FOR V_BC IN (SELECT CODCOMANDA1, MATERIAL, SERIEMATERIAL, IOARTMATERIAL, CANTMATERIAL, PRETMATERIAL, VALMATERIAL, COD, CODCMDPRODMAT
                     FROM TMP_TRASBC
                     WHERE CODCOMANDA1 = V_REC.CODCOMANDA1
                    )
        LOOP
          UPDATE TMP_TRASCMDINT
          SET
            MATERIAL      = V_BC.MATERIAL,
            SERIEMATERIAL = V_BC.SERIEMATERIAL,
            IOARTMATERIAL = V_BC.IOARTMATERIAL,
            CANTMATERIAL  = V_BC.CANTMATERIAL,
            PRETMATERIAL  = V_BC.PRETMATERIAL,
            VALMATERIAL   = V_BC.VALMATERIAL,
            CODCMDPRODMAT = V_BC.CODCMDPRODMAT
          WHERE CODCOMANDA1 = V_BC.CODCOMANDA1 AND  COD = V_BC.COD;
        END LOOP;

        FOR V_RP IN (SELECT CODCOMANDA1, OPERATIE, NROP, VALOP, COD, CODCMDPRODMAN FROM TMP_TRASRP WHERE CODCOMANDA1 = V_REC.CODCOMANDA1) LOOP
          UPDATE TMP_TRASCMDINT
          SET
            OPERATIE      = V_RP.OPERATIE,
            NROP          = V_RP.NROP,
            VALOP         = V_RP.VALOP,
            CODCMDPRODMAN = V_RP.CODCMDPRODMAN
          WHERE CODCOMANDA1 = V_RP.CODCOMANDA1 AND  COD = V_RP.COD;
        END LOOP;
      ELSE
        IF  cbc &gt;= cnp and cbc &gt;= crp THEN
          INSERT INTO TMP_TRASCMDINT(CODCOMANDA1, MATERIAL, SERIEMATERIAL, IOARTMATERIAL, CANTMATERIAL, PRETMATERIAL, VALMATERIAL, COD, CODCMDPRODMAT)
          SELECT CODCOMANDA1, MATERIAL, SERIEMATERIAL, IOARTMATERIAL, CANTMATERIAL, PRETMATERIAL, VALMATERIAL, COD, CODCMDPRODMAT
          FROM TMP_TRASBC
          WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;

          FOR V_NP IN (SELECT CODCOMANDA1, PRODUS, SERIEPRODUS, IOARTPRODUS, CANTPRODUS, PRETPRODUS, VALPRODUS, COD
                       FROM TMP_TRASNP
                       WHERE CODCOMANDA1 = V_REC.CODCOMANDA1
                      )
          LOOP
            UPDATE TMP_TRASCMDINT
            SET
              PRODUS      = V_NP.PRODUS,
              SERIEPRODUS = V_NP.SERIEPRODUS,
              IOARTPRODUS = V_NP.IOARTPRODUS,
              CANTPRODUS  = V_NP.CANTPRODUS,
              PRETPRODUS  = V_NP.PRETPRODUS,
              VALPRODUS   = V_NP.VALPRODUS
            WHERE CODCOMANDA1 = V_NP.CODCOMANDA1 AND  COD = V_NP.COD;
          END LOOP;

          FOR V_RP IN (SELECT CODCOMANDA1, OPERATIE, NROP, VALOP, COD, CODCMDPRODMAN FROM TMP_TRASRP WHERE CODCOMANDA1 = V_REC.CODCOMANDA1) LOOP
            UPDATE TMP_TRASCMDINT
            SET
              OPERATIE      = V_RP.OPERATIE,
              NROP          = V_RP.NROP,
              VALOP         = V_RP.VALOP,
              CODCMDPRODMAN = V_RP.CODCMDPRODMAN
            WHERE CODCOMANDA1 = V_RP.CODCOMANDA1 AND  COD = V_RP.COD;
          END LOOP;
        ELSE
          IF crp &gt;= cnp and  crp &gt;= cbc THEN
            INSERT INTO TMP_TRASCMDINT(CODCOMANDA1, OPERATIE, NROP, VALOP, COD, CODCMDPRODMAN)
            SELECT CODCOMANDA1, OPERATIE, NROP, VALOP, COD, CODCMDPRODMAN FROM TMP_TRASrp WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;

            FOR V_BC IN (SELECT CODCOMANDA1, MATERIAL, SERIEMATERIAL, IOARTMATERIAL, CANTMATERIAL, PRETMATERIAL, VALMATERIAL, COD, CODCMDPRODMAT
                         FROM TMP_TRASBC
                         WHERE CODCOMANDA1 = V_REC.CODCOMANDA1
                        )
            LOOP
              UPDATE TMP_TRASCMDINT
              SET
                MATERIAL      = V_BC.MATERIAL,
                SERIEMATERIAL = V_BC.SERIEMATERIAL,
                IOARTMATERIAL = V_BC.IOARTMATERIAL,
                CANTMATERIAL  = V_BC.CANTMATERIAL,
                PRETMATERIAL  = V_BC.PRETMATERIAL,
                VALMATERIAL   = V_BC.VALMATERIAL,
                CODCMDPRODMAT = V_BC.CODCMDPRODMAT
              WHERE CODCOMANDA1 = V_BC.CODCOMANDA1 AND  COD = V_BC.COD;
            END LOOP;

            FOR V_NP IN (SELECT CODCOMANDA1, PRODUS, SERIEPRODUS, IOARTPRODUS, CANTPRODUS, PRETPRODUS, VALPRODUS, COD
                         FROM TMP_TRASNP
                         WHERE CODCOMANDA1 = V_REC.CODCOMANDA1
                        )
            LOOP
              UPDATE TMP_TRASCMDINT
              SET
                PRODUS      = V_NP.PRODUS,
                SERIEPRODUS = V_NP.SERIEPRODUS,
                IOARTPRODUS = V_NP.IOARTPRODUS,
                CANTPRODUS  = V_NP.CANTPRODUS,
                PRETPRODUS  = V_NP.PRETPRODUS,
                VALPRODUS   = V_NP.VALPRODUS
              WHERE CODCOMANDA1 = V_NP.CODCOMANDA1 AND  COD = V_NP.COD;
            END LOOP;
          END IF;
        END IF;
      END IF;
    END LOOP;
  ELSE
    INSERT INTO TMP_TRASNP(CODCOMANDA1, PRODUS, IOARTPRODUS, CANTPRODUS, PRETPRODUS, VALPRODUS, COD, CODCMDPRODMAT)
    SELECT C1.CODCOMANDA1, O.DENUMIRE, IO.DEN_IOART, SUM(NS.CANTNIR), NS.PRET, SUM(NS.CANTNIR * NS.PRET),
           ROW_NUMBER() OVER(PARTITION BY C1.CODCOMANDA1 ORDER BY C.DATADOC) AS ROWNUM, L.CODLINIECOMANDA
    FROM  COMANDA1               C1
          INNER JOIN COMANDA     C  ON  C1.CODCOMANDA = C.CODCOMANDA
          INNER JOIN INTRARI1    I1 ON  I1.CODCMDINT1 = C1.CODCOMANDA1
          INNER JOIN INTRARI     I  ON  I1.CODINTR    = I.CODINTR
          INNER JOIN NIR            ON  I.CODINTR     = NIR.CODINTR
          INNER JOIN NIRSTOC     NS ON  NS.CODNIR     = NIR.CODNIR AND  I1.CODINTR1 = NS.CODINTR1
          INNER JOIN NARTOBJ     O  ON  I1.CODOBIECT  = O.CODOBIECT
          INNER JOIN IOART       IO ON  NS.CODIOART   = IO.CODIOART
          LEFT JOIN INTRPRODLINK L  ON  I1.CODINTR1   = L.CODINTR1
    WHERE I.OPERAT = 1 AND  I.ANULAT = 0 AND  C.ANULAT = 0 AND  C.OPERAT = 1 AND  C.TIPDOC = 53
          AND C.DATADOC BETWEEN TO_DATE(current_setting('PKG_LIST_SELECTPERIOADA.vDATAINI', TRUE), 'DD.MM.YYYY')
                            AND TO_DATE(current_setting('PKG_LIST_SELECTPERIOADA.vDATAFIN', TRUE), 'DD.MM.YYYY')
    GROUP BY C1.CODCOMANDA1, O.DENUMIRE, IO.DEN_IOART, NS.PRET, C.DATADOC, L.CODLINIECOMANDA;

    INSERT INTO TMP_TRASBC(CODCOMANDA1, MATERIAL, IOARTMATERIAL, CANTMATERIAL, PRETMATERIAL, VALMATERIAL, COD, CODCMDPRODMAT)
    SELECT C1.CODCOMANDA1, O.DENUMIRE, IO.DEN_IOART, SUM(L1.CANT), SUM(NS.PRET * L1.CANT) / SUM(L1.CANT), SUM(L1.CANT * NS.PRET),
           ROW_NUMBER() OVER(PARTITION BY C1.CODCOMANDA1 ORDER BY C.DATADOC) AS ROWNUM, LI.CODCMDPRODMAT
    FROM  COMANDA1 C1
          INNER JOIN COMANDA    C  ON  C.CODCOMANDA  = C1.CODCOMANDA
          INNER JOIN IESIRI1    I1 ON  I1.CODCMDINT1 = C1.CODCOMANDA1
          INNER JOIN IESIRI     I  ON  I1.CODIES     = I.CODIES
          INNER JOIN LIVR       L  ON  L.CODIES      = I.CODIES
          INNER JOIN LIVR1      L1 ON  L.CODLIVR     = L1.CODLIVR AND  L1.CODIES1 = I1.CODIES1
          INNER JOIN NIRSTOC    NS ON  NS.CODNIRSTOC = L1.CODNIRSTOC
          INNER JOIN IOART      IO ON  IO.CODIOART   = NS.CODIOART
          INNER JOIN NARTOBJ    O  ON  O.CODOBIECT   = I1.CODOBIECT
          LEFT JOIN IESPRODLINK LI ON  I1.CODIES1    = LI.CODIES1
    WHERE I.OPERAT = 1 AND  I.ANULAT = 0 AND  C.ANULAT = 0 AND  C.OPERAT = 1 AND  C.TIPDOC = 53
          AND C.DATADOC BETWEEN TO_DATE(current_setting('PKG_LIST_SELECTPERIOADA.vDATAINI', TRUE), 'DD.MM.YYYY')
                            AND TO_DATE(current_setting('PKG_LIST_SELECTPERIOADA.vDATAFIN', TRUE), 'DD.MM.YYYY')
    GROUP BY C1.CODCOMANDA1, O.DENUMIRE, IO.DEN_IOART, C.DATADOC, LI.CODCMDPRODMAT;

    INSERT INTO TMP_TRASRP(CODCOMANDA1, OPERATIE, NROP, VALOP, COD, CODCMDPRODMAN)
    SELECT C1.CODCOMANDA1, O.DENUMIRE, SUM(R2.REALIZAT), SUM(T1.TARIF * R2.REALIZAT * R2.TU / 60),
           ROW_NUMBER() OVER(PARTITION BY C1.CODCOMANDA1 ORDER BY C.DATADOC) AS ROWNUM, MAN.CODCMDPRODMAN
    FROM  COMANDA1 C1
          INNER JOIN COMANDA     C   ON  C.CODCOMANDA      = C1.CODCOMANDA
          INNER JOIN CMDPRODMAN  MAN ON  MAN.CODCOMANDA1   = C1.CODCOMANDA1
          INNER JOIN MANPRODLINK L   ON  MAN.CODCMDPRODMAN = L.CODCMDPRODMAN
          INNER JOIN RAPORTP2    R2  ON  R2.CODRAPORTP2    = L.CODRAPORTP2
          INNER JOIN RAPORTP1    R1  ON  R2.CODRAPORTP1    = R1.CODRAPORTP1
          INNER JOIN RAPORTP     R   ON  R1.CODRAPORTP     = R.CODRAPORTP
          INNER JOIN NOPER       O   ON  O.CODOP           = R2.CODOP
          INNER JOIN TARIFEMAN1  T1  ON  T1.CODTARIF       = R2.CODTARIF AND (R.AN * 12 + R.LUNA) BETWEEN T1.ALSTART AND T1.ALSTOP
    WHERE C.ANULAT = 0 AND  C.OPERAT = 1 AND  C.TIPDOC = 53
          AND C.DATADOC BETWEEN to_date(current_setting('PKG_LIST_SELECTPERIOADA.vDATAINI', TRUE), 'dd.mm.yyyy')
                            AND to_date(current_setting('PKG_LIST_SELECTPERIOADA.vDATAFIN', TRUE), 'dd.mm.yyyy')
--          AND  T1.ANSTART * 12 + T1.LUNASTART = (SELECT MAX(T2.ANSTART * 12 + T2.LUNASTART)
--                                                 FROM TARIFEMAN1 T2
--                                                 WHERE T2.CODTARIF = T1.CODTARIF AND  T2.ANSTART * 12 + T2.LUNASTART &lt;= R.AN * 12 + R.LUNA
--                                                )
    GROUP BY C1.CODCOMANDA1, O.DENUMIRE, C.DATADOC, MAN.CODCMDPRODMAN;

    FOR V_REC IN (SELECT C1.CODCOMANDA1
                  FROM COMANDA1 C1
                       INNER JOIN COMANDA C ON  C1.CODCOMANDA = C.CODCOMANDA
                  WHERE C.DATADOC BETWEEN to_date(current_setting('PKG_LIST_SELECTPERIOADA.vDATAINI', TRUE), 'dd.mm.yyyy')
                                      AND to_date(current_setting('PKG_LIST_SELECTPERIOADA.vDATAFIN', TRUE), 'dd.mm.yyyy')
                        AND  C.TIPDOC = 53 AND  C.OPERAT = 1 AND  C.ANULAT = 0
                 )
    LOOP
      CNP := 0; CBC := 0; CRP := 0;
      SELECT COUNT(*) INTO CNP FROM TMP_TRASNP WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;
      SELECT COUNT(*) INTO CBC FROM TMP_TRASBC WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;
      SELECT COUNT(*) INTO CRP FROM TMP_TRASRP WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;

      IF  cnp &gt;= cbc and  cnp &gt;= crp THEN
        INSERT INTO TMP_TRASCMDINT(COD, CODCOMANDA1, PRODUS, IOARTPRODUS, CANTPRODUS, PRETPRODUS, VALPRODUS)
        SELECT COD, CODCOMANDA1, PRODUS, IOARTPRODUS, CANTPRODUS, PRETPRODUS, VALPRODUS
        FROM TMP_TRASNP
        WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;

        FOR V_BC IN (SELECT CODCOMANDA1, MATERIAL, IOARTMATERIAL, CANTMATERIAL, PRETMATERIAL, VALMATERIAL, COD, CODCMDPRODMAT
                     FROM TMP_TRASBC
                     WHERE CODCOMANDA1 = V_REC.CODCOMANDA1
                    )
        LOOP
          UPDATE TMP_TRASCMDINT
          SET
            MATERIAL      = V_BC.MATERIAL,
            IOARTMATERIAL = V_BC.IOARTMATERIAL,
            CANTMATERIAL  = V_BC.CANTMATERIAL,
            PRETMATERIAL  = V_BC.PRETMATERIAL,
            VALMATERIAL   = V_BC.VALMATERIAL,
            CODCMDPRODMAT = V_BC.CODCMDPRODMAT
          WHERE CODCOMANDA1 = V_BC.CODCOMANDA1 AND  COD = V_BC.COD;
        END LOOP;

        FOR V_RP IN (SELECT CODCOMANDA1, OPERATIE, NROP, VALOP, COD, CODCMDPRODMAN FROM TMP_TRASRP WHERE CODCOMANDA1 = V_REC.CODCOMANDA1) LOOP
          UPDATE TMP_TRASCMDINT
          SET
            OPERATIE      = V_RP.OPERATIE,
            NROP          = V_RP.NROP,
            VALOP         = V_RP.VALOP,
            CODCMDPRODMAN = V_RP.CODCMDPRODMAN
          WHERE CODCOMANDA1 = V_RP.CODCOMANDA1 AND  COD = V_RP.COD;
        END LOOP;
      ELSE
        IF  cbc &gt;= cnp and  cbc &gt;= crp THEN
          INSERT INTO TMP_TRASCMDINT(CODCOMANDA1, MATERIAL, IOARTMATERIAL, CANTMATERIAL, PRETMATERIAL, VALMATERIAL, COD, CODCMDPRODMAT)
          SELECT CODCOMANDA1, MATERIAL, IOARTMATERIAL, CANTMATERIAL, PRETMATERIAL, VALMATERIAL, COD, CODCMDPRODMAT
          FROM TMP_TRASBC
          WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;

          FOR V_NP IN (SELECT CODCOMANDA1, PRODUS, IOARTPRODUS, CANTPRODUS, PRETPRODUS, VALPRODUS, COD
                       FROM TMP_TRASNP
                       WHERE CODCOMANDA1 = V_REC.CODCOMANDA1
                      )
          LOOP
            UPDATE TMP_TRASCMDINT
            SET
              PRODUS      = V_NP.PRODUS,
              IOARTPRODUS = V_NP.IOARTPRODUS,
              CANTPRODUS  = V_NP.CANTPRODUS,
              PRETPRODUS  = V_NP.PRETPRODUS,
              VALPRODUS   = V_NP.VALPRODUS
            WHERE CODCOMANDA1 = V_NP.CODCOMANDA1 AND  COD = V_NP.COD;
          END LOOP;

          FOR V_RP IN (SELECT CODCOMANDA1, OPERATIE, NROP, VALOP, COD, CODCMDPRODMAN FROM TMP_TRASRP WHERE CODCOMANDA1 = V_REC.CODCOMANDA1) LOOP
            UPDATE TMP_TRASCMDINT
            SET
              OPERATIE      = V_RP.OPERATIE,
              NROP          = V_RP.NROP,
              VALOP         = V_RP.VALOP,
              CODCMDPRODMAN = V_RP.CODCMDPRODMAN
            WHERE CODCOMANDA1 = V_RP.CODCOMANDA1 AND  COD = V_RP.COD;
          END LOOP;
        ELSE
          IF  crp &gt;= cnp and  crp &gt;= cbc THEN
            INSERT INTO TMP_TRASCMDINT(CODCOMANDA1, OPERATIE, NROP, VALOP, COD, CODCMDPRODMAN)
            SELECT CODCOMANDA1, OPERATIE, NROP, VALOP, COD, CODCMDPRODMAN
            FROM TMP_TRASrp
            WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;

            FOR V_BC IN (SELECT CODCOMANDA1, MATERIAL, IOARTMATERIAL, CANTMATERIAL, PRETMATERIAL, VALMATERIAL, COD, CODCMDPRODMAT
                         FROM TMP_TRASBC
                         WHERE CODCOMANDA1 = V_REC.CODCOMANDA1
                        )
            LOOP
              UPDATE TMP_TRASCMDINT
              SET
                MATERIAL      = V_BC.MATERIAL,
                IOARTMATERIAL = V_BC.IOARTMATERIAL,
                CANTMATERIAL  = V_BC.CANTMATERIAL,
                PRETMATERIAL  = V_BC.PRETMATERIAL,
                VALMATERIAL   = V_BC.VALMATERIAL,
                CODCMDPRODMAT = V_BC.CODCMDPRODMAT
              WHERE CODCOMANDA1 = V_BC.CODCOMANDA1 AND  COD = V_BC.COD;
            END LOOP;

            FOR V_NP IN (SELECT CODCOMANDA1, PRODUS, IOARTPRODUS, CANTPRODUS, PRETPRODUS, VALPRODUS, COD
                         FROM TMP_TRASNP
                         WHERE CODCOMANDA1 = V_REC.CODCOMANDA1
                        )
            LOOP
              UPDATE TMP_TRASCMDINT
              SET
                PRODUS      = V_NP.PRODUS,
                IOARTPRODUS = V_NP.IOARTPRODUS,
                CANTPRODUS  = V_NP.CANTPRODUS,
                PRETPRODUS  = V_NP.PRETPRODUS,
                VALPRODUS   = V_NP.VALPRODUS
              WHERE CODCOMANDA1 = V_NP.CODCOMANDA1 AND  COD = V_NP.COD;
            END LOOP;
          END IF;
        END IF;
      END IF;
    END LOOP;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_icont_codcont</obj_name>
  <obj_hashval>b4b26dd134408a5d0d4f1498923ddfcd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_icont_codcont(picont numeric, pcodpart numeric, panluna numeric, psemnif numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
declare
  pCol     varchar;
  sSelect  varchar;
  pCodCont numeric;
  vAnLuna  numeric := Greatest(Coalesce(current_setting('PKG_GLOBALS.LUNAINITIALA', true)::numeric + current_setting('PKG_GLOBALS.ANINITIAL', true)::numeric * 12, 0), Coalesce(pAnLuna, 0));
  pAux     numeric;

  glbOldIdx_IOPERS1  numeric;
  glbOldCodP_IOPERS1 numeric;
  glbOldAL_IOPERS1   numeric;
  glbOldCod_IOPERS1  numeric;
  glbOldCodC_IOPERS1 numeric;
  glbOldDen_IOPERS1  varchar;

  glbOldIdx_IOPART1  numeric;
  glbOldCodP_IOPART1 numeric;
  glbOldAL_IOPART1   numeric;
  glbOldCod_IOPART1  numeric;
  glbOldCodC_IOPART1 numeric;
  glbOldDen_IOPART1  varchar;

  sSchema            varchar;
BEGIN
  --Florin 16.05.2023 - fixat 58290
  --Stef   12.12.2022
  --Florin 08.12.2022 - sinc. oracle
  --Florin 17.06.2022 - fixat 54319
  --Florin 24.11.2021 - fixat 52112
  --Adina 10.06.2021 - schimbat initializare sSchema
  --Adina 02.06.2021 - add schema_name in select-urile din information_schema.columns
  --Bogdan 31.07.2020
  --Bogdan 24.08.2020
  --Adina 25 septembrie 2020 : la liniile 67 si 73 am pus glboldCod_IOPERS1 in loc de oldCod_IOPERS1
  IF COALESCE(pIcont, 0) = 0 then Return null; end if;
  sSchema := Lower(current_setting('PKG_GLOBALS.FIRMANAME', true));
  IF NULLIF(sSchema, '') IS NULL THEN
    sSchema := public.get_schema();
  END IF;

  IF pSEMNIF IN (900, 901, 950, 951) THEN pCodCont := pIcont;
  ELSIF  pSEMNIF IN (500, 600) THEN
    SELECT  Max(cv.valoare)
    INTO pCodCont
    FROM constluna cl
        INNER JOIN constval cv ON  cv.codconstluna = cl.codconstluna
    WHERE
       cl.codconst1 = picont AND  pAnluna BETWEEN cl.ALStart AND CL.ALStop;
  ELSIF pIcont &lt; 1 THEN    pCodCont := 0;
  ELSIF pSEMNIF IN (1100,1101) THEN -- pCodPart = CodPers
    glbOldIdx_IOPERS1  = NULLIF(current_setting('PKG_LIST_BASE_UTILS.oldIdx_IOPERS1' , true),'')::NUMERIC;
    glbOldCodP_IOPERS1 = NULLIF(current_setting('PKG_LIST_BASE_UTILS.oldCodP_IOPERS1', true),'')::NUMERIC;
    glbOldAL_IOPERS1   = NULLIF(current_setting('PKG_LIST_BASE_UTILS.oldAL_IOPERS1'  , true),'')::NUMERIC;
    glbOldCod_IOPERS1  = NULLIF(current_setting('PKG_LIST_BASE_UTILS.oldCod_IOPERS1' , true),'')::NUMERIC;
    glbOldDen_IOPERS1  = NULLIF(current_setting('PKG_LIST_BASE_UTILS.oldDen_IOPERS1' , true),'');
    IF (glbOldDen_IOPERS1 IS NOT NULL) AND Coalesce(glbOldIdx_IOPERS1,-1) = pIcont THEN
      pCol := glbOldDen_IOPERS1;
    ELSE
      SELECT column_name INTO pCol
      FROM information_schema.columns
      WHERE table_schema = sSchema AND table_name = 'iopers1' AND ORDINAL_POSITION = pIcont + 1;
    END IF;

    IF Coalesce(glbOldCodP_IOPERS1,-1) = pCodPart AND Coalesce(glbOldAL_IOPERS1,-1) = vAnLuna THEN
      pAux := glboldCod_IOPERS1;
    else
     select  distinct last_value(codiopers) over (order by(anstart * 12 + lunastart)) into pAux
     from npers1  where codpers = pCodPart and (anstart * 12 + lunastart) &lt;= vanluna;
    END IF;

    IF Coalesce(glboldCod_IOPERS1,-1) = pAux
            AND Coalesce(glbOldAL_IOPERS1,-1) = vAnLuna
            AND Coalesce(current_setting('PKG_LIST_BASE_UTILS.oldDen_IOPERS1', true),'') = pCol THEN
      pCodCont := glbOldCodC_IOPERS1;
    ELSE
      IF Coalesce(pAux,-1) &gt; 0 and pCol is not null then
        EXECUTE 'SELECT '||pCol||' FROM iopers1 WHERE '||pAnLuna||' BETWEEN alstart and alstop AND codiopers = '||pAux INTO pCodCont;
      ELSE pCodCont := 0;
      END IF;
    END IF;

    perform set_config('PKG_LIST_BASE_UTILS.oldIdx_IOPERS1' ,pIcont::varchar  ,false);
    perform set_config('PKG_LIST_BASE_UTILS.oldDen_IOPERS1' ,pCol             ,false);
    perform set_config('PKG_LIST_BASE_UTILS.oldCod_IOPERS1' ,pAux::varchar    ,false);
    perform set_config('PKG_LIST_BASE_UTILS.oldAL_IOPERS1'  ,vAnLuna::varchar ,false);
    perform set_config('PKG_LIST_BASE_UTILS.oldCodC_IOPERS1',pCodCont::varchar,false);
    perform set_config('PKG_LIST_BASE_UTILS.oldCodP_IOPERS1',pCodPart::varchar,false);
  ELSE
    glbOldIdx_IOPART1  = NULLIF(current_setting('PKG_LIST_BASE_UTILS.oldIdx_IOPART1' , true),'')::NUMERIC;
    glbOldCodP_IOPART1 = NULLIF(current_setting('PKG_LIST_BASE_UTILS.oldCodP_IOPART1', true),'')::NUMERIC;
    glbOldAL_IOPART1   = NULLIF(current_setting('PKG_LIST_BASE_UTILS.oldAL_IOPART1'  , true),'')::NUMERIC;
    glbOldCod_IOPART1  = NULLIF(current_setting('PKG_LIST_BASE_UTILS.oldCod_IOPART1' , true),'')::NUMERIC;
    glbOldCodC_IOPART1 = NULLIF(current_setting('PKG_LIST_BASE_UTILS.oldCodC_IOPART1', true),'')::NUMERIC;
    glbOldDen_IOPART1  = NULLIF(current_setting('PKG_LIST_BASE_UTILS.oldDen_IOPART1' , true),'');

    IF (glbOldDen_IOPART1 IS NOT NULL) AND Coalesce(glbOldIdx_IOPART1,-1) = pIcont THEN
      pCol := glbOldDen_IOPART1;
    ELSE
      SELECT column_name INTO pCol
      FROM information_schema.columns
      WHERE table_schema = sSchema AND table_name = 'iopart1' AND  ORDINAL_POSITION = pIcont + 1;
    END IF;

    IF  Coalesce(glbOldCodP_IOPART1, -1) = pCodPart AND  Coalesce(glbOldAL_IOPART1, -1) = vAnLuna THEN
      pAux := glbOldCod_IOPART1;
    ELSE
      SELECT  max(codiopart) INTO pAux
      FROM martor.npart1
      WHERE codpart = pCodPart AND vAnluna BETWEEN ALStart AND ALStop;
    END IF;

    IF Coalesce(glbOldCod_IOPART1,-1) = pAux AND Coalesce(glbOldAL_IOPART1,-1) = pAnluna AND Coalesce(glbOldDen_IOPART1,'') = pCol THEN
      pCodCont := glbOldCodC_IOPART1;
    ELSE
      IF Coalesce(pAux, -1) &gt; 0 and pCol is not NULL THEN
        EXECUTE 'SELECT Max('||pCol||') FROM iopart1 WHERE '||pAnLuna||' BETWEEN ALStart AND ALStop AND codiopart = '||pAux INTO pCodCont;
      ELSE pCodCont := 0;
      END IF;
    END IF;
    perform set_config('PKG_LIST_BASE_UTILS.oldIdx_IOPART1' ,pIcont::varchar  ,false);
    perform set_config('PKG_LIST_BASE_UTILS.oldDen_IOPART1' ,pCol             ,false);
    perform set_config('PKG_LIST_BASE_UTILS.oldCod_IOPART1' ,pAux::varchar    ,false);
    perform set_config('PKG_LIST_BASE_UTILS.oldAL_IOPART1'  ,vAnLuna::varchar ,false);
    perform set_config('PKG_LIST_BASE_UTILS.oldCodC_IOPART1',pCodCont::varchar,false);
    perform set_config('PKG_LIST_BASE_UTILS.oldCodP_IOPART1',pCodPart::varchar,false);
  END IF;
  return  Coalesce(pCodCont, 0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzclaseart_setjoinuri</obj_name>
  <obj_hashval>bcffcff4262279bfb3abd0ef3b1fd5cb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzclaseart_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 10.09.2020
  PERFORM Pkg_List_Struct_SetTableSpec('');
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzper_processlist</obj_name>
  <obj_hashval>48012a7596c732fb416d76dce31ad1b5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzper_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     VARCHAR := '';
  sSelect     VARCHAR := '';
  sUpdate     VARCHAR := '';
  sWhere      VARCHAR := '';
  sJoinUM     VARCHAR := '';
  sJoinU1     VARCHAR := '';
  sCurs       VARCHAR := '';
  sCampUM     VARCHAR := 'NUM.DEN_UM';
  vVal        VARCHAR := '';
  sInsAUX     VARCHAR := '';
  sSelAUX     VARCHAR := '';
  sJoinUMA    VARCHAR := '';
  sJoinCL     VARCHAR := '';
  sValAchiz   VARCHAR := '';
  sJoinAchiz  VARCHAR := '';
  sInsAchiz   VARCHAR := '';
  sGroupAchiz VARCHAR := '';
  aSitV       NUMERIC;
  aBancaV     NUMERIC;
  aMonedaV    NUMERIC;
  K           NUMERIC;
  sCU1        VARCHAR := '';
  vMaxCl      NUMERIC;
  sAnP        NUMERIC;
  sLunaP      NUMERIC;
  sAnM        NUMERIC;
  sLunaM      NUMERIC;
  vDataRef    DATE;
  sTipLin     VARCHAR := '''=''';
  sArtAtrib1  VARCHAR := ', NULL ARTATRIB1';
  sFiltruObj  VARCHAR := '';
  gSuplCols   VARCHAR := '';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  sCondB      VARCHAR;
  sCond       VARCHAR;

  wmeRes      BOOLEAN;

  vCodAtribut VARCHAR := current_setting('PKG_LIST_BASE_VANZPER.vCodAtribut', true);
  vTipPer     NUMERIC := current_setting('PKG_LIST_BASE_VANZPER.vTipPer'    , true)::NUMERIC;
  vLunaIni    VARCHAR := current_setting('PKG_LIST_BASE_VANZPER.vLunaIni'   , true);
  vLunaFin    VARCHAR := current_setting('PKG_LIST_BASE_VANZPER.vLunaFin'   , true);
  vInceput    VARCHAR := current_setting('PKG_LIST_BASE_VANZPER.vInceput'   , TRUE);
  vSfarsit    VARCHAR := current_setting('PKG_LIST_BASE_VANZPER.vSfarsit'   , TRUE);
  vTipData    BOOLEAN := current_setting('PKG_LIST_BASE_VANZPER.vTipData'   , TRUE);
  vTipUM      NUMERIC := current_setting('PKG_LIST_BASE_VANZPER.vTipUM'     , true)::NUMERIC;
  vValuta     BOOLEAN := current_setting('PKG_LIST_BASE_VANZPER.vValuta'    , true);
  vCantitativ BOOLEAN := current_setting('PKG_LIST_BASE_VANZPER.vCantitativ', true)::BOOLEAN;
  vValoric    BOOLEAN := current_setting('PKG_LIST_BASE_VANZPER.vValoric'   , true)::BOOLEAN;
  vInclTVA    BOOLEAN := current_setting('PKG_LIST_BASE_VANZPER.vInclTVA'   , true)::BOOLEAN;
  vInclUnit   BOOLEAN := current_setting('PKG_LIST_BASE_VANZPER.vInclUnit'  , true)::BOOLEAN;
  vUM         NUMERIC := current_setting('PKG_LIST_BASE_VANZPER.vUM'        , true)::NUMERIC;
  vInclServ   BOOLEAN := current_setting('PKG_LIST_BASE_VANZPER.vInclServ'  , true)::BOOLEAN;
  vCantCutii  BOOLEAN := current_setting('PKG_LIST_BASE_VANZPER.vCantCutii' , true)::BOOLEAN;
  vCantPaleti BOOLEAN := current_setting('PKG_LIST_BASE_VANZPER.vCantPaleti', true)::BOOLEAN;
  vNrCol      NUMERIC := current_setting('PKG_LIST_BASE_VANZPER.vNrCol'     , true)::NUMERIC;
  vVariatie   BOOLEAN := current_setting('PKG_LIST_BASE_VANZPER.vVariatie'  , true)::BOOLEAN;
  vExclCust   BOOLEAN := current_setting('PKG_LIST_BASE_VANZPER.vExclCust'  , true)::BOOLEAN;
BEGIN
  --Florin 21.11.2025 - fixat 67400
  --Stef 04.04.2025 - sinc. Oracle
  IF vCodAtribut::NUMERIC &gt; 0 THEN
    sArtAtrib1 := ',
      (SELECT Min(aa1.valoare)
        FROM nartatr aa
          LEFT JOIN natrobj ao  ON ao.codartatr  = aa.codartatr
          LEFT JOIN natrib1 aa1 ON aa1.codvalatr = ao.codvalatr
        WHERE aa.codarticol = nao.codarticol AND ao.codobiect = nao.codobiect AND aa.codatribut = ' || coalesce(vCodAtribut,'') || '
      ) ARTATRIB1';
    sFiltruObj := ' and exists (select aa.codatribut from nartatr aa where aa.codarticol = nao.codarticol AND aa.codatribut = ' || coalesce(vCodAtribut,'') || ') ';
  END IF;
  gSuplCols :=
    'NARTOBJ NAO, NART NA, NUM NUM, NGEST NG, NPART NP, NPART PROD, IOART IOA, NCLASEA NCA, NCLASEP NCP, NPERS AG, '||
    'NAGENDA SSOC, NLOCALIT LSOC, NJUDET JSOC, NAGENDA SLIV, NLOCALIT LLIV, NJUDET JLIV, TRASEULIVR TLIV, NTIPSEDII TIPSLIV,PRETM PRETIMP';

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = NAO.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = NAO.CODOBIECT',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.gSuplCols', gSuplCols, FALSE);

  PERFORM pkg_list_base_vanzper_BAGA_JOB_DINAMIC_COLS(tmpName);

  IF vInclserv THEN
    sTipLin := sTipLin ||',''S''';
  END IF;

  IF vTipData THEN
    sCondB := EXTRACT(YEAR FROM To_Date(coalesce(vInceput,''),'dd.mm.yyyy')) * 12 + EXTRACT(MONTH FROM To_Date(coalesce(vInceput,''),'dd.mm.yyyy')) || '
            AND ' || EXTRACT(YEAR FROM To_Date(coalesce(vSfarsit,''),'dd.mm.yyyy')) * 12 + EXTRACT(MONTH FROM To_Date(coalesce(vSfarsit,''),'dd.mm.yyyy'));
    sCond  := EXTRACT(YEAR FROM To_Date(coalesce(vInceput,''),'dd.mm.yyyy')) * 12 + EXTRACT(MONTH FROM To_Date(coalesce(vInceput,''),'dd.mm.yyyy')) - 1;
  ELSE
    sCondB := COALESCE(vInceput, '')||' and '||COALESCE(vSfarsit, '');
    sCond  := (vInceput::NUMERIC - 1)::VARCHAR;
  END IF;

  IF vTipPer = 5 THEN
    IF vLunaIni::NUMERIC = vLunaFin::NUMERIC THEN
      sWhere := 'I.LUNA = ' || coalesce(vLunaIni,'0') || ' AND I.An';
    ELSE
      sWhere := 'I.LUNA BETWEEN ' || coalesce(vLunaIni,'0') || ' AND ' || coalesce(vLunaFin,'0') || ' AND I.An';
    END IF;
  ELSIF vTipData THEN
    sWhere := 'I.DataDoc';
  ELSE
    sWhere := 'I.An*12+I.LUNA';
  END IF;
  IF vInceput = vSfarsit AND vTipData THEN
      sWhere := coalesce(sWhere,'') || ' = To_Date(''' || coalesce(vInceput,'') || ''',''dd.mm.yyyy'')';
  ELSIF vInceput = vSfarsit THEN
      sWhere := coalesce(sWhere,'') || ' = ' || coalesce(vInceput,'');
  ELSIF vTipData THEN
      sWhere := coalesce(sWhere,'') || ' BETWEEN ' || ' To_Date(''' || coalesce(vInceput,'') || ''',''dd.mm.yyyy'')' || ' AND ' ||
      'To_Date(''' || coalesce(vSfarsit,'') || ''',''dd.mm.yyyy'')' ;
  ELSE
      sWhere := COALESCE(sWhere, '')||' BETWEEN '|| coalesce(vInceput, '') ||' AND '|| coalesce(vSfarsit, '');
  END IF;

  IF vExclCust THEN
    sWhere := sWhere||' AND NOT I.CUSTODIE IN (1, 2)';
  END IF;

  sValAchiz   := ',CAST(NULL AS NUMERIC(20,7)) VALACHIZ';
  sJoinAchiz  := '';
  if current_setting('PKG_LIST_BASE_VANZPER.vValAchiz', TRUE)::BOOLEAN then
   CALL create_wm_temps_flag('TMP_LST_VALACHIZ');
    sValAchiz :=',
        CASE
          WHEN iesval.codlivr1 &gt; 0 AND ae.initializari = 1 and ae.custodie = 1 THEN iesval.val * i1.cant
          WHEN iesval.codlivr1 &gt; 0 THEN iesval.val * Coalesce(l1.cant,0)*i1.cant/Coalesce(ae1.cant,i1.cant)
          ELSE
            CASE
              WHEN NS.CODNIRSTOC &gt; 0 THEN NS.PRET - COALESCE(NS.ADAOS,0)
              ELSE LV.PRETACHIZ
            END * CASE WHEN I.TIPDOC = 26 AND AE1.CANT &lt;&gt; 0 THEN I1.CANT/AE1.CANT ELSE 1 END * coalesce(L1.CANT,I1.CANT)
        END ValAchiz';
    sJoinAchiz := 'LEFT JOIN TMP_LST_VALACHIZ IESVAL ON IESVAL.CODLIVR1  = L1.CODLIVR1';
    sInsAchiz  := 'INSERT INTO TMP_LST_VALACHIZ(VAL, CODLIVR1)
     SELECT SUM(LL1.CANT * (NS.PRET - Coalesce(NS.ADAOS,0)))/SUM(LL1.CANT) VAL, L1.CODLIVR1
      FROM IESIRI I
        INNER JOIN IESIRI1    I1  ON I1.CODIES     = I.CODIES
        INNER JOIN LIVR1      L1  ON L1.CODIES1    = I1.CODIES1
        INNER JOIN IESVALLINK IVL ON IVL.CODLIVR1  = L1.CODLIVR1
        INNER JOIN LIVR1      LL1 ON LL1.CODIES1   = IVL.CODIES1
        INNER JOIN NIRSTOC    NS  ON NS.CODNIRSTOC = LL1.CODNIRSTOC
      WHERE '||sWhere||' AND coalesce(I.InfoCM,0) = 0 AND I.ANULAT = 0 AND I.OPERAT = 1 AND LL1.CANT &lt;&gt; 0
        AND I.TIPDOC::VARCHAR IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''TIPDOC'')
        AND I1.TIPLINIE IN ('||sTipLin||') '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', NULL, NULL, NULL)||'
      GROUP BY L1.CODLIVR1
      UNION ALL
      SELECT SUM(L1.CANT * (NS.PRET - Coalesce(NS.ADAOS,0)))/SUM(L1.CANT) VAL, L1.CODLIVR1
      FROM IESIRI I
        INNER JOIN IESIRI1    I1  ON I1.CODIES     = I.CODIES
        INNER JOIN LIVR1      L1  ON L1.CODIES1    = I1.CODIES1
        INNER JOIN NIRSTOC    NS  ON NS.CODNIRSTOC = L1.CODNIRSTOC
        LEFT JOIN IESVALLINK IVL ON IVL.CODLIVR1  = L1.CODLIVR1
      WHERE '||sWhere||' AND coalesce(I.InfoCM,0) = 0 AND I.ANULAT = 0 AND I.OPERAT = 1 AND L1.CANT &lt;&gt; 0
        AND I.TIPDOC::VARCHAR IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''TIPDOC'')
        AND I1.TIPLINIE IN ('||sTipLin||') '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', NULL, NULL, NULL)||'
        AND IVL.CODLIVR1 IS NULL
      GROUP BY L1.CODLIVR1';
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsAchiz, aListID, aListVer);
  END IF;

  IF vTipUM = 3 THEN
    sWhere := coalesce(sWhere,'') || '
              AND (COALESCE(O.MASA,0) &lt;&gt; 0 OR U.TIPUM = 1)';
  END IF;

  IF vTipUM = 4 THEN
    sWhere := coalesce(sWhere,'') || '
              AND (COALESCE(O.VOLUM,0) &lt;&gt; 0 OR U.TIPUM = 2)';
  END IF;

   SELECT   pkg_list_base_utils_GetInfoSitValuta.WME_RESULT,
          pkg_list_base_utils_GetInfoSitValuta.psitvaluta,
          pkg_list_base_utils_GetInfoSitValuta.pbancavaluta,
          pkg_list_base_utils_GetInfoSitValuta.pmonedavaluta
  INTO wmeRes, aSitV, aBancaV, aMonedaV
  FROM pkg_list_base_utils_GetInfoSitValuta(NULL,aSitV, aBancaV, aMonedaV);
  IF vValuta AND wmeRes THEN
    sCurs := '/ PKG_LIST_BASE_UTILS_GETCURSREFERINTA(' || coalesce(aMonedaV::VARCHAR,'0') || ',' || coalesce(aBancaV::VARCHAR,'0') || ', to_char(i.datadoc,''dd.mm.yyyy'') )';
  END IF;

  IF vCantitativ THEN
    vVal := coalesce(vVal,'') || ',
              CASE WHEN I.TIPDOC = 26 AND AE1.CANT &lt;&gt; 0 THEN I1.CANT/AE1.CANT ELSE 1 END * COALESCE(L1.CANT,I1.CANT) CAux';
  END IF;

  IF vValoric THEN
    vVal := coalesce(vVal,'') || ',
              CASE WHEN I.TIPDOC = 26 AND AE1.CANT &lt;&gt; 0 THEN I1.CANT/AE1.CANT ELSE 1 END * COALESCE(L1.CANT,I1.CANT) * i1.pretorig * COALESCE(i1.coefdiscmaj,1) * CASE WHEN i.tipdoc IN (16,21) AND (i1.cant * i1.pu) &lt;&gt; 0 THEN (1 - COALESCE(i1.tva,0) / (i1.cant * i1.pu)) ELSE 1 END * i.curs' || coalesce(sCurs,'') || ' VAux';
  if current_setting('PKG_LIST_BASE_VANZPER.vValAchiz', TRUE)::BOOLEAN then
      sGroupAchiz := sGroupAchiz||',i1.pretorig,coalesce(i1.coefdiscmaj,1),i1.pu,coalesce(i1.tva,0),i.curs';
    end if;
  END IF;

  IF vInclTVA THEN
    vVal := coalesce(vVal,'') || ',
            CASE WHEN I.TIPDOC = 26 AND AE1.CANT &lt;&gt; 0 THEN I1.CANT/AE1.CANT ELSE 1 END * COALESCE(L1.CANT,I1.CANT) * i1.pretorig * COALESCE(i1.coefdiscmaj,1) * CASE WHEN i.tipdoc IN (16,21) OR (i1.cant * i1.pu) = 0 THEN 1 ELSE (1 + COALESCE(i1.tva,0) / (i1.cant * i1.pu)) END * i.curs' || coalesce(sCurs,'') || ' VTAux';
    IF NOT VVALORIC and current_setting('PKG_LIST_BASE_VANZPER.vValAchiz', TRUE)::BOOLEAN THEN
      sGroupAchiz := sGroupAchiz||',i1.pretorig,coalesce(i1.coefdiscmaj,1),i1.pu,coalesce(i1.tva,0),i.curs';
    END IF;
  END IF;

  IF vInclUnit THEN
    vVal := coalesce(vVal,'') || ',
              CASE WHEN I.TIPDOC = 26 AND AE1.CANT &lt;&gt; 0 THEN I1.CANT/AE1.CANT ELSE 1 END * COALESCE(L1.CANT,I1.CANT) * i1.pu * CASE WHEN i.tipdoc IN (16,21) AND (i1.cant * i1.pu) &lt;&gt; 0 THEN (1 - COALESCE(i1.tva,0) / (i1.cant * i1.pu)) ELSE 1 END * i.curs' || coalesce(sCurs,'') || ' VUAux';
    IF NOT VVALORIC AND NOT VINCLTVA and current_setting('PKG_LIST_BASE_VANZPER.vValAchiz', TRUE)::BOOLEAN THEN
      sGroupAchiz := sGroupAchiz||',i1.pretorig,i1.pu,coalesce(i1.tva,0),i.curs';
    END IF;
  END IF;
  if vTipPer = 1 THEN
    vVal := COALESCE(vVal, '') ||',
              CASE WHEN I.TIPDOC = 16 THEN coalesce(i1.valdiscpret-i1.valdiscpret*i1.tva/(i1.pu*i1.cant),0) ELSE 0 END DAux';
  END IF;


  sJoinU1 := '
        LEFT JOIN NUM1 U1 ON U1.CODUM = NA.UM AND SECUNDARA = 0';

  IF vTipUM = 1 THEN
    sJoinUM := '
            INNER JOIN NARTOBJ O ON O.CODOBIECT    = I1.CODOBIECT
            INNER JOIN NART ART  ON ART.CODARTICOL = O.CODARTICOL AND ART.UM = ' || coalesce(vUM::VARCHAR,'0');
  ELSIF vTipUM = 2 THEN
    sJoinUM := '
            INNER JOIN NARTOBJ O  ON O.CODOBIECT  = I1.CODOBIECT
            INNER JOIN NARTAMB AA ON AA.CODOBIECT = O.CODOBIECT AND AA.UMSEC = ' || coalesce(vUM::VARCHAR,'0') || '
            INNER JOIN NUM1 U1    ON U1.CODUM1    = AA.UMSEC';
    sCU1 := ', ' || coalesce(vUM::VARCHAR,'0') || ' CU1';
    sJoinU1 := '
        LEFT JOIN NUM1 U1 ON U1.CODUM1 = IG.CU1';
    sCampUM := 'U1.DEN_UM1';
    sInsAux := coalesce(sInsAux,'') || ', ParCant';
    sSelAux := coalesce(sSelAux,'') || ', U1.PARITATE';
  ELSIF vTipUM IN (3,4) THEN
    sJoinUM := '
        INNER JOIN NARTOBJ O ON O.CODOBIECT    = I1.CODOBIECT
        INNER JOIN NART ART  ON ART.CODARTICOL = O.CODARTICOL
        INNER JOIN NUM U     ON U.CODUM        = ART.UM';
    sCampUM  := CASE WHEN vTipUM = 3 THEN '''KG''' ELSE '''CC''' END;
    sInsAux  := sInsAux||', ParCant';
    sSelAux  := sSelAux||', NUM.COEF';
  END IF;

  vDataRef := TO_DATE(current_setting('PKG_LIST_BASE_VANZPER.vDataFin', true), 'dd.mm.yyyy');
  sAnP     := To_Char(vDataRef, 'yyyy');
  sLunaP   := To_Char(vDataRef, 'mm');

  SELECT anmaxim, lunamaxima INTO sAnM, sLunaM FROM FIRMALUNI;
  IF sAnP * 12 + sLunaP &gt; sAnM * 12 + sLunaM THEN
      sAnP   := sAnM;
      sLunaP := sLunaM;
  ELSE
      sAnM   := sAnP;
      sLunaM := sLunaP;
  END IF;

  --PERFORM PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA(sAnP, sLunaP, sAnP, sLunaP);
  SELECT PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA.newan, PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA.newluna
  INTO sAnP, sLunaP
  FROM PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA(sAnP, sLunaP, sAnP, sLunaP);
  sSelect := '
    WITH STOC AS (
      SELECT CODOBIECT, GEST, CODIOART, SUM(REST) STOCINI, SUM(VALACHIZ) VALACHIZ
      FROM (
        SELECT NS.CODOBIECT, N.GEST, NS.CODIOART, NL.REST, COALESCE(NS.PRET,0) * NL.REST VALACHIZ
        FROM NIRLUNA NL
          INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = NL.CODNIRSTOC
          INNER JOIN NIR     N  ON N.CODNIR      = NS.CODNIR
        WHERE NL.AN * 12 + NL.LUNA = ' || sCond || '
        UNION ALL -- NIRURI LUNA
        SELECT NS.CODOBIECT, N.GEST, NS.CODIOART, NS.CANTNIR AS REST, COALESCE(NS.PRET,0) * NS.CANTNIR VALACHIZ
        FROM NIRSTOC NS
          INNER JOIN NIR     N ON N.CODNIR    = NS.CODNIR
          LEFT  JOIN INTRARI I ON I.CODINTR   = N.CODINTR
          LEFT  JOIN TRANSF  T ON T.CODTRANSF = N.CODTRANSF
        WHERE N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 12, 13) AND  N.ANULAT = 0 AND N.OPERAT = 1
          AND N.DATANIR &lt; To_Date(''' || coalesce(To_Char(vDataRef, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')
          AND COALESCE(I.AN,T.AN,0) * 12 + COALESCE(I.LUNA,T.LUNA,0) between ' || sCondB || '
        UNION ALL
        SELECT NS.CODOBIECT, N.GEST, NS.CODIOART, CASE WHEN L.TIPLIVR = 15 THEN L1.CANT ELSE -1 * L1.CANT END REST, COALESCE(NS.PRET,0) * CASE WHEN L.TIPLIVR = 15 THEN L1.CANT ELSE -1 * L1.CANT END VALACHIZ
        FROM LIVR L
          INNER JOIN LIVR1   L1  ON L1.CODLIVR    = L.CODLIVR
          INNER JOIN NIRSTOC NS  ON NS.CODNIRSTOC = L1.CODNIRSTOC
          INNER JOIN NIR     N   ON N.CODNIR      = NS.CODNIR
          LEFT  JOIN INTRARI I   ON I.CODINTR     = L.CODINTR
          LEFT  JOIN IESIRI  IES ON IES.CODIES    = L.CODIES
          LEFT  JOIN TRANSF  T   ON T.CODTRANSF   = L.CODTRANSF
        WHERE L.TIPLIVR IN (1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15 ,16, 19, 20, 21, 23, 24) AND L.OPERAT = 1 AND L.ANULAT = 0
          AND L.DATALIVR &lt; To_Date(''' || coalesce(To_Char(vDataRef,'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')
          AND COALESCE(I.AN,IES.AN,T.AN,0) * 12 + COALESCE(I.LUNA,IES.LUNA,T.LUNA,0) between ' || sCondB || '
      ) a_pg
      GROUP BY CODOBIECT, GEST, CODIOART)';
  IF vCantCutii OR vCantPaleti THEN
    sSelect := coalesce(sSelect,'') || ',
      UMA AS (
        SELECT
          AMB.CODOBIECT,
          Max((CASE WHEN Upper(U1.Codextern) = ''CUTIE'' THEN paritate END)) PUMAC,
          Max((CASE WHEN Upper(U1.Codextern) = ''PALET'' THEN paritate END)) PUMAP
        FROM NARTAMB AMB
          INNER JOIN NUM1 U1 ON U1.CODUM1 = AMB.UMSEC
        GROUP BY CODOBIECT)';
    sInsAux  := coalesce(sInsAux,'') || ', ParCutie, ParPalet';
    sSelAux  := coalesce(sSelAux,'') || ', UMA.PUMAC, UMA.PUMAP';
    sJoinUMA := '
      LEFT JOIN UMA ON UMA.CODOBIECT = NAO.CODOBIECT';
  END IF;

  vMaxCl := (SELECT PKG_LIST_BASE_UTILS_NIVELE_NCLASEA.WME_RESULT FROM PKG_LIST_BASE_UTILS_NIVELE_NCLASEA(NULL,NULL));

  IF vMaxCL &gt; 0 THEN
    sJoinCL := coalesce(sJoinCL,'') || '
        LEFT JOIN (
          SELECT
            CODCLASEA ';
    FOR i in 1..vMaxCL loop
      sInsAUX := sInsAUX||', CL'||i::VARCHAR  ||', CS'||i::VARCHAR;
      sSelAUX := sSelAUX||', CL.D'||i::VARCHAR||', CL.S'||i::VARCHAR;
      sJoinCL := sJoinCL ||',
        coalesce(Max(CASE WHEN nivel = '||i::VARCHAR||' THEN den_clasea ELSE NULL end),''FARA CLASA '||i::VARCHAR||''') D'||i::VARCHAR||',
        Max(CASE WHEN nivel = '||i::VARCHAR||' THEN simbol     ELSE '''' end) S'||i::VARCHAR;
    END LOOP;
    sJoinCL := coalesce(sJoinCL,'') || '
        FROM TMP_PROFIT_NCLASEA
        GROUP BY CODCLASEA
      ) CL ON CL.CodClasea = NA.Clasa ';
  END IF;

  sInsert :=
  'INSERT INTO ' || tmpName ||
  '(CodObiect, Art, UM, Client, Gest, IOArt, DenClasaA, CodInt, CodExt, Prod, DenClasaC, SediuCli, SediuLiv, Agent, AgentI, StocFin, ValAchizStocFin, Masa, Volum,ValAchiz,ArtAtrib1'
  || coalesce(sInsAUX,'') || coalesce(PKG_LIST_BASE_VANZPER_CAMPURI('INSERT',NULL),'')
  || ', x_judet, x_codclasap, x_codgest, x_codsubunit '
  || gUserFields || ')';

  sSelect := coalesce(sSelect,'') || ',
    IG AS (
      SELECT CODOBIECT, PARTENER, CODLOCATIE, GEST, CODIOART, AGENT, SUM(COALESCE(VALACHIZ,0)) VALACHIZ'
      || coalesce(PKG_LIST_BASE_VANZPER_CAMPURI('SELECT',NULL),'') || coalesce(sCU1,'') || '
      FROM (
        SELECT
          I1.CODOBIECT, I.PARTENER, I.CODLOCATIE, COALESCE(N.GEST,LV.GEST) GEST, COALESCE(NS.CODIOART,LV.CODIOART) CODIOART, COALESCE(I.AGENT,0) AGENT,
          I.DATADOC, I.LUNA, I.AN' || COALESCE(sValAchiz, '') || coalesce(vVal,'') || '
        FROM IESIRI I
          INNER JOIN IESIRI1 I1  ON I1.CODIES     = I.CODIES' || coalesce(sJoinUM,'') || '
          LEFT  JOIN IESLINK IL  ON IL.CODIES1    = I1.CODIES1
          LEFT  JOIN IESIRI1 AE1 ON AE1.CODIES1   = IL.CODLINIEAVIZ
          LEFT JOIN IESIRI   AE  ON AE1.CODIES    = AE.CODIES
          LEFT  JOIN LIVR    L   ON L.CODIES      = COALESCE(AE1.CODIES, I.CODIES) AND I1.TIPLINIE = ''=''
          LEFT  JOIN LIVR1   L1  ON L1.CODLIVR    = L.CODLIVR AND L1.CODIES1 = COALESCE(AE1.CODIES1,I1.CODIES1)
          LEFT  JOIN NIRSTOC NS  ON NS.CODNIRSTOC = L1.CODNIRSTOC
          LEFT  JOIN NIR     N   ON N.CODNIR      = NS.CODNIR
          LEFT  JOIN LIVRVAL LV  ON LV.CODLIVR1   = L1.CODLIVR1
          '||sJoinAchiz||'
        WHERE '||sWhere||' AND coalesce(I.InfoCM,0) = 0 AND I.ANULAT = 0 AND I.OPERAT = 1 AND COALESCE(I1.CANT,0) &lt;&gt; 0
          AND I.TIPDOC::VARCHAR IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''TIPDOC'')
                  AND I1.TIPLINIE IN ('||sTipLin||') '||coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'')||') b_pg
      GROUP BY CODOBIECT, PARTENER, CODLOCATIE, GEST, CODIOART, AGENT )
    SELECT
      COALESCE (IG.CODOBIECT, STOC.CODOBIECT) CodObiect, NAO.DENUMIRE, ' || coalesce(sCampUM,'') || ', NP.DEN_PART, NG.DEN_GEST, IOA.DEN_IOART, NCA.DEN_CLASEA, NAO.CODINTERN, NAO.CODEXTERN,
      PROD.DEN_PART, NCP.DEN_CLASEP,
      LSOC.DEN_LOCALIT||'' ''||(SELECT GETADRESA.wme_result FROM GETADRESA(NULL, SSOC.SECTOR, SSOC.STRADA, SSOC.NR1, SSOC.NR2, SSOC.BLOC, SSOC.SCARA, SSOC.ETAJ, SSOC.APART, SSOC.CODPOSTAL)),
      LLIV.DEN_LOCALIT||'' ''||(SELECT GETADRESA.wme_result FROM GETADRESA(NULL, SLIV.SECTOR, SLIV.STRADA, SLIV.NR1, SLIV.NR2, SLIV.BLOC, SLIV.SCARA, SLIV.ETAJ, SLIV.APART, SLIV.CODPOSTAL)),
      (Case  When AG.CODPERS=0 then AG.NUME else AG.NUME||'' ''||AG.PRENUME end), (Case  When AGI.CODPERS=0 then AGI.NUME else AGI.NUME||'' ''||AGI.PRENUME end),
      coalesce(STOC.STOCINI,0), coalesce(STOC.VALACHIZ,0), coalesce(NAO.MASA,0), coalesce(NAO.VOLUM,0), COALESCE(IG.VALACHIZ,0)'
      || coalesce(sArtAtrib1,'') || coalesce(sSelAUX,'')
      || coalesce(PKG_LIST_BASE_VANZPER_CAMPURI('INSERT', 'IG'),'')
      || ', coalesce(JLIV.Simbauto, JSOC.Simbauto), NCP.CODCLASEP, NG.CODGEST, NG.CODSUBUNIT'
      || gUserAlias || '
    FROM IG
      ' || coalesce(CASE WHEN fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vFaraVanz') THEN 'FULL' ELSE 'LEFT' END ,'') || ' JOIN STOC ON STOC.CODOBIECT = IG.CODOBIECT AND STOC.GEST = IG.GEST AND STOC.CODIOART = IG.CODIOART
      LEFT JOIN NARTOBJ NAO       ON NAO.CODOBIECT       = COALESCE(IG.CODOBIECT, STOC.CODOBIECT)
      LEFT JOIN NART NA           ON NA.CODARTICOL       = NAO.CODARTICOL
      LEFT JOIN NUM               ON NUM.CODUM           = NA.UM ' || coalesce(sJoinU1,'') || coalesce(sJoinUMA,'') || coalesce(sJoinCL,'') || '
      LEFT JOIN NGEST NG          ON NG.CODGEST          = COALESCE(IG.GEST,STOC.GEST)
      LEFT JOIN NPART NP          ON NP.CODPART          = IG.PARTENER
      LEFT JOIN NPART PROD        ON PROD.CODPART        = NAO.CODPRODUCATOR
      LEFT JOIN IOART IOA         ON IOA.CODIOART        = COALESCE(IG.CODIOART,STOC.CODIOART)
      LEFT JOIN NCLASEA NCA       ON NCA.CODCLASEA       = NA.CLASA
      LEFT JOIN NCLASEP NCP       ON NCP.CODCLASEP       = NP.CODCLASA
      LEFT JOIN NPERS AG          ON AG.CODPERS          = IG.AGENT
      LEFT JOIN NAGENDA SSOC      ON SSOC.CODPART        = IG.PARTENER AND SSOC.SEDIUSOCIAL BETWEEN 4 AND 7 AND COALESCE(SSOC.INACTIV, 0) = 0
      LEFT JOIN NPERS AGI         ON AGI.CODPERS         = COALESCE(SSOC.CODAGENT,0)
      LEFT JOIN NLOCALIT LSOC     ON LSOC.CODLOCALIT     = SSOC.CODLOCALIT
      LEFT JOIN NJUDET JSOC       ON JSOC.CODJUDET       = LSOC.CODJUDET
      LEFT JOIN NAGENDA SLIV      ON SLIV.CODAGENDA      = IG.CODLOCATIE
      LEFT JOIN NLOCALIT LLIV     ON LLIV.CODLOCALIT     = SLIV.CODLOCALIT
      LEFT JOIN NJUDET JLIV       ON JLIV.CODJUDET       = LLIV.CODJUDET
      LEFT JOIN TRASEULIVR TLIV   ON TLIV.CODTRASEULIVR  = SLIV.CODTRASEU
      LEFT JOIN NTIPSEDII TIPSLIV ON TIPSLIV.CODTIPSEDIU = SLIV.CODTIPSEDIU
      LEFT JOIN PRETM PRETIMP     ON PRETIMP.CODOBIECT   = NAO.CODOBIECT AND PRETIMP.SUBUNITATEA = NG.CODSUBUNIT AND PRETIMP.IMPLICIT = 1' || gSuplJoins;

  INSERT INTO x (view_name, test) VALUES ('vanzper', coalesce(sInsert,'') || coalesce(sSelect,''));
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);

  IF vNrCol &gt; 1 AND vVariatie THEN
    sUpdate := 'UPDATE ' || tmpName || '
      SET ';

     FOR k IN 1..vNrCol - 1 LOOP
      IF vCantitativ THEN
        sUpdate := sUpdate || '
        VV'||To_Char(k,'fm999')||' = (CASE WHEN C'||To_Char(k,'fm999')||' = 0 THEN 0 ELSE (C'||To_Char(k+1,'fm999')||'-C'||To_Char(k,'fm999')||')/C'||To_Char(k,'fm999')||'*100 END),';
      END IF;
      IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vValoric') THEN
        sUpdate := sUpdate || '
        VV'||To_Char(k,'fm999')||' = (CASE WHEN V'||To_Char(k,'fm999')||' = 0 THEN 0 ELSE (V'||To_Char(k+1,'fm999')||'-V'||To_Char(k,'fm999')||')/V'||To_Char(k,'fm999')||'*100 END),';
      END IF;
    END LOOP;
    sUpdate := SubStr(sUpdate, 1, Length(sUpdate) - 1);
    PERFORM LIST_EXECUTE_IMMEDIATE(sUpdate, 0, 0);
  END IF;

  IF vCantCutii THEN
    sUpdate := 'UPDATE ' || tmpName || '
      SET CC0 = C0/ParCutie';

    FOR k IN 1..vNrCol LOOP
      sUpdate := sUpdate ||', CC'||To_Char(k,'fm999')||' = C'||To_Char(k,'fm999')||'/ParCutie';
    END LOOP;
    sUpdate := coalesce(sUpdate,'') || '
      WHERE COALESCE(ParCutie,0) &lt;&gt; 0';
    PERFORM LIST_EXECUTE_IMMEDIATE(sUpdate, 0, 0);
  END IF;

  IF vCantPaleti THEN
    sUpdate := 'UPDATE ' || tmpName || '
        SET CP0 = C0/ParPalet';
    FOR k IN 1..vNrCol LOOP
      sUpdate := sUpdate ||', CP'||To_Char(k,'fm999')||' = C'||To_Char(k,'fm999')||'/ParPalet';
    END LOOP;
    sUpdate := coalesce(sUpdate,'') || '
      WHERE COALESCE(ParPalet,0) &lt;&gt; 0';
    PERFORM LIST_EXECUTE_IMMEDIATE(sUpdate, 0, 0);
  END IF;

  IF vCantitativ AND  vTipUM = 2 THEN
    sUpdate := 'UPDATE ' || tmpName || '
        SET C0 = C0/ParCant';
    FOR k IN 1..vNrCol LOOP
      sUpdate := sUpdate ||', C'||To_Char(k,'fm999')||' = C'||To_Char(k,'fm999')||'/ParCant';
    END LOOP;
    sUpdate := coalesce(sUpdate,'') || '
      WHERE COALESCE(ParCant,0) &lt;&gt; 0';
    PERFORM LIST_EXECUTE_IMMEDIATE(sUpdate, 0, 0);
  END IF;

  IF vCantitativ AND  vTipUM = 3 THEN
    sUpdate := 'UPDATE ' || tmpName || '
        SET C0 = (Case  When MASA=0 then C0/ParCant else C0*MASA end)';
    FOR k IN 1..vNrCol LOOP
     sUpdate := sUpdate ||', C'||To_Char(k,'fm999')||' = (CASE WHEN MASA = 0 THEN C'||To_Char(k,'fm999')||'/ParCant ELSE C'||To_Char(k,'fm999')||'*MASA END)';
    END LOOP;
    sUpdate := coalesce(sUpdate,'') || '
      WHERE COALESCE(ParCant,0) &lt;&gt; 0 OR MASA &lt;&gt;0';
    PERFORM LIST_EXECUTE_IMMEDIATE(sUpdate, 0, 0);
  END IF;

  IF vCantitativ AND  vTipUM = 4 THEN
    sUpdate := 'UPDATE ' || tmpName || '
        SET C0 = (Case  When VOLUM=0 then C0/ParCant else C0*VOLUM end)';
    FOR k IN 1..vNrCol LOOP
      sUpdate := sUpdate ||', C'||To_Char(k,'fm999')||' = (CASE WHEN VOLUM = 0 THEN C'||To_Char(k,'fm999')||'/ParCant ELSE C'||To_Char(k,'fm999')||'*VOLUM END)';
    END LOOP;
    sUpdate := coalesce(sUpdate,'') || '
      WHERE COALESCE(ParCant,0) &lt;&gt; 0 OR VOLUM &lt;&gt;0';
    PERFORM LIST_EXECUTE_IMMEDIATE(sUpdate, 0, 0);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_config_sumesoldselect</obj_name>
  <obj_hashval>5da86077f6ad4305c38f9c9a87a3f8fb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_config_sumesoldselect(tmptable character varying, visible_cols character varying, sum_cols character varying, where_clause character varying, order_cols character varying, sold_cols character varying, resetsold_cols character varying, calc_cols character varying, sum_calc character varying, sold_calc character varying, bcentralizat boolean, finterval character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_COLS           RECORD;
  strSelect        varchar := 'SELECT null';
  strSelectAll     varchar := 'SELECT ';
  strSelectFooter  varchar := 'SELECT ';
  strSelectDetalii varchar := 'SELECT ';
  strSelectSum     varchar := 'SELECT ';
  strWhereClause   varchar := 'WHERE ';
  nrCols           integer := 0;
  sNVL_header      varchar := '';
  sNVL_footer      varchar := '';
  sWhere           varchar := '';
  i                integer;
  sColoaneCalc     varchar := '';
  nrCalcCols       integer;
  allCols          varchar := '';
  sCalcCols        varchar := '';
  sSumCalcCols     varchar := '';
  sSumHeaderFooter varchar := '';
  fara_total       varchar := '';
  sType            varchar := '';
  vSumCols         varchar := ','||Lower(REPLACE(sum_cols, ' ', ''))||',';
  sOrderCols       varchar := '';
  auxSelectDetalii varchar := '';
BEGIN
  -- Stef 29.07.2020 -- AS
  IF COALESCE(LENGTH(TRIM(order_cols)),0) &gt; 0 THEN
    sOrderCols  := order_cols||', ';
  END IF;

  FOR V_COLS IN (SELECT COLUMN_NAME::varchar COLUMN_NAME FROM information_schema.columns WHERE TABLE_NAME = lower(tmptable)) LOOP
    strSelectAll     := strSelectAll     || v_cols.column_name || ',';
    strSelectDetalii := strSelectDetalii || v_cols.column_name || ',';
    allCols          := allCols          || v_cols.column_name || ',';
    IF POSITION(','||v_cols.column_name||',' IN vSumCols) &gt; 0 THEN
      strSelectFooter := strSelectFooter ||         v_cols.column_name || ',';
      strSelectSum    := strSelectSum    || 'SUM('||v_cols.column_name || ') ' ||v_cols.column_name || ',';
    ELSE
      SELECT
        PKG_LIST_CONFIG_GetNVLClause.sNVL_header,
        PKG_LIST_CONFIG_GetNVLClause.sNVL_footer,
        PKG_LIST_CONFIG_GetNVLClause.sWhere,
        PKG_LIST_CONFIG_GetNVLClause.sType
      INTO sNVL_header, sNVL_footer, sWhere, sType
      FROM PKG_LIST_CONFIG_GetNVLClause( tmptable, v_cols.column_name, sNVL_header, sNVL_footer, sWhere, sType);
      strSelectFooter := strSelectFooter || sNVL_footer || ' ' || v_cols.column_name || ',';
      strSelectSum    := strSelectSum || 'NULL::'||sType||' AS '|| v_cols.column_name || ',';
    END IF;
  END LOOP;

  allCols      := substr(allCols, 1, length(allCols) - 1);
  SELECT
    PKG_LIST_CONFIG_getColoanefromExpresii.WME_RESULT,
    PKG_LIST_CONFIG_getColoanefromExpresii.calc_cols
  INTO sColoaneCalc, calc_cols
  FROM PKG_LIST_CONFIG_getColoanefromExpresii(NULL,calc_cols,nrCalcCols);
  sCalcCols    := calc_cols;
  sSumCalcCols := sum_calc;
  fara_total   := '';
  IF Length(calc_cols) &gt; 0 THEN
    SELECT
      PKG_LIST_CONFIG_PrelucreazaColCalc.pcoloanecalc,
      PKG_LIST_CONFIG_PrelucreazaColCalc.psumcalc,
      PKG_LIST_CONFIG_PrelucreazaColCalc.psumheaderfooter
    INTO sCalcCols,sSumCalcCols,sSumHeaderFooter
    FROM PKG_LIST_CONFIG_PrelucreazaColCalc(sCalcCols,sSumCalcCols,sSumHeaderFooter,fara_total);
    strSelectDetalii := strSelectDetalii || sCalcCols;
    strSelectFooter  := strSelectFooter || sSumHeaderFooter;
    strSelectSum     := strSelectSum || sSumCalcCols;
  END IF;
  strSelectAll := strSelectAll || ' (row_number() over ())::numeric AS NRCRT FROM ' ||UPPER(tmptable);
  IF length(TRIM(both ' ' from where_clause)) &gt; 0 then strSelectAll := strSelectAll || ' WHERE ' || where_clause;  END IF;

  IF LENGTH(TRIM(order_cols))&gt;0 THEN
    strSelectAll     := strSelectAll || ' ORDER BY ' || sOrderCols ||'NRCRT';
  else
    strSelectAll     := strSelectAll || ' ORDER BY NRCRT';
  end if;

  select
    PKG_LIST_CONFIG_GetSoldSumClause.WME_Result,
    PKG_LIST_CONFIG_GetSoldSumClause.pexp
  INTO
    auxSelectDetalii,
    nrCols
  from PKG_LIST_CONFIG_GetSoldSumClause(null, sold_cols,resetsold_cols,order_cols,nrCols,False);

  strSelectDetalii := strSelectDetalii || ' ' ||auxSelectDetalii;
  strSelectDetalii := strSelectDetalii || ' NRCRT';

  for i IN 1.. nrCols LOOP
    strSelectFooter:= strSelectFooter||'EXP_'||i||',';
    strSelectSum   := strSelectSum   ||'NULL::NUMERIC AS EXP_'||i||',';
    allCols        := allCols        ||',EXP_'||i;
  END LOOP;

  strSelectFooter  := strSelectFooter || 'NRCRT ';
  IF length(calc_cols) &gt; 0 THEN allCols := allCols || ',' || sColoaneCalc; END IF;
  allCols         := allCols || ',NRCRT';
  strSelectFooter := strSelectFooter || ' FROM (' || strSelectSum || ' NULL::numeric AS NRCRT FROM ' || tmptable || ') sql';
  IF COALESCE(LENGTH(TRIM(where_clause)),0) &gt; 0 THEN
    strSelectFooter := strSelectFooter || ' WHERE ' || where_clause;
  END IF;
  strSelectDetalii := strSelectDetalii || ' FROM(' || strSelectAll || ') sql';
  strSelect        := 'SELECT ' || allCols || ',';
  strSelect        := substr(strSelect, 1, length(strSelect) - 1);
  strSelect        := strSelect || '  FROM ( ';

  IF COALESCE(LENGTH(TRIM(both ' ' from sum_cols)), 0) &gt; 0
  then strSelect := strSelect || strSelectDetalii || ' UNION ALL ';
  ELSE strSelect := strSelect || strSelectDetalii;
  END IF;

  IF COALESCE(LENGTH(TRIM(order_cols)),0) &gt; 0 THEN
    IF COALESCE(LENGTH(TRIM(sum_cols)),0) &gt; 0
    THEN strSelect := strSelect || strSelectFooter || ' ) sql ORDER BY ' ||sOrderCols || 'NRCRT';
    ELSE strSelect := strSelect || ' ) sql ORDER BY ' || sOrderCols || 'NRCRT';
    END IF;
  ELSE
    strSelect := strSelect || strSelectFooter || ' ) sql ORDER BY NRCRT';
  END IF;

  strSelect := 'SELECT SQL.*, (row_number() over ())::numeric AS GLOBALID FROM (' || STRSELECT ||') sql ';
  IF bCentralizat THEN strSelect := 'SELECT * FROM  (' || strSelect || ') sql WHERE  (NRCRT &gt;= ' ||PKG_LIST_CONFIG_get_Sid_footer|| ' OR NRCRT &lt;= -' ||PKG_LIST_CONFIG_get_Sid_header|| ')  ';
    IF COALESCE(LENGTH(TRIM(fInterval)),0) &gt; 0 THEN
      strSelect := strSelect || fInterval;
    END IF;
  END IF;

  RETURN strSelect;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_locmunca_sp_postrecords</obj_name>
  <obj_hashval>6c7dd40b4c97ac7c8f94cfd3890b799c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_locmunca_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  StartDate Date;
  Nr        numeric;
  DayOfWeek numeric;
  MaxData   Date;
  IsSpecial numeric;
BEGIN
  --Florin 18.06.2025 - sinc. Oracle
  --Laura 27.11.2021 - sinc Oracle (26.11.2021)
  --Laura 18.11.2021 - sinc Oracle (17.11.2021)
  --Adina 09.07.2021 - sinc.Oracle din 08.07.2021
  --Adina 21.04.2021 - sinc.Oracle din 20.04.2021
  --Adina 16.04.2021 - sinc.Oracle din 15.04.2021
  IF  Operation = 0 THEN
    SELECT CodLoc INTO RecId FROM TMP_LOCMUNCA;

    UPDATE LOCMUNCA
    SET
    (SIMBOL, DENUMIRE, TIP, ACTIVI, DSV, CodLocDef, MinuteOn, MinuteOff, SPECIAL, FARA_GANT ) = (SELECT SIMBOL, DENUMIRE, TIP, ACTIVI, DSV, CodLocDef, MinuteOn, MinuteOff, SPECIAL, FARA_GANT  FROM TMP_LOCMUNCA)
    WHERE
     CodLoc = RecId;

    DELETE FROM LOCMUNCA1 LC1
    WHERE LC1.CodLoc = RecId AND  NOT EXISTS (SELECT CodLoc1 FROM TMP_LOCMUNCA1 TMP1 WHERE TMP1.CodLoc1 = LC1.CodLoc1);

    FOR v_rec IN (SELECT * FROM TMP_LOCMUNCA1) LOOP
      IF  COALESCE( v_rec.CodLoc1, 0) &gt; 0 THEN
        UPDATE LOCMUNCA1
        SET
        CODMIFIX   = v_rec.codmifix,
        ORE        = v_rec.ore,
        CODUTILAJ  = v_Rec.Codutilaj,
        CODGEST    = v_Rec.CodGest,
        NICKNAME   = v_Rec.NICKNAME,
        CodLocatie = v_Rec.CodLocatie
        WHERE
         CodLoc1 = v_rec.CodLoc1;
      ELSE
        Nr := NEXTVAL('SEQ_LOCMUNCA1_CODLOC1');
        UPDATE TMP_ORELM SET CODLM1 = Nr WHERE CODLM1 = v_rec.CODLOC1;
           update TMP_LocMunca2 set CODLoc1 = Nr where CODLoc1 = v_rec.CODLOC1;
        INSERT INTO LOCMUNCA1 (CODLOC1, CODLOC, NICKNAME, CODMIFIX, ORE, CODUTILAJ, CODGEST,CodLocatie)
        VALUES (Nr, RecId, v_Rec.NICKNAME, v_Rec.CODMIFIX, v_Rec.ore, v_rec.codutilaj, v_rec.codgest, v_rec.CodLocatie);
      END IF;
    END LOOP;

    DELETE FROM LOCMUNCA2 LC2
      WHERE LC2.CodLoc = RecId AND NOT EXISTS (SELECT CodLoc2 FROM TMP_LOCMUNCA2 TMP2 WHERE TMP2.CodLoc2 = LC2.CodLoc2);

    FOR v_rec IN (SELECT * FROM TMP_LOCMUNCA2) LOOP
      IF COALESCE(v_rec.CodLoc2, 0) &gt; 0 THEN
        UPDATE LOCMUNCA2 SET
          codLoc1Asoc =  v_rec.codLoc1Asoc ,
          OreStart    =  v_rec.OreStart    ,
          DataStart   =  v_rec.DataStart   ,
          OreStop     =  v_Rec.OreStop     ,
          DataStop    =  v_Rec.DataStop    ,
          OreActiv    =  v_rec.OreActiv    ,
          MinuneOn    =  v_Rec.MinuneOn    ,
          MinuneOff   =  v_Rec.MinuneOff
        WHERE CodLoc2 = v_rec.CodLoc2;
      else
        Nr := NEXTVAL('SEQ_LOCMUNCA2_CODLOC2');
    INSERT INTO LOCMUNCA2
    ( codloc2 , codloc1 , codloc , codLoc1Asoc, OreStart , DataStart , OreStop , DataStop , OreActiv, MinuneOn, MinuneOff)
    Values
    (Nr, v_rec.codloc1 , RecID, v_rec.codLoc1Asoc, v_rec.OreStart , v_rec.DataStart , v_rec.OreStop , v_rec.DataStop , v_rec.OreActiv, v_rec.MinuneOn, v_rec.MinuneOff);
      END IF;
    END LOOP;

  ELSE
    SELECT NEXTVAL('SEQ_LOCMUNCA_CODLOC') INTO RecId;

    INSERT INTO LOCMUNCA(CodLoc, Simbol, Denumire, Tip, ACTIVI, DSV, CodLocDef, MinuteOn, MinuteOff, SPECIAL, FARA_GANT)
    SELECT RecId, Simbol, Denumire, Tip, ACTIVI, DSV, CodLocDef, MinuteOn, MinuteOff, SPECIAL, FARA_GANT
    FROM TMP_LOCMUNCA;

    FOR v_rec IN (SELECT * FROM TMP_LOCMUNCA1) LOOP
      SELECT NEXTVAL('SEQ_LOCMUNCA1_CODLOC1') INTO Nr;
      update TMP_LocMunca2 set CODLOC1 = Nr where CODLOC1 = v_rec.CODLOC1;
      UPDATE TMP_ORELM SET CODLM1 = Nr WHERE CODLM1 = v_rec.CODLOC1;
      INSERT INTO LOCMUNCA1 (CODLOC1, CODLOC, NICKNAME, CODMIFIX, ORE, CODUTILAJ, CODGEST,CodLocatie)
      VALUES (Nr, RecId, v_Rec.NICKNAME, v_Rec.CODMIFIX, v_Rec.ore, v_rec.codutilaj, v_rec.codgest, v_rec.CodLocatie);
    END LOOP;
       INSERT INTO LOCMUNCA2 ( codloc2 , codloc1 , codloc , codLoc1Asoc, OreStart , DataStart , OreStop , DataStop , OreActiv, MinuneOn, MinuneOff)
    SELECT nextval('seq_locmunca2_codloc2'), codloc1 , RecID, codLoc1Asoc, OreStart , DataStart , OreStop , DataStop , OreActiv, MinuneOn, MinuneOff
    FROM TMP_LOCMUNCA2;
  END IF;

  Select Coalesce(Special, 0) into IsSpecial from TMP_Locmunca;

  if IsSpecial = 1 then
    DELETE FROM ORELM OLM WHERE OLM.CodLM = RecId;
  else
    StartDate := To_Date('01'||to_char(current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric,'fm00')||to_char(current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric,'fm0000'),'ddmmyyyy');
    StartDate := (SELECT wme_result FROM iso_week_to_date(NULL, (EXTRACT (YEAR FROM StartDate))::numeric, to_char(StartDate,'iw')::numeric));
    DELETE FROM TMP_OreLM WHERE Saptamana &gt; 0;
    DELETE FROM ORELM OLM WHERE CodLM = RecId AND NOT EXISTS (SELECT CodOreLM FROM TMP_OreLM TMP1 WHERE TMP1.CodOreLM = OLM.CodOreLM);

    FOR v_rec IN (SELECT * FROM TMP_ORELM) LOOP
      Select Count(*) into Nr from ORELM where DataLM = V_REC.DataLM and CodLM1 = v_Rec.CodLM1;
      if Nr &gt; 0 then
          UPDATE ORELM SET ORE = v_rec.ore WHERE DataLM = V_REC.DataLM and CodLM1 = v_rec.CodLM1;
      ELSE
          Nr := v_rec.CodORELM;
          if Nr &lt; 0 then Nr := NEXTVAL('SEQ_ORELM_CodORELM'); end if;
          INSERT INTO OreLM (CodORELM, DataLM,CodLM,CodLM1,Ore)
          VALUES (Nr, V_REC.DataLM, V_REC.CodLM, V_REC.CodLM1, V_REC.Ore );
      END IF;
    END LOOP;
  END IF;

  PERFORM NotifyModif( Operation, RecId, 'LOCMUNCA');
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS(524);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mifix_sp_deleterecord</obj_name>
  <obj_hashval>981eb158f341914de801629e5a333c25</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mifix_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  V_MF  RECORD;
  NR    numeric := 0;
  aDoc  varchar;
  ANL   numeric;
  ANM   numeric;
  LUNAL numeric;
  LUNAM numeric;
  ANI   numeric;
  LUNAI numeric;
BEGIN
  --Florin 25.11.2025 - sinc. Oracle
  --Florin 18.11.2025 - sinc. Oracle
  --Florin 28.11.2024 - sinc. Oracle
  --Florin 01.06.2023 - monitor
  --Florin 06.09.2022 - fixat 55455
  --Bogdan 12.08.2022 - 55226 : ca se sterge rezolvarea unui mijloc fix, nu se sterge si numarul de inventar asociat in parc auto.
  --Florin 30.10.2020 - fixat #40471
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_mifix_setct_monitor('MON_15');
  PERFORM PKG_GLOBALS_MarkDirtyJurnal();
  PERFORM PKG_MIFIX_SP_LOCKRECORD( RecId);
  DELETE FROM TMP_MANEVRA;
    delete FROM TMP_MANEVRA_LISTE;
    INSERT INTO TMP_MANEVRA_LISTE
    (FILTRU, VALOARE, FILTRU1, VALOARE1,FILTRU2, VALOARE2)
    (SELECT distinct 'CODMIFIX'::varchar, mf1.CODMIFIX::varchar, 'CODAUTO'::varchar, mf1.codauto::varchar, 'NRINV'::varchar, mf.NRINVENTAR::varchar
       FROM MIFIX1 mf1
       JOIN MIFIX  mf ON mf.CODMIFIX = mf1.CODMIFIX
      WHERE mf1.CODNIRSTOC = RecId
        AND ANSTART * 12 + LUNASTART &gt;=
            getANLUCRU() * 12 + GETLUNALUCRU());
  FOR V_REC IN
  (
  SELECT *
  FROM MIFIX1
  WHERE
     CODNIRSTOC = RecId AND  ANSTART * 12 + LUNASTART &gt;= TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') * 12 + TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999')
  )
  LOOP
    IF fnc_tmpexists('MIFIX1EXT') = 1  THEN
      EXECUTE 'DELETE FROM MIFIX1EXT WHERE CODMIFIX1 =' || V_REC.CODMIFIX1;
    END IF;
    DELETE FROM MIFIX1 WHERE CODMIFIX1 = V_REC.CODMIFIX1;
    INSERT INTO TMP_MANEVRA(CODUNIC) VALUES(V_REC.CODMIFIX);
  END LOOP;

  BEGIN
    SELECT ANINITIAL, LUNAINITIALA INTO ANI, LUNAI FROM FIRMALUNI;
  EXCEPTION WHEN OTHERS THEN
    ANI   := 0;
    LUNAI := 0;
  END;

  IF  TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') = ANI AND  TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999') = LUNAI
  then
     INSERT INTO TMP_MANEVRA_LISTE
        (FILTRU, VALOARE, FILTRU1, VALOARE1, FILTRU2, VALOARE2)
        (SELECT distinct 'CODMIFIX'::varchar,
                         mf1.CODMIFIX::varchar,
                         'CODAUTO'::varchar,
                         mf1.codauto::varchar,
                         'NRINV'::varchar,
                         mf.NRINVENTAR::varchar
           FROM MIFIX1 mf1
           JOIN MIFIX mf
             ON mf.CODMIFIX = mf1.CODMIFIX
          WHERE mf1.CODNIRSTOC = RecId
            AND mf1.ANSTART * 12 + mf1.LUNASTART &lt;
                getANLUCRU() * 12 + getLUNALUCRU());
    FOR V_REC IN (SELECT * FROM MIFIX1
                  WHERE CODNIRSTOC = RecId AND
                        ANSTART * 12 + LUNASTART &lt; TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') * 12 + TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999')
                 )
    LOOP
      IF fnc_tmpexists('MIFIX1EXT') = 1  THEN
        EXECUTE 'DELETE FROM MIFIX1EXT WHERE CODMIFIX1 =' || V_REC.CODMIFIX1;
      END IF;
      DELETE FROM MIFIX1 WHERE CODMIFIX1 = V_REC.CODMIFIX1;
      INSERT INTO TMP_MANEVRA(CODUNIC) VALUES(V_REC.CODMIFIX);
    END LOOP;
  END IF;

  FOR V_REC IN (SELECT CODUNIC FROM TMP_MANEVRA) LOOP
    SELECT COUNT( *) INTO NR FROM MIFIX1 WHERE CODMIFIX = V_REC.CODUNIC;

    IF  NR = 0 THEN
      IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_MIFIX.CT_MONITOR', true))))
      THEN
        BEGIN
          SELECT ' rezolvare mifix nr inventar ' || nrinventar INTO aDoc FROM mifix WHERE codmifix = v_rec.codunic;
        EXCEPTION WHEN others THEN
          aDoc := 'nu am gasit numarul de inventar';
        END;

        PERFORM pkg_userfirme_postlogcucommit( 'MIFIX', (current_setting('PKG_GLOBALS.USERNAME', true)), 'S', RECID, (current_setting('PKG_GLOBALS.FIRMANAME', true)), 1, LAST_DAY( TO_DATE( '01.' || TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999') || '.' || TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999'), 'DD.MM.YYYY')), aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
      END IF;

      DELETE FROM FISAMF WHERE CODMIFIX = V_REC.CODUNIC;

      UPDATE MIFIX
          SET
            CODMIFIXNOU = NULL,
            ANLUNAMIFIXNOU = NULL
          WHERE
            CODMIFIXNOU =  V_REC.CODUNIC;

      DELETE FROM MIFIX  WHERE CODMIFIX = V_REC.CODUNIC;

        UPDATE nparcaut
               SET nrinv = null
            WHERE (codnparcaut, nrinv) IN
                 ( SELECT distinct tl.valoare1::numeric, tl.valoare2::numeric
                    FROM tmp_manevra_liste tl
                   where tl.valoare = V_REC.CODUNIC::varchar);

      DELETE FROM MASTERMIFIX WHERE CODNIRSTOC = RECID;

      FOR V_MF IN (SELECT CODBUGETMF FROM BUGETMF WHERE CODMIFIX = V_REC.CODUNIC) LOOP
        DELETE FROM BUGETMF1 WHERE CODBUGETMF = V_MF.CODBUGETMF;
        DELETE FROM BUGETMF  WHERE CODBUGETMF = V_MF.CODBUGETMF;
      END LOOP;
    END IF;
  END LOOP;

  DELETE FROM MASTERMIFIX WHERE CODNIRSTOC = RECID AND COALESCE((SELECT COUNT( *) FROM MIFIX1 WHERE CODNIRSTOC = RECID), 0) = 0;

  ANL   := TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU'  , true)),'999999999999999999');
  LUNAL := TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999');

  BEGIN
    SELECT ANMAXIM, LUNAMAXIMA INTO ANM, LUNAM FROM FIRMALUNI;
  EXCEPTION WHEN OTHERS THEN
    ANM   := ANL;
    LUNAM := LUNAL;
  END;

  PERFORM NotifyModif( 2, RECID, 'MIFIX');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nmvs_insertnmvs</obj_name>
  <obj_hashval>ac91160bfec0fd89d22046829b25a35a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nmvs_insertnmvs(INOUT agtin character varying, INOUT alot character varying, INOUT aexp character varying, INOUT asn character varying, INOUT askemetype character varying, INOUT anewcodnmvs numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  SELECT NEXTVAL('SEQ_NMVS_CODNMVS') INTO aNewCodNMVS;

  INSERT INTO nmvs(codnmvs, gtin, dataexp, lot, sn, skemetype)
  VALUES(aNewCodNMVS, agtin, aexp, alot, asn, aSkemeType);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_setct_monitor</obj_name>
  <obj_hashval>51c7c76f73684c428d4383704be1bdbe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOM_ARTICOL.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_set_stopaj_salarii</obj_name>
  <obj_hashval>ac8b118c8799378d6b9828f410dc5e92</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_set_stopaj_salarii()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  cArtCASS     numeric := 0;
  cArtImpozit  numeric := 0;
  cTaxaCASS    numeric := 0;
  cTaxaImpozit numeric := 0;
  aBazaCass    numeric := 0;
  aBazaImp     numeric := 0;
  aBNetCass    numeric := 0;
  aBNetImp     numeric := 0;
  aValCass     numeric := 0;
  aValImp      numeric := 0;
  Nr           numeric;
  aCODFISCAL   varchar;
  vNullDate    date := To_Date ('1900', 'yyyy');
  pjArtCass    numeric(20,7);
  lcArtCass    numeric(1,0);
  pjDimCass    numeric(12,2);
  coefDimCass  numeric;
  pjArtImp     numeric(20,7);
  lcArtImp     numeric(1,0);
  pjDimImp     numeric(12,2);
  coefDimImp   numeric;
  aPos         numeric;
  aNume        varchar;
  aPrenume     varchar;
  vDataSf      date;
  vSubunit     NUMERIC(20) := 1;
BEGIN
  --Florin 30.10.2024 - sinc. Oracle
  --Florin 26.08.2024 - fixat 63132
  --Stef 31.01.2024
  cTaxaCASS := fnc_getvalconstantalucru('CTaxaCASS')::NUMERIC;
  IF GETSUBUNITATE() &lt;&gt; 1 AND fnc_getvalconstantalucru('Holding')::NUMERIC &lt;&gt; 2 THEN
    vSubunit := GETSUBUNITATE();
  END IF;
  IF cTaxaCASS &gt; 0 THEN
    SELECT  DISTINCT
      LAST_VALUE (CODSERVFACT)    OVER (ORDER BY ANSTART * 12 + LUNASTART range between unbounded preceding and unbounded following),
      LAST_VALUE (VALOARE)        OVER (ORDER BY ANSTART * 12 + LUNASTART range between unbounded preceding and unbounded following),
      LAST_VALUE (LACEAPLIC)      OVER (ORDER BY ANSTART * 12 + LUNASTART range between unbounded preceding and unbounded following),
      LAST_VALUE (PROCDIMINUAREB) OVER (ORDER BY ANSTART * 12 + LUNASTART range between unbounded preceding and unbounded following)
    INTO
      cArtCASS, pjArtCass, lcArtCass, pjDimCass
    FROM NTAXE1
    WHERE CodTaxa = cTaxaCASS AND ANSTART * 12 + LUNASTART &lt;= getanlunalucru();
  ELSE
    cArtCASS := fnc_getvalconstantalucru('CArtCASS')::NUMERIC;
    SELECT  DISTINCT
      LAST_VALUE (VALOARE)        OVER (ORDER BY ANSTART * 12 + LUNASTART range between unbounded preceding and unbounded following) ,
      LAST_VALUE (LACEAPLIC)      OVER (ORDER BY ANSTART * 12 + LUNASTART range between unbounded preceding and unbounded following) ,
      LAST_VALUE (PROCDIMINUAREB) OVER (ORDER BY ANSTART * 12 + LUNASTART range between unbounded preceding and unbounded following)
    INTO pjArtCass, lcArtCass, pjDimCass
    FROM NTAXE1
    WHERE CODSERVFACT = cArtCASS AND ANSTART * 12 + LUNASTART &lt;= getanlunalucru();
  END IF;
  coefDimCass  := 1 - Coalesce (pjDimCass, 0) / 100;

  cTaxaImpozit := fnc_getvalconstantalucru('cTaxaImpozit')::NUMERIC;
  IF cTaxaImpozit &gt; 0 THEN
    SELECT DISTINCT
      LAST_VALUE (CODSERVFACT)    OVER (ORDER BY ANSTART * 12 + LUNASTART range between unbounded preceding and unbounded following) ,
      LAST_VALUE (VALOARE)        OVER (ORDER BY ANSTART * 12 + LUNASTART range between unbounded preceding and unbounded following) ,
      LAST_VALUE (LACEAPLIC)      OVER (ORDER BY ANSTART * 12 + LUNASTART range between unbounded preceding and unbounded following) ,
      LAST_VALUE (PROCDIMINUAREB) OVER (ORDER BY ANSTART * 12 + LUNASTART range between unbounded preceding and unbounded following)
    INTO cArtImpozit, pjArtImp, lcArtImp, pjDimImp
    FROM NTAXE1
    WHERE CodTaxa = cTaxaImpozit AND ANSTART*12+LUNASTART &lt;= getanlunalucru();
  ELSE
    cArtImpozit := fnc_getvalconstantalucru('cArtImpozit')::NUMERIC;
    SELECT  DISTINCT
      LAST_VALUE (VALOARE)        OVER (ORDER BY ANSTART * 12 + LUNASTART range between unbounded preceding and unbounded following) ,
      LAST_VALUE (LACEAPLIC)      OVER (ORDER BY ANSTART * 12 + LUNASTART range between unbounded preceding and unbounded following) ,
      LAST_VALUE (PROCDIMINUAREB) OVER (ORDER BY ANSTART * 12 + LUNASTART range between unbounded preceding and unbounded following)
    INTO pjArtImp, lcArtImp, pjDimImp
    FROM NTAXE1
    WHERE CODSERVFACT = cArtImpozit AND ANSTART*12+LUNASTART &lt;= getanlunalucru();
  END IF;
  coefDimImp := 1 - Coalesce (pjDimImp, 0) / 100;

  DELETE FROM Tmp_stopaj;
  INSERT INTO Tmp_stopaj (Nume, Prenume, BazaCass, ContrCass) VALUES ('.?.', 'Sursa', getanlucru() , getlunalucru() );

  FOR v_rec IN (
    SELECT  DISTINCT
      i1.CodIntr, i.Partener, p.Den_Part, pcf.CodFiscal CNP, p1.SimbolCASS, CASE WHEN c.codcontract IS NULL THEN 0 ELSE 26 END TipAsig,
      Min(C.DataStart) OVER (PARTITION BY i.Partener) DataAng, Max(C.DataStop) OVER (PARTITION BY i.Partener) DataSf
    FROM intrari1                       i1
      INNER JOIN Intrari              i ON i.codIntr = i1.CodIntr
      INNER JOIN NPart                p ON p.codPart = i.Partener
      INNER JOIN (
        SELECT  DISTINCT codpart, LAST_VALUE (SimbolCass) OVER (partition by CodPart ORDER BY ANSTART * 12 + LUNASTART range between unbounded preceding and unbounded following) SIMBOLCASS
        FROM NPART1
        WHERE ANSTART*12+LUNASTART &lt;= getanlunalucru()
      ) p1  ON p1.codpart = i.Partener
      INNER JOIN npartcodfisc                                    pcf ON pcf.CODPART = i.Partener
      LEFT JOIN contract                                         c   ON c.codcontract = i.codcontract
      INNER JOIN npartcodfisc pcf1 ON pcf1.CODPART = i.Partener
      LEFT JOIN contract c1 ON c1.codcontract = i.codcontract
    WHERE Coalesce(i1.Taxa, 0) &gt; 0
      AND i.TipDoc = 4
      AND i.An * 12 + i.luna = getanlunalucru()
      AND Coalesce(p.Persoanafizica, 0) = 1
      AND pcf.PRINCIPAL = 1
      AND 1 = CASE WHEN c.codcontract IS NULL AND i.an &gt;= 2104 THEN 0 ELSE 1 END
      AND (vSubunit = 1 OR vSubunit = i.SUBUNITATEA)
  ) LOOP
    SELECT Sum (BazaCASS), Sum (ValCass) INTO aBazaCASS, aValCass
    FROM (
      SELECT  DISTINCT
        (
          SELECT  DISTINCT LAST_VALUE (t.Cant * t.PU) OVER (ORDER BY t.indexlocal range between unbounded preceding and unbounded following)
          FROM intrari1 t
          WHERE t.codintr = i1.codintr AND t.indexlocal &lt; i1.indexlocal AND NOT t.CodObiect IN (cArtCASS, cArtImpozit)
       ) BAZACASS,
       i1.Cant * i1.PU VALCASS
      FROM intrari1 i1
      WHERE CodIntr = v_rec.CodIntr AND Coalesce(i1.Taxa,0) &gt; 0 AND i1.CodObiect = cArtCASS
    ) A_PG;

    SELECT Sum (BazaImp), Sum (ValImp) INTO aBazaImp, aValImp
    FROM (
      SELECT DISTINCT
        (
          SELECT  DISTINCT LAST_VALUE (t.Cant * t.PU) OVER (ORDER BY t.indexlocal range between unbounded preceding and unbounded following)
          FROM intrari1 t
          WHERE t.codintr = i1.codintr AND t.indexlocal &lt; i1.indexlocal AND NOT t.CodObiect IN (cArtCASS, CArtImpozit)
        ) BAZAIMP,
        i1.Cant * i1.PU VALIMP
      FROM intrari1 i1
      WHERE CodIntr = v_rec.CodIntr AND Coalesce(i1.Taxa,0) &gt; 0 AND i1.CodObiect = cArtImpozit
    ) B_PG;

    IF    Coalesce(lcArtCass,0)  &lt;&gt; 6 THEN aBazaCass := Coalesce( aBazaCass ,0); aBNetCass := aBazaCass;
    ELSIF Coalesce(pjArtCass,0)   = 0 THEN aBazaCass := 0;                       aBNetCass := 0;
    ELSIF Coalesce(coefDimCass,0) = 0 THEN aBazaCass := 0;                       aBNetCass := 0;
    ELSE                                   aBazaCass := Round(Coalesce(aValCass, 0) * 100 / (coefDimCass*pjArtCass), 2);
                                           aBNetCass := Round(Coalesce(aValCass, 0) * 100 / pjArtCass, 2);
    END IF;

    IF    Coalesce(lcArtImp,0)  &lt;&gt; 6  THEN aBazaImp  := Coalesce( aBazaImp ,0);  aBNetImp := aBazaImp;
    ELSIF Coalesce(pjArtImp,0)   = 0  THEN aBazaImp  := 0;                       aBNetImp := 0;
    ELSIF Coalesce(coefDimImp,0) = 0  THEN aBazaImp  := 0;                       aBNetImp := 0;
    ELSE                                   aBazaImp  := Round(Coalesce(aValImp, 0) * 100 / (coefDimImp*pjArtImp), 2);
                                           aBNetImp  := Round(Coalesce(aValImp, 0) * 100 / pjArtImp, 2);
    END IF;

    aBazaCASS := Coalesce(Abs(aBazaCASS),0);
    aBNetCASS := Coalesce(Abs(aBNetCASS),0);
    aValCass  := Coalesce(Abs(aValCass) ,0);
    aBazaImp  := Coalesce(Abs(aBazaImp) ,0);
    aBNetImp  := Coalesce(Abs(aBNetImp) ,0);
    aValImp   := Coalesce(Abs(aValImp)  ,0);

    aBazaCASS := CASE WHEN aBazaCASS &gt; 0 AND aBazaCASS &lt; 1 THEN 1 ELSE Round(aBazaCASS,0) END;
    aBNetCASS := CASE WHEN aBNetCASS &gt; 0 AND aBNetCASS &lt; 1 THEN 1 ELSE Round(aBNetCASS,0) END;
    aValCass  := CASE WHEN aValCass  &gt; 0 AND aValCass  &lt; 1 THEN 1 ELSE Round(aValCass ,0) END;
    aBazaImp  := CASE WHEN aBazaImp  &gt; 0 AND aBazaImp  &lt; 1 THEN 1 ELSE Round(aBazaImp ,0) END;
    aBNetImp  := CASE WHEN aBNetImp  &gt; 0 AND aBNetImp  &lt; 1 THEN 1 ELSE Round(aBNetImp ,0) END;
    aValImp   := CASE WHEN aValImp   &gt; 0 AND aValImp   &lt; 1 THEN 1 ELSE Round(aValImp  ,0) END;

    aPos      := InStr(v_rec.Den_Part, ' ');
    IF aPos = 0 OR aPos &gt; 51 THEN
      aNume    := SubStr(v_rec.Den_Part,  1, 50);
      aPrenume := SubStr(v_rec.Den_Part, 51, 50);
    ELSE
      aNume    := SubStr(v_rec.Den_Part, 1, (aPos - 1)::integer);
      aPrenume := SubStr(v_rec.Den_Part, (aPos + 1)::integer, 50);
    END IF;

    IF getanlucru() = Coalesce(Extract(YEAR FROM v_rec.DataSf),0) AND getlunalucru() = Coalesce(Extract(MONTH FROM v_rec.DataSf),0)
    THEN vDataSf := v_rec.DataSf;
    ELSE vDataSf := NULL;
    END IF;

    IF Coalesce(aValImp,0) &lt;&gt; 0 OR Coalesce(aValCass,0) &lt;&gt; 0 THEN
      SELECT Count(*) INTO Nr FROM Tmp_stopaj
      WHERE CNP = v_rec.CNP
        AND Coalesce(Nume, '?') = Coalesce(aNume, '?') AND Coalesce(Prenume, '?') = Coalesce(aPrenume, '?')
        AND Coalesce(DataAng, vNullDate) = Coalesce(v_rec.DataAng, vNullDate) AND Coalesce(DataSf, vNullDate) = Coalesce(vDataSf, vNullDate);
      IF Nr = 0 THEN
        INSERT INTO Tmp_stopaj (
          Nume, Prenume, CNP,
          DataAng, DataSf,
          casaSN, TipAsig,
          BazaCass,    BNetCass,    ContrCass,
          BazaImpozit, BNetImpozit, Impozit)
        VALUES (
          aNume, aPrenume, v_rec.CNP,
          v_rec.DataAng, vDataSf,
          v_rec.SimbolCaSS, v_rec.TipAsig,
          aBazaCass, aBNetCass, aValCass,
          aBazaImp,  aBNetImp,  aValImp);
      ELSE
        UPDATE Tmp_stopaj
        SET BazaCass    = BazaCass    + aBazaCass,
            BNetCass    = BNetCass    + aBNetCass,
            ContrCass   = ContrCass   + aValCass,
            BazaImpozit = BazaImpozit + aBazaImp,
            BNetImpozit = BNetImpozit + aBNetImp,
            Impozit     = Impozit     + aValImp
        WHERE CNP = v_rec.CNP
          AND Coalesce(Nume, '?') = Coalesce(aNume, '?') AND Coalesce(Prenume, '?') = Coalesce(aPrenume, '?')
          AND Coalesce(DataAng, vNullDate) = Coalesce(v_rec.DataAng, vNullDate) AND Coalesce(DataSf, vNullDate) = Coalesce(vDataSf, vNullDate);
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getdiscvolumtrim</obj_name>
  <obj_hashval>30074035f9c9f71ab142901204abd53b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getdiscvolumtrim(INOUT wme_result numeric, INOUT acoddoc numeric, INOUT acodcontract numeric, INOUT atip numeric, INOUT acodncredit numeric, INOUT trimestru numeric, INOUT pretbrut numeric, INOUT acurs numeric DEFAULT 1)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  vDisc     double precision;
  vProcDisc double precision;
  vValDisc  double precision;
  vTipDisc  numeric;
  vValDoc   double precision;
  vTotal    double precision;
  vCurs     NUMERIC(10,7);
BEGIN
  --Florin 05.01.2023 - sinc. Oracle (03.01.2023)
  --Florin 20.04.2023 - sinc. Oracle (12.04.2023)
  if aCurs = 0 then vCurs := 1; else vCurs := aCurs; end if;
  IF  aCodContract = 0 THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  vDisc := 0;
  BEGIN
    SELECT COALESCE( TipTargetV, 0) INTO vTipDisc FROM contract WHERE codcontract = aCodContract;
  EXCEPTION WHEN others THEN
    vTipDisc := 0;
  END;

  IF  aTip = 1 THEN
    IF  vTipDisc = 0 THEN
      BEGIN
        SELECT valoare
        INTO vTotal
        FROM manevra_notecredit
        WHERE codobiect = 0 and  rownum = 1 and  UserID = (SELECT pkg_globals_GETUSERID.WME_RESULT FROM pkg_globals_GETUSERID(NULL,NULL)) and  CodNCredit = aCodNCredit;
      EXCEPTION WHEN others THEN
        vTotal := 0;
      END;

      IF  vTotal = 0 THEN
        WME_Result :=  0;
        RETURN;
      END IF;

      SELECT sum( COALESCE( a.valm, 0))
      INTO vValDoc
      FROM (SELECT SUM( CASE WHEN  COALESCE( PretBrut, 0) &lt;&gt; 1 THEN CASE WHEN  i.tipdoc = 21 THEN (  I1.Cant * i1.pretorig - I1.TVA)  * COALESCE( I1.CoefDiscMaj, 1)
                                                                         ELSE i1.cant * i1.pretorig * COALESCE( I1.CoefDiscMaj, 1)
                                                                    END
                             ELSE CASE WHEN  i.tipdoc = 21 THEN I1.Cant * i1.pretorig - I1.TVA ELSE i1.cant * i1.pretorig END
                        END ) VALM
            FROM IESIRI I INNER JOIN iesiri1 I1 ON  i.codies = i1.codies
            WHERE i1.codobiect &gt; 0
              AND I1.CodObiect IN (COALESCE( (fnc_GetValConstantalucru('ArtDiscAcVol' )::NUMERIC), 0),
                                   COALESCE( (fnc_GetValConstantalucru('ArtDiscAcCant' )::NUMERIC), 0),
                                   COALESCE( (fnc_GetValConstantalucru('ArtPenAcTer')::NUMERIC), 0),
                                   COALESCE( (fnc_GetValConstantalucru('ArtDiscOffInvoiceC'  )::NUMERIC), 0))
              AND INSTR(COALESCE((fnc_GetValConstantalucru('ArtPenAcTer'), '0'), (I1.CODOBIECT)::varchar) = 0)
              AND i.codies = aCodDoc
           ) a;

      IF  Trimestru = 1 THEN
        BEGIN
          SELECT COALESCE( c.discount1, 0) INTO vProcDisc FROM contract c WHERE c.codcontract = aCodContract and  c.suma1 &lt;= vTotal;
        EXCEPTION WHEN others THEN
          vProcDisc := 0;
        END;
      ELSE
        IF  Trimestru = 2 THEN
          BEGIN
            SELECT COALESCE( c.discount2, 0) INTO vProcDisc FROM contract c WHERE c.codcontract = aCodContract and  c.suma2 &lt;= vTotal;
          EXCEPTION WHEN others THEN
            vProcDisc := 0;
          END;
        ELSE
          IF  Trimestru = 3 THEN
            BEGIN
              SELECT COALESCE( c.discount3, 0) INTO vProcDisc FROM contract c WHERE  c.codcontract = aCodContract and  c.suma3 &lt;= vTotal;
            EXCEPTION WHEN others THEN
              vProcDisc := 0;
            END;
          ELSE
            IF  Trimestru = 4 THEN
              BEGIN
                SELECT COALESCE( c.discount4, 0) INTO vProcDisc FROM contract c WHERE c.codcontract = aCodContract and  c.suma4 &lt;= vTotal;
              EXCEPTION WHEN others THEN
                vProcDisc := 0;
              END;
            END IF;
          END IF;
        END IF;
      END IF;

      IF  vProcDisc &lt;&gt; 0 THEN
        vDisc := vValDoc * vProcDisc / 100;
      END IF;
    ELSE
      IF  vTipDisc = 1 THEN
        BEGIN
          SELECT valoare
          INTO vTotal
          FROM manevra_notecredit
          WHERE codobiect = 0 and  rownum = 1 and  UserID = (SELECT pkg_globals_GETUSERID.WME_RESULT FROM pkg_globals_GETUSERID(NULL,NULL)) and  CodNCredit = aCodNcredit;
        EXCEPTION WHEN others THEN
          vTotal := 0;
        END;

        IF  vTotal = 0 THEN
          WME_Result :=  0;
          RETURN;
        END IF;

        SELECT sum( COALESCE( a.valm, 0))
        INTO vValDoc
        FROM (SELECT SUM( CASE WHEN  COALESCE( PretBrut, 0) &lt;&gt; 1 THEN CASE WHEN  i.tipdoc = 21 THEN (  I1.Cant * i1.pretorig - I1.TVA)  * COALESCE( I1.CoefDiscMaj, 1)
                                                                           ELSE i1.cant * i1.pretorig * COALESCE( I1.CoefDiscMaj, 1)
                                                                      END
                               ELSE CASE WHEN  i.tipdoc = 21 THEN I1.Cant * i1.pretorig - I1.TVA ELSE i1.cant * i1.pretorig END
                          END ) VALM
              FROM IESIRI I
                  INNER JOIN iesiri1   I1 ON  i.codies = i1.codies
                  INNER JOIN contract1 c1 ON  c1.codcontract1 = (SELECT pkg_notecredit_GetCodContract1.WME_RESULT FROM pkg_notecredit_GetCodContract1(NULL, i1.codobiect, i.datadoc, aCodContract))
              WHERE i1.codobiect &gt; 0
                AND (I1.CodObiect NOT IN (COALESCE( (fnc_GetValConstantalucru('ArtDiscAcVol')::numeric), 0),
                                     COALESCE( (fnc_GetValConstantalucru('ArtDiscAcCant')::numeric), 0),
                                     COALESCE( (fnc_GetValConstantalucru('ArtPenAcTer')::numeric), 0),
                                     COALESCE( (fnc_GetValConstantalucru('ArtDiscOffInvoiceC')::numeric), 0))
                AND INSTR(COALESCE(fnc_GetValConstantalucru('ArtPenAcTer'), '0'), (I1.CODOBIECT)::varchar) = 0)
                and  i.codies = aCodDoc and  c1.codcontract = aCodContract
              ) a;

        IF  Trimestru = 1 THEN
          BEGIN
            SELECT COALESCE( c.discount1, 0) INTO vProcDisc FROM contract c WHERE c.codcontract = aCodContract and  c.suma1 &lt;= vTotal;
          EXCEPTION WHEN others THEN
            vProcDisc := 0;
          END;
        ELSE
          IF  Trimestru = 2 THEN
            BEGIN
              SELECT COALESCE( c.discount2, 0) INTO vProcDisc FROM contract c WHERE c.codcontract = aCodContract and  c.suma2 &lt;= vTotal;
            EXCEPTION WHEN others THEN
              vProcDisc := 0;
            END;
          ELSE
            IF  Trimestru = 3 THEN
              BEGIN
                SELECT COALESCE( c.discount3, 0) INTO vProcDisc FROM contract c WHERE c.codcontract = aCodContract and  c.suma3 &lt;= vTotal;
              EXCEPTION WHEN others THEN
                vProcDisc := 0;
              END;
            ELSE
              IF  Trimestru = 4 THEN
                BEGIN
                  SELECT COALESCE( c.discount4, 0) INTO vProcDisc FROM contract c WHERE c.codcontract = aCodContract and  c.suma4 &lt;= vTotal;
                EXCEPTION WHEN others THEN
                  vProcDisc := 0;
                END;
              END IF;
            END IF;
          END IF;
        END IF;

        IF  vProcDisc &lt;&gt; 0 THEN
          vDisc := vValDoc * vProcDisc / 100;
        END IF;
      END IF;
    END IF;
  ELSE
    IF  vTipDisc = 0 THEN
      BEGIN
        SELECT valoare INTO vTotal FROM manevra_notecredit
        WHERE codobiect = 0 and  UserID = (SELECT pkg_globals_GETUSERID.WME_RESULT FROM pkg_globals_GETUSERID(NULL,NULL)) and  codncredit = aCodNCredit LIMIT 1;
      EXCEPTION WHEN others THEN
        vTotal := 0;
      END;

      IF  vTotal = 0 THEN
        WME_Result :=  0;
        RETURN;
      END IF;

      SELECT sum( COALESCE( a.valm, 0))
      INTO vValDoc
      FROM (SELECT SUM( CASE WHEN  COALESCE( PretBrut, 0) &lt;&gt; 1 THEN I1.Cant * I1.PretOrig * COALESCE( I1.CoefDiscMaj, 1)
                             ELSE I1.Cant * I1.PretOrig
                        END ) VALM
            FROM Intrari I INNER JOIN intrari1 I1 ON  i.codintr = i1.codintr
            WHERE i1.codobiect &gt; 0
              AND I1.CodObiect NOT IN (COALESCE( (fnc_GetValConstantalucru('ArtDiscPrimVol' )::numeric), 0),
                                   COALESCE( (fnc_GetValConstantalucru('ArtDiscPrimCant')::numeric), 0),
                                   fnc_GetValConstantalucru('ArtPenPrimTer'  ))
              AND INSTR(fnc_GetValConstantalucru('ArtDiscPrimTer' ), (I1.CODOBIECT)::varchar) = 0
              and  i.codintr = aCodDoc
           ) a;

      BEGIN
        SELECT COALESCE( cv.Discount, 0)
        INTO vProcDisc
        FROM contractv cv
        WHERE cv.codcontract = aCodContract and  COALESCE( cv.codcontract1, 0) = 0
          and  cv.suma = (SELECT max( suma) FROM contractv CCv WHERE CCv.Codcontract = aCodContract and  suma &lt;= vTotal and  COALESCE( ccv.codcontract1, 0) = 0);
      EXCEPTION WHEN others THEN
        vProcDisc := 0;
      END;

      IF  vProcDisc = 0 THEN
        BEGIN
          SELECT COALESCE( cv.ValDiscount, 0)
          INTO vValDisc
          FROM contractv cv
          WHERE cv.codcontract = aCodContract and  COALESCE( cv.codcontract1, 0) = 0
            and  cv.suma = (SELECT max( suma) FROM contractv CCv WHERE CCv.Codcontract = aCodContract and  suma &lt;= vTotal and  COALESCE( ccv.codcontract1, 0) = 0);
        EXCEPTION WHEN others THEN
          vValDisc := 0;
        END;
      END IF;

      IF  vProcDisc &lt;&gt; 0 THEN
        vDisc := vValDoc * vProcDisc / 100;
      ELSE
        vDisc := vValDoc / vTotal * vValDisc * vCurs;
      END IF;
    ELSE
      IF  vTipDisc = 1 THEN
        BEGIN
          SELECT valoare INTO vTotal FROM manevra_notecredit
          WHERE codobiect = 0 and  UserID = (SELECT pkg_globals_GETUSERID.WME_RESULT FROM pkg_globals_GETUSERID(NULL,NULL)) and  CodNCredit = aCodNCredit LIMIT 1;
        EXCEPTION WHEN others THEN
          vTotal := 0;
        END;

        IF  vTotal = 0 THEN
          WME_Result :=  0;
          RETURN;
        END IF;

        SELECT sum( COALESCE( a.valm, 0))
        INTO vValDoc
        FROM (SELECT SUM( CASE  WHEN  COALESCE( PretBrut, 0) &lt;&gt; 1 THEN I1.Cant * I1.PretOrig * COALESCE( I1.CoefDiscMaj, 1)
                                ELSE I1.Cant * I1.PretOrig
                          END ) VALM
              FROM Intrari I
                  INNER JOIN intrari1  I1 ON  i.codintr = i1.codintr
                  INNER JOIN contract1 c1 ON  c1.codcontract1 = (SELECT pkg_notecredit_GetCodContract1.WME_RESULT FROM pkg_notecredit_GetCodContract1(NULL, i1.codobiect, i.datadoc, aCodContract))
              WHERE i1.codobiect &gt; 0
                AND I1.CodObiect NOT IN (COALESCE( (fnc_GetValConstantalucru('ArtDiscPrimVol' )::numeric), 0),
                                     COALESCE( (fnc_GetValConstantalucru('ArtDiscPrimCant')::numeric), 0),
                                     fnc_GetValConstantalucru('ArtPenPrimTer'  )::numeric)
                AND INSTR(fnc_GetValConstantalucru('ArtDiscPrimTer' ), (I1.CODOBIECT)::varchar) = 0
                and  i.codintr = aCodDoc and  c1.codcontract = aCodContract
              ) a;

        BEGIN
          SELECT COALESCE( cv.Discount, 0)
          INTO vProcDisc
          FROM contractv cv
          WHERE  cv.codcontract = aCodContract and  COALESCE( cv.codcontract1, 0) = 0
            and  cv.suma = (SELECT max( suma) FROM contractv CCv WHERE CCv.Codcontract = aCodContract and  suma &lt;= vTotal and  COALESCE( ccv.codcontract1, 0) = 0);
        EXCEPTION WHEN others THEN
          vProcDisc := 0;
        END;

        IF  vProcDisc = 0 THEN
          BEGIN
            SELECT COALESCE( cv.ValDiscount, 0)
            INTO vValDisc
            FROM contractv cv
            WHERE  cv.codcontract = aCodContract and  COALESCE( cv.codcontract1, 0) = 0
              and  cv.suma = (SELECT max( suma) FROM contractv CCv WHERE CCv.Codcontract = aCodContract and  suma &lt;= vTotal and  COALESCE( ccv.codcontract1, 0) = 0);
          EXCEPTION WHEN others THEN
            vValDisc := 0;
          END;
        END IF;

        IF  vProcDisc &lt;&gt; 0 THEN
          vDisc := vValDoc * vProcDisc / 100;
        ELSE
          vDisc := vValDoc / vTotal * vValDisc * vCurs;
        END IF;
      ELSE
        FOR v_rec IN
        (
        SELECT a.codobiect, a.codcontract1, sum( a.valm) VALM, tmp.valoare VALTOT
        FROM (SELECT I1.CodObiect, c1.codcontract1, SUM( CASE WHEN  COALESCE( PretBrut, 0) &lt;&gt; 1 THEN I1.Cant * I1.PretOrig * COALESCE( I1.CoefDiscMaj, 1)
                                                              ELSE I1.Cant * I1.PretOrig
                                                         END ) VALM
              FROM Intrari I
                  INNER JOIN intrari1  I1 ON  i.codintr = i1.codintr
                  INNER JOIN contract1 c1 ON  c1.codcontract1 = (SELECT pkg_notecredit_GetCodContract1.WME_RESULT FROM pkg_notecredit_GetCodContract1(NULL, i1.codobiect, i.datadoc, aCodContract))
              WHERE i1.codobiect &gt; 0
                AND I1.CodObiect NOT IN (COALESCE( (fnc_GetValConstantalucru('ArtDiscPrimVol' )::numeric), 0),
                                     COALESCE( (fnc_GetValConstantalucru('ArtDiscPrimCant')::numeric), 0),
                                     fnc_GetValConstantalucru('ArtPenPrimTer'  ))
                AND INSTR(fnc_GetValConstantalucru('ArtDiscPrimTer' ), (I1.CODOBIECT)::varchar) = 0
                and  i1.codintr1 = aCodDoc and  c1.codcontract = aCodContract
              GROUP BY I1.CodObiect, c1.codcontract1
              ) a
              LEFT JOIN manevra_notecredit tmp ON  a.codobiect = tmp.codobiect and  a.codcontract1 = tmp.codcontract1 and  UserID = (SELECT pkg_globals_GETUSERID.WME_RESULT FROM pkg_globals_GETUSERID(NULL,NULL)) and  tmp.codncredit = aCodNCredit
        GROUP BY a.codobiect, a.codcontract1, tmp.valoare
        )
        LOOP
          BEGIN
            SELECT COALESCE( cv.Discount, 0)
            INTO vProcDisc
            FROM contractv cv INNER JOIN contract1 c1 ON  cv.codcontract1 = c1.codcontract1
            WHERE  cv.codcontract = aCodContract and  c1.codcontract1 = v_rec.codcontract1
              and  cv.suma = (SELECT max( suma) FROM contractv CCv WHERE CCv.Codcontract = aCodContract and  suma &lt;= v_rec.valtot and  ccv.codcontract1 = c1.codcontract1);
          EXCEPTION WHEN others THEN
            vProcDisc := 0;
          END;

          IF  vProcDisc = 0 THEN
            BEGIN
              SELECT COALESCE( cv.ValDiscount, 0)
              INTO vValDisc
              FROM contractv cv INNER JOIN contract1 c1 ON  cv.codcontract1 = c1.codcontract1
              WHERE  cv.codcontract = aCodContract and  c1.codcontract1 = v_rec.codcontract1
                and  cv.suma = (SELECT max( suma) FROM contractv CCv WHERE CCv.Codcontract = aCodContract and  suma &lt;= v_rec.valtot and  ccv.codcontract1 = c1.codcontract1);
            EXCEPTION WHEN others THEN
              vValDisc := 0;
            END;
          END IF;

          IF  vProcDisc &lt;&gt; 0 THEN
            vDisc := vDisc + v_Rec.ValM * vProcDisc / 100;
          ELSE
            vDisc := vDisc + v_Rec.ValM / v_Rec.valtot * vValDisc * vCurs;
          END IF;
        END LOOP;
      END IF;
    END IF;
  END IF;

  WME_Result :=  vDisc;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_npartretail_do_post_modifpart_onbaza</obj_name>
  <obj_hashval>1d8e12c6a09b1ff7236fc0927446f517</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_npartretail_do_post_modifpart_onbaza()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  V_REC_D RECORD;
  CODNOUAGENDA     numeric;
  COD_CODFISCALNOU numeric;
  CODPARTDISCNOU   numeric;
  CODPARTTRNOU     numeric;
  CODPARTBNOU      numeric;
  aCODLOCALIT      numeric;
  aCODBANCA        numeric;
begin
  --Florin 02.10.2025 - sinc. oracle
  --Bogdan 23.02.2021
  FOR V_REC IN (SELECT * FROM TMP_NPARTRETAIL) LOOP
    UPDATE NPART
    SET
      (
        DEN_PART, REGCOM, CODEXTERN, CODINTERN,
        COLDISCOUNT, CODCLASA, FIDELIZARE, DATANASTERE,
        BLOCAT, INFOBLOCAT, PERSOANAFIZICA, OBS
      )
      = (SELECT V_REC.DENUMIRE, V_REC.REGCOM, V_REC.CODEXTERN, V_REC.CODINTERN,
          V_REC.COLDISCOUNT, V_REC.CODCLASA, V_REC.FIDELIZARE, V_REC.DATANASTERE,
          V_REC.BLOCAT, V_REC.INFOBLOCAT, V_REC.TIPPART, V_REC.OBS)
    WHERE
      CODPART = V_REC.CODPART;

    perform NotifyModif(-12,  V_REC.CODPART, 'NPART');

    FOR V_REC_D IN (SELECT * FROM TMP_NSEDIIPARTRETAIL D WHERE D.CODPARTRETAIL = V_REC.CODPARTRETAIL) LOOP
      aCODLOCALIT := (SELECT PKG_NPARTRETAIL_GET_COD_LOCALIT.WME_RESULT
                      FROM PKG_NPARTRETAIL_GET_COD_LOCALIT (NULL, V_REC_D.CODLOCALIT, V_REC_D.DENLOCALIT, V_REC_D.CODJUDET::varchar, V_REC_D.CODTARA::varchar));
      IF V_REC_D.CODAGENDA IS NULL THEN
        CODNOUAGENDA := NEXTVAL ('SEQ_NAGENDA_CODAGENDA');
        INSERT INTO NAGENDA (CODAGENDA, TIP, CODLOCALIT, SEDIUSOCIAL,
            TELEFON, FAX, EMAIL, SECTOR,
            STRADA, NR1, NR2, BLOC,
            SCARA, ETAJ, APART, CODPOSTAL,
            OBS, CODPART)
        VALUES (CODNOUAGENDA, 0, aCODLOCALIT, V_REC_D.SEDIUSOCIAL,
            V_REC_D.TELEFON, V_REC_D.FAX, V_REC_D.EMAIL, V_REC_D.SECTOR,
            V_REC_D.STRADA, V_REC_D.NR1, V_REC_D.NR2, V_REC_D.BLOC,
            V_REC_D.SCARA, V_REC_D.ETAJ, V_REC_D.APART, V_REC_D.CODPOSTAL,
            V_REC_D.DENUMIRE, V_REC.CODPART);

        UPDATE TMP_NSEDIIPARTRETAIL
        SET CODAGENDA = CODNOUAGENDA, CODLOCALIT = aCODLOCALIT
        WHERE
          CODSEDIU = V_REC_D.CODSEDIU;
      ELSE
        UPDATE NAGENDA
        SET
          (
            CODLOCALIT, SEDIUSOCIAL, TELEFON, FAX,
            EMAIL, SECTOR, STRADA, NR1,
            NR2, BLOC, SCARA, ETAJ,
            APART, CODPOSTAL, OBS
          )
          = (SELECT aCODLOCALIT, V_REC_D.SEDIUSOCIAL, V_REC_D.TELEFON, V_REC_D.FAX,
              V_REC_D.EMAIL, V_REC_D.SECTOR, V_REC_D.STRADA, V_REC_D.NR1,
              V_REC_D.NR2, V_REC_D.BLOC, V_REC_D.SCARA, V_REC_D.ETAJ,
              V_REC_D.APART, V_REC_D.CODPOSTAL, V_REC_D.DENUMIRE)
        WHERE
          CODAGENDA = V_REC_D.CODAGENDA;

        UPDATE TMP_NSEDIIPARTRETAIL SET CODLOCALIT = aCODLOCALIT WHERE CODSEDIU = V_REC_D.CODSEDIU;
      END IF;
    END LOOP;

    FOR V_REC_D IN (SELECT * FROM TMP_NCODFISCRETAIL D WHERE D.CODPARTRETAIL = V_REC.CODPARTRETAIL) LOOP
      IF V_REC_D.COD_CODFISCAL IS NULL THEN
        COD_CODFISCALNOU := NEXTVAL ('SEQ_NPARTCODFISC_COD_CODFISCAL');
        INSERT INTO NPARTCODFISC (COD_CODFISCAL, CODPART, CODFISCAL, PRINCIPAL)
        VALUES (COD_CODFISCALNOU, V_REC.CODPART, V_REC_D.CODFISCAL, V_REC_D.PRINCIPAL);

        UPDATE TMP_NCODFISCRETAIL SET COD_CODFISCAL = COD_CODFISCALNOU WHERE COD = V_REC_D.COD;
      ELSE
        UPDATE NPARTCODFISC
        SET
          (CODFISCAL, PRINCIPAL) = (SELECT V_REC_D.CODFISCAL, V_REC_D.PRINCIPAL)
        WHERE
          COD_CODFISCAL = V_REC_D.COD_CODFISCAL;
      END IF;
    END LOOP;

    FOR V_REC_D IN (SELECT * FROM TMP_NPARTDISCRETAIL D WHERE D.CODPARTRETAIL = V_REC.CODPARTRETAIL) LOOP
      IF V_REC_D.CODPARTDISC IS NULL THEN
        CODPARTDISCNOU := NEXTVAL ('SEQ_NPARTDISC_CODPARTDISC');
        INSERT INTO NPARTDISC (CODPARTDISC, CODPART, CODCATEGDISC, INDEXLOCAL)
        VALUES (CODPARTDISCNOU, V_REC.CODPART, V_REC_D.CODCATEGDISC, V_REC_D.INDEXLOCAL);

        UPDATE TMP_NPARTDISCRETAIL SET CODPARTDISC = CODPARTDISCNOU WHERE COD = V_REC_D.COD;
      ELSE
        UPDATE NPARTDISC
        SET CODCATEGDISC = V_REC_D.CODCATEGDISC, INDEXLOCAL = V_REC_D.INDEXLOCAL
        WHERE
          CODPARTDISC = V_REC_D.CODPARTDISC;
      END IF;
    END LOOP;

    FOR V_REC_D IN (SELECT * FROM TMP_NDELEGATRETAIL D WHERE D.CODPARTRETAIL = V_REC.CODPARTRETAIL) LOOP
      IF V_REC_D.CODPARTTR IS NULL THEN
        CODPARTTRNOU := NEXTVAL ('SEQ_NPARTTR_CODPARTTR');
        INSERT INTO NPARTTR (CODPARTTR, CODPART, DELEGAT, CNP,
            DOC, SERIEDOC, NRDOC, ELIBERAT,
            MIJLTRANSP, NRTRANSP, ACTIV, DATADOC,
            IMPLICIT, OBS)
        VALUES (CODPARTTRNOU, V_REC.CODPART, V_REC_D.DELEGAT, V_REC_D.CNP,
            V_REC_D.DOC, V_REC_D.SERIEDOC, V_REC_D.NRDOC, V_REC_D.ELIBERAT,
            V_REC_D.MIJLTRANSP, V_REC_D.NRTRANSP, V_REC_D.ACTIV, V_REC_D.DATADOC,
            V_REC_D.IMPLICIT, V_REC_D.OBS);

        UPDATE TMP_NDELEGATRETAIL SET CODPARTTR = CODPARTTRNOU WHERE COD = V_REC_D.COD;
      ELSE
        UPDATE NPARTTR
        SET
          (
            DELEGAT, CNP, DOC, SERIEDOC,
            NRDOC, ELIBERAT, MIJLTRANSP, NRTRANSP,
            ACTIV, DATADOC, IMPLICIT, OBS
          )
          = (SELECT V_REC_D.DELEGAT, V_REC_D.CNP, V_REC_D.DOC, V_REC_D.SERIEDOC,
              V_REC_D.NRDOC, V_REC_D.ELIBERAT, V_REC_D.MIJLTRANSP, V_REC_D.NRTRANSP,
              V_REC_D.ACTIV, V_REC_D.DATADOC, V_REC_D.IMPLICIT, V_REC_D.OBS)
        WHERE
          CODPARTTR = V_REC_D.CODPARTTR;
      END IF;
    END LOOP;

    FOR V_REC_D IN (SELECT * FROM TMP_NBANCIRETAIL D WHERE D.CODPARTRETAIL = V_REC.CODPARTRETAIL) LOOP
      aCODLOCALIT := (SELECT PKG_NPARTRETAIL_GET_COD_LOCALIT.WME_RESULT
                      FROM PKG_NPARTRETAIL_GET_COD_LOCALIT (NULL, V_REC_D.CODLOCALIT, V_REC_D.DENLOCALIT, V_REC_D.CODJUDET::varchar, V_REC_D.CODTARA::varchar));
      aCODBANCA := (select WME_RESULT from PKG_NPARTRETAIL_GET_COD_BANCA (null, V_REC_D.CODBANK, V_REC_D.DENBANCA));
      IF V_REC_D.CODPARTB IS NULL THEN
        CODPARTBNOU := NEXTVAL ('SEQ_NPARTB_CODPARTB');
        INSERT INTO NPARTB (CODPARTB, CODPART, CODBANK, IMPLICIT,
            CODLOCALIT, CONTBANCA, SUCURSALA, CODMONEDA)
        VALUES (CODPARTBNOU, V_REC.CODPART, aCODBANCA, V_REC_D.IMPLICIT,
            aCODLOCALIT, V_REC_D.CONTBANCA, V_REC_D.SUCURSALA, V_REC_D.CODMONEDA);

        UPDATE TMP_NBANCIRETAIL
        SET CODPARTB = CODPARTBNOU, CODLOCALIT = aCODLOCALIT, CODBANK = aCODBANCA
        WHERE
          COD = V_REC_D.COD;
      ELSE
        UPDATE NPARTB
        SET
          (CODBANK, IMPLICIT, CODLOCALIT, CONTBANCA, SUCURSALA, CODMONEDA)
          = (SELECT V_REC_D.CODBANK, V_REC_D.IMPLICIT, V_REC_D.CODLOCALIT, V_REC_D.CONTBANCA, V_REC_D.SUCURSALA, V_REC_D.CODMONEDA)
        WHERE
          CODPARTB = V_REC_D.CODPARTB;

        UPDATE TMP_NBANCIRETAIL
        SET CODLOCALIT = aCODLOCALIT, CODBANK = aCODBANCA
        WHERE
          COD = V_REC_D.COD;
      END IF;
    END LOOP;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_onorarecomenzi_get_tmp_operlivr_comenzi</obj_name>
  <obj_hashval>e1c41e96f76da55eb45fa5659381f565</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_onorarecomenzi_get_tmp_operlivr_comenzi()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 03.09.2024 - sinc. Oracle
  --Florin 26.04.2023 - sinc. Oracle (25.04.2023)
  --Florin 25.04.2023 - fixat 58047
  --Florin 17.03.2023 - sinc. Oracle (16.03.2023)
  --Florin 17.08.2021 - sinc. Oracle (38743)
  DELETE FROM TMP_OnorCom_Comenzi;
  INSERT INTO TMP_OnorCom_Comenzi(Poz, CodClient, DenClient, CodSediu, DenSediu, SediuSocial, CodFiscal,
                                  TipComanda, NrComanda, DataComanda, Obs, CodAgent, DenAgent, CodDelegat, CodPers, FaraTransport,
                                  CodMijlTransp, CodTraseuLivr, CodComanda, CodMoneda, Subunitatea, ScadentaV, Rest, Curs,
                                  GDI, GAA, A1, A2, A3, A4, A5, A6, KGA1, KGA2, KGA3, KGA4, KGA5, KGA6, MASAU, VOLUMU, MASA, VOLUM,
                                  ModDoc, TipDoc, TipDocAmb, FlagLucru, FlagInchidere, DenTraseu, DenDelegat, DenMijlTransp,
                                  Valoare, Discount, ExclPromoAut, CountNeinchise, Custodie,
    MijlTransp, NrTransp,
    Tipcmd, ValRest, SeriaDoc)
  SELECT  C.ORDINELIVRARE,
          CASE
            WHEN  C.TipDoc = 18 THEN C.Partener     -- comanda client
            WHEN  C.TipDoc = 43 THEN C.Codgest      -- comanda de la gestiuni
            WHEN  C.TipDoc = 44 THEN C.Subunitatea  -- comanda de la subunitati
          END ,
           CASE
            WHEN  C.TipDoc = 18 THEN P.Den_Part      -- comanda client
            WHEN  C.TipDoc = 43 THEN NGE.Den_Gest    -- comanda de la gestiuni
            WHEN  C.TipDoc = 44 THEN NS.Den_Subunit  -- comanda de la subunitati
          END ,
          C.CodLocatie, S.Obs, S.SediuSocial, C.CodFiscal, C.TipDoc, C.NrDoc, C.DataDoc, C.Obs,
          C.Agent, AG.Nume || ' ' || AG.Prenume, C.Delegat, PT.CodPers, C.FaraTransport, C.MijlTransp, C.CodTraseuLivr, C.CodComanda, C.Moneda,
          CASE WHEN  C.TipDoc=44 THEN C.SubunitSursa ELSE  C.Subunitatea END ,
          C.ScadentaV, a1.Rest, 1 CURS, 0 GDI, 0 GAA, 0 A1, 0 A2, 0 A3, 0 A4, 0 A5, 0 A6, 0 KGA1, 0 KGA2, 0 KGA3, 0 KGA4, 0 KGA5, 0 KGA6,
          0 MASAU, 0 VOLUMU, 0 MASA, 0 VOLUM, 0 MODDOC,
          CASE
            WHEN  C.TipDoc = 43                     THEN 12  -- Nota de transfer
            WHEN  C.TipDoc = 44                     THEN 23  -- Iesiri catre subunitati
            ELSE
             CASE
               WHEN C.DISPLIVRARE = 1 THEN
               CASE
                WHEN  COALESCE( P.DocDefOnorCom, 0) = 1 THEN 19
                WHEN  COALESCE( P.DocDefOnorCom, 0) = 2 THEN 20
                WHEN S.SediuSocial IN (2, 3, 6, 7)      THEN 19  -- Facturi care clienti -- orice sediu care include facturare
                ELSE 20  -- Avize de Expeditie catre clienti -- practic restul tipurilor de sedii S.SediuSocial IN (1,4,5)
             END
           ELSE
             CASE
               WHEN fnc_getvalconstantalucru('OnorComNoRez') = '1' THEN 18
               ELSE
               CASE
                 WHEN COALESCE(P.DocDefOnorCom,0) = 1 THEN 19
                 WHEN COALESCE(P.DocDefOnorCom,0) = 2 THEN 20
                 WHEN S.SediuSocial IN (2,3,6,7) THEN 19 -- Facturi care clienti -- orice sediu care include facturare
                 ELSE 20 -- Avize de Expeditie catre clienti -- practic restul tipurilor de sedii S.SediuSocial IN (1,4,5)
               END
             END
           END
          END  TIPDOC,
          CASE
            WHEN  C.TipDoc = 43                 THEN 57
            WHEN  COALESCE( PT.Codpers, 0) &lt;&gt; 0 THEN 57
            ELSE 20
          END  TIPDOCAMB,
          1 FLAGLUCRU, 0 FLAGINCHIDERE, TL.DenTraseu, PT.Delegat, PA.NrInreg, C.VALOARE, 0 DISCOUNT,
          CASE WHEN  C.TipDoc = 18 AND  COALESCE( ModPromoFactCom, 1) = 1 THEN 1 ELSE 0 END ,
          A2.CountNeinchise, 0 CUSTODIE, c.mijltransp, c.nrtransp,
          CASE WHEN COALESCE(C.DISPLIVRARE, 0) = 1 THEN 'DL' ELSE C.PREFIXDOC END,
          round(A1.restval,2), C.SeriaDoc
  FROM COMANDA C
  LEFT JOIN NPART      P   ON  P.CodPart        = C.PARTENER
  LEFT JOIN NPERS      AG  ON  AG.CodPers       = C.AGENT
  LEFT JOIN NAGENDA    S   ON  S.CodAgenda      = C.CodLocatie
  LEFT JOIN (SELECT CodComanda, Sum(RESTLIVR) Rest, Sum(RESTLIVR*pretorig*coefdiscmaj) RestVal, Count(1) CountNeinchise FROM TMP_Onorcom_Articole GROUP BY CodComanda) A1 ON A1.CodComanda = C.CodComanda
  LEFT JOIN (SELECT CodComanda, Sum( RESTLIVR) REST, Count( 1) COUNTNEINCHISE FROM TMP_Onorcom_Articole GROUP BY CodComanda) A2 ON  A2.CodComanda = C.CodComanda
  LEFT JOIN NSubunit NS ON  NS.CodSubunit       = C.Subunitatea
  LEFT JOIN NGest      NGE ON  NGE.CodGest      = C.CodGest
  LEFT JOIN TraseuLivr TL  ON  TL.CodTraseuLivr = C.CodTraseuLivr
  LEFT JOIN NPartTr    PT  ON  PT.CodPartTr     = C.Delegat
  LEFT JOIN NParcAut   PA  ON  PA.CodNParcAut   = C.MijlTransp
  WHERE  C.TipDoc IN (18, 43, 44)   -- doar comenzi clienti, comenzi de la gestiuni, comenzi de la subunitati
    AND  C.UserIDBlocaj = TO_NUMBER((current_setting('PKG_GLOBALS.UserID', true)),'999999999999999999')
    AND EXISTS (SELECT TMP.CODCOMANDA FROM TMP_Onorcom_Articole TMP WHERE C.CODCOMANDA = TMP.CODCOMANDA);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_packing_sp_gotorecord</obj_name>
  <obj_hashval>d91273247059bc9369a699e8542ee342</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_packing_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  nrRows NUMERIC;
  v_rec record;
  total_rows integer := 0;
BEGIN
  --Bogdan 16.09.2025 - 66650 - PG - Contracte - Packing
  --Fl0orin 02.08.2024 - fixat 62900
  --Florin 10.07.2024
  delete from TMP_PACKING;
  delete from TMP_PACKING1;
  delete from TMP_PACKING2;
  delete from TMP_PACKING3;

  INSERT INTO  TMP_PACKING (CODPACKING, CODDOC, TIPDOC, OBS, dirty)
      SELECT CODPACKING, CODDOC, TIPDOC, OBS, dirty from PACKING
      WHERE CODPACKING = RecId;

  INSERT INTO TMP_PACKING1
    (CODPACKING1,
     CODPACKING,
     CODDOC1,
     CODOBIECT,
     CODAMB_PRIMAR,
     CODAMB_SECUNDAR,
     CODAMB_TERTIAR,
     CANTAMB,
     CANTAMBXPRIMAR,
     CANTAMBXSECUNDAR,
     CANTAMBXTERTIAR,
     CANTOBJ,
     DENAMB_PRIMAR,
     DENAMB_SECUNDAR,
     DENAMB_TERTIAR,
     DENOBIECT,
     CANTXPRIMAR,
     NR_RANDXPRIMAR,
     CANTRANDXPRIMAR,
     CANTXSECUNDAR,
     NR_RANDXSECUNDAR,
     CANTRANDXSECUNDAR,
     CANTXTERTIAR,
     NR_RANDXTERTIAR,
     CANTRANDXTERTIAR)
    SELECT pk1.CODPACKING1,
           pk1.CODPACKING,
           pk1.CODDOC1,
           pk1.CODOBIECT,
           pk1.CODAMB_PRIMAR,
           pk1.CODAMB_SECUNDAR,
           pk1.CODAMB_TERTIAR,
           pk1.CANTAMB,
           pk1.CANTAMBXPRIMAR,
           pk1.CANTAMBXSECUNDAR,
           pk1.CANTAMBXTERTIAR,
           pk1.CANTOBJ,
           nobj_amb_primar.DENUMIRE,
           nobj_amb_secundar.DENUMIRE,
           nobj_amb_tertiar.DENUMIRE,
           nobj.DENUMIRE,
           namb_primar.CANT,
           namb_primar.NR_RANDURI ,
           case when coalesce(namb_primar.CANT,0) &lt;&gt; 0 then ceil(namb_primar.CANT/coalesce(namb_primar.NR_RANDURI,1)) else null end,
           namb_secundar.CANT,
           namb_secundar.NR_RANDURI,
           case when coalesce(namb_secundar.CANT,0) &lt;&gt; 0 then ceil(namb_secundar.CANT/coalesce(namb_secundar.NR_RANDURI,1)) else null end,
           namb_tertiar.CANT,
           namb_tertiar.NR_RANDURI,
           case when coalesce(namb_tertiar.CANT,0) &lt;&gt; 0 then ceil(namb_tertiar.CANT/coalesce(namb_tertiar.NR_RANDURI,1)) else null end
      from PACKING1 pk1
      join PACKING pk on pk.CODPACKING = pk1.CODPACKING
      left join NARTAMB namb_primar on namb_primar.CODAMB = pk1.CODAMB_PRIMAR
      left join NARTAMB namb_secundar on namb_secundar.CODAMB = pk1.CODAMB_SECUNDAR
      left join NARTAMB namb_tertiar on namb_tertiar.CODAMB = pk1.CODAMB_TERTIAR
      left join NARTOBJ  nobj on nobj.CODOBIECT = pk1.CODOBIECT
      left join NARTOBJ nobj_amb_primar on nobj_amb_primar.CODOBIECT = namb_primar.CODOBIECTRETURN
      left join NARTOBJ nobj_amb_secundar on nobj_amb_secundar.CODOBIECT = namb_secundar.CODOBIECTRETURN
      left join NARTOBJ nobj_amb_tertiar on nobj_amb_tertiar.CODOBIECT = namb_tertiar.CODOBIECTRETURN
      WHERE PK.CODPACKING = RecId;
      --din contracte
      IF current_setting('pkg_packing.gTipDoc', TRUE)::numeric IN (27,34) THEN
        UPDATE TMP_PACKING1
          set CANTCOMANDA = ( SELECT ctr1.CANT * coalesce(u1.paritate,1)
                                                        FROM CONTRACT1 ctr1
                                                            JOIN NUM1 u1 ON u1.CodUM1 = ctr1.UmSec
                                                        WHERE ctr1.CODCONTRACT1 = CODDOC1 and ctr1.codobiect = codobiect );
        -- adauga inregistrarile noi
         nrRows := -1;
        FOR v_rec IN (SELECT ctr1.CODCONTRACT1, ctr1.CODOBIECT, nobj.DENUMIRE ,ctr1.CANT * coalesce(u1.PARITATE,1) AS cantcmd
                             FROM CONTRACT ctr
                               JOIN CONTRACT1 ctr1 on ctr1.CODCONTRACT = ctr.CODCONTRACT
                               JOIN NUM1 u1 ON u1.CODUM1 = ctr1.UMSEC
                               JOIN NARTOBJ  nobj on nobj.CODOBIECT = ctr1.CODOBIECT
                             where ctr.CODCONTRACT = current_setting('pkg_packing.gCodDoc', TRUE)::numeric and ctr.tipdoc = current_setting('pkg_packing.gTipDoc', TRUE)::numeric) LOOP
        update tmp_packing1 tpk1 set deleted = 0 where tpk1.coddoc1 = v_rec.CODCONTRACT1 and codobiect = v_rec.codobiect ;
        IF NOT FOUND THEN
        RAISE NOTICE 'No rows found';
      ELSIF FOUND THEN
        GET DIAGNOSTICS total_rows := ROW_COUNT;
      END IF;
        IF total_rows = 0 THEN
           INSERT INTO tmp_packing1(CODPACKING1,
                                                     CODPACKING,
                                                     CODDOC1,
                                                     CODOBIECT,
                                                     CANTOBJ,
                                                     DENOBIECT,
                                                     CANTCOMANDA,
                                                     DELETED)
           VALUES(nrRows, RecId, v_rec.CODCONTRACT1, v_rec.CODOBIECT, v_rec.CANTCMD, v_rec.DENUMIRE, v_rec.CANTCMD, 0);
            nrRows := nrRows - 1;
         END IF;
        END LOOP;

        UPDATE TMP_PACKING1 SET DELETED = 1 WHERE DELETED IS NULL;
      END IF;

      -- daca sunt comenzi
      IF current_setting('pkg_packing.gTipDoc', TRUE)::numeric IN (18) THEN
        UPDATE TMP_PACKING1
          set CANTCOMANDA = ( SELECT c1.CANTACCEPTAT * coalesce(u1.paritate,1)
                                                        FROM COMANDA1 c1
                                                            JOIN NUM1 u1 ON u1.CodUM1 = c1.UmSec
                                                        WHERE c1.CODCOMANDA1 = CODDOC1 and c1.codobiect = codobiect );
        -- adauga inregistrarile noi
         nrRows := -1;
        FOR v_rec IN (SELECT cmd1.codcomanda1, cmd1.CODOBIECT, nobj.DENUMIRE ,cmd1.CANTACCEPTAT * coalesce(u1.PARITATE,1) AS cantcmd
                             FROM COMANDA cmd
                               JOIN COMANDA1 cmd1 on cmd1.CODCOMANDA = cmd.CODCOMANDA
                               JOIN NUM1 u1 ON u1.CODUM1 = cmd1.UMSEC
                               JOIN NARTOBJ  nobj on nobj.CODOBIECT = cmd1.CODOBIECT
                             where cmd.codcomanda = current_setting('pkg_packing.gCodDoc', TRUE)::numeric and cmd.tipdoc = current_setting('pkg_packing.gTipDoc', TRUE)::numeric) LOOP
        update tmp_packing1 set deleted = 0 where coddoc1 = v_rec.codcomanda1 and codobiect = v_rec.codobiect ;
      IF NOT FOUND THEN
        RAISE NOTICE 'No rows found';
      ELSIF FOUND THEN
        GET DIAGNOSTICS total_rows := ROW_COUNT;
      END IF;
        IF total_rows = 0 THEN
           INSERT INTO tmp_packing1(CODPACKING1,
                                                     CODPACKING,
                                                     CODDOC1,
                                                     CODOBIECT,
                                                     CANTOBJ,
                                                     DENOBIECT,
                                                     CANTCOMANDA,
                                                     DELETED)
           VALUES(nrRows, RecId, v_rec.CODCOMANDA1, v_rec.CODOBIECT, v_rec.CANTCMD, v_rec.DENUMIRE, v_rec.CANTCMD, 0);
            nrRows := nrRows - 1;
         END IF;
        END LOOP;

        UPDATE TMP_PACKING1 SET DELETED = 1 WHERE DELETED IS NULL;

        INSERT INTO TMP_REZERVATS
                                              (CODREZERVATS,
                                               CODCOMANDA1,
                                               CODNIRSTOC,
                                               CODNIRSER,
                                               REST,
                                               UMSEC,
                                               CODCMDPRODMAT,
                                               REZERVATINI,
                                               CODOBIECT)
          SELECT CODREZERVATS,
                 CODCOMANDA1,
                 CODNIRSTOC,
                 CODNIRSER,
                 REST,
                 UMSEC,
                 CODCMDPRODMAT,
                 REZERVATINI,
                 CODOBIECT
            FROM REZERVATS rz
           WHERE rz.CODCOMANDA1 IN
                 (SELECT tpk1.CODDOC1 FROM TMP_PACKING1 tpk1);

      END IF;
      INSERT INTO tmp_packing2 (
               CODPACKING2,
               CODPACKING1,
               SSCC,
               OBS,
               CODAMB_FINAL,
               DEN_AMB,
               CANTOBJ)
        SELECT pk2.codpacking2,
                    pk2.codpacking1,
                    pk2.sscc,
                    pk2.obs,
                    pk2.codamb_final,
                    nobj_amb_final.denumire,
                    pk2.CANTOBJ
        FROM PACKING2 pk2
        LEFT JOIN NARTAMB namb_final on namb_final.CODAMB = pk2.codamb_final
        LEFT JOIN NARTOBJ nobj_amb_final on nobj_amb_final.CODOBIECT = namb_final.CODOBIECTRETURN
        where pk2.codpacking1 in (select pk1.codpacking1 from tmp_packing1 pk1);

        INSERT INTO tmp_packing3 (
               CODPACKING3 ,
               CODPACKING2,
               CODREZERVATS,
               CANT,
               UMSEC,
               SERIE,
               CODSERIE)
        SELECT pk3.CODPACKING3,
                    pk3.CODPACKING2,
                    pk3.CODREZERVATS,
                    pk3.CANT,
                    pk3.UMSEC,
                    ns.SERIE,
                    ns.CODSERIE
        FROM PACKING3 pk3
        left join rezervats rez on rez.codrezervats = pk3.codrezervats
        left join nirser nrsr
               on nrsr.codnirser = rez.codnirser
        left join nserii ns
               on ns.codserie = nrsr.codserie
        where pk3.codpacking2 in (select pk2.codpacking2 from tmp_packing2 pk2);

        update tmp_packing2 SET rest = cantobj
                                               - coalesce((SELECT sum(pk3.CANT) as consum
                                                         FROM tmp_packing3 pk3 where pk3.CODPACKING2 = codpacking2 group by pk3.CODPACKING2), 0) ;

end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprod_sp_postrecords</obj_name>
  <obj_hashval>9e0f802f8e9876e892031ef6f847f7fc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprod_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  vCod         numeric;
  vOldCod      numeric;
  Nr           numeric;
  aDataDoc     date;
  aDoc         varchar;
  aCARNETDOC   numeric;
  aNRDOC       numeric;
  aSetimana    numeric;
  aCurentWeek  numeric;
  aOldWeek     numeric;
  aAn          numeric;
  aOldAn       numeric;
  aOldSetimana numeric;
  aSubunit     numeric;
BEGIN
  --Florin 07.08.2023 - sinc. Oracle (02.08.2023)
  --Florin 01.06.2023 - monitor
  --Florin 22.05.2023 - corectie PKG_CARNETEDOC_SOLVENUMARDOC
  --Florin 27.01.2021 - fixat 42044
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_planifprod_setct_monitor('MON_45');
  aOldWeek := 0;
  SELECT ADD_DAYS((DATE_TRUNC('DAY', DATE_TRUNC('YEAR', to_date( AN::VARCHAR, 'yyyy'))))::date, ((Saptamana - 1) * 7)::integer), PREFIXDOC || NRDOC || '/' || DATADOC, carnetdoc, nrdoc, saptamana, InSaptamana, An, subunitatea
  INTO aDATADOC, ADOC, acarnetdoc, anrdoc, asetimana, aCurentWeek, aAn, asubunit
  FROM TMP_PLANIFPROD;

  FOR V_REC IN (SELECT * FROM tmp_planifnod WHERE CodPlanifNod &lt; 0) LOOP
    SELECT NEXTVAL('SEQ_PLANIFNOD_CODPLANIFNOD') INTO vCOD;
    vOldCod := V_REC.codplanifnod;

    UPDATE tmp_planifnod SET nodoriginal  = vCOD WHERE nodoriginal = vOldCod;
    UPDATE tmp_planifnod SET codplanifnod = vCOD WHERE codplanifnod = vOldCod;
  END LOOP;

  IF  Operation = 0 THEN
    IF (SELECT WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_PLANIFPROD.CT_MONITOR', true))))
    THEN
      PERFORM pkg_userfirme_postlogcucommit( 'PLANIFPROD', (current_setting('PKG_GLOBALS.USERNAME', true)), 'M', RECID, (current_setting('PKG_GLOBALS.FIRMANAME', true)), (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL)), aDataDoc, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    SELECT CodPLANIFPROD              INTO RecId                          FROM TMP_PLANIFPROD;
    SELECT InSaptamana, An, Saptamana INTO aOldWeek, aOldAn, aOldSetimana FROM planifprod WHERE codplanifprod = recid;

    UPDATE PLANIFPROD
    SET
    (CODPLANIFPROD, CODLANSPROD, AN, LUNA, SUBUNITATEA, USERID, DATACREARE, OBS, ANULAT, OPERAT, BLOCAT, SAPTAMANA, NRDOC, DATADOC, CARNETDOC, SERIADOC, INSAPTAMANA)
    =
    (SELECT CODPLANIFPROD, CODLANSPROD, AN, LUNA, SUBUNITATEA, USERID, DATACREARE, OBS, ANULAT, OPERAT, BLOCAT, SAPTAMANA, NRDOC, DATADOC, CARNETDOC, SERIADOC, INSAPTAMANA
     FROM TMP_PLANIFPROD
    )
    WHERE CodPLANIFPROD = RecId;

    DELETE FROM PLANIFNOD PN1  WHERE PN1.CODPLANIFPROD = RECID AND  NOT  EXISTS (SELECT T1.CODPLANIFPROD  FROM TMP_PLANIFNOD T1   WHERE PN1.CODPLANIFNOD  = T1.CODPLANIFNOD);
    DELETE FROM PLANIFPROD1 P1 WHERE P1.CODPLANIFPROD  = RECID AND  NOT  EXISTS (SELECT T1.CODPLANIFPROD1 FROM TMP_PLANIFPROD1 T1 WHERE T1.CODPLANIFPROD1 = P1.CODPLANIFPROD1);

    FOR V_REC IN (SELECT * FROM TMP_PLANIFPROD1) LOOP
      IF  V_REC.CODPLANIFPROD1 &gt; 0 THEN
        UPDATE PLANIFPROD1
        SET
        CODLANSPROD1 = V_REC.CODLANSPROD1,
        CODOBIECT    = V_REC.CODOBIECT,
        CODRETETA    = V_REC.CODRETETA,
        OBS          = V_REC.OBS,
        NECESAR      = V_REC.NECESAR,
        CANT         = V_REC.CANT,
        CUPROIECT    = V_REC.CUPROIECT,
        CODPROIECT   = V_REC.CODPROIECT
        WHERE
         CODPLANIFPROD1 = V_REC.CODPLANIFPROD1;
      ELSE
        SELECT NEXTVAL('SEQ_PLANIFPROD1_CODPLANIFPROD1') INTO vCod;

        UPDATE tmp_planifnod SET codplanifprod1 = vCod WHERE CodPlanifProd1 = v_rec.codplanifprod1;

        INSERT INTO PLANIFPROD1(CODPLANIFPROD1, CODPLANIFPROD, CODLANSPROD1, CODOBIECT, CODRETETA, OBS, NECESAR, CANT, CUPROIECT, CODPROIECT)
        VALUES(vCod, RecId, V_REC.CODLANSPROD1, V_REC.CODOBIECT, V_REC.CODRETETA, V_REC.OBS, V_REC.NECESAR, V_REC.CANT, V_REC.CUPROIECT, V_REC.CODPROIECT);
      END IF;
    END LOOP;

    FOR v_rec IN (SELECT * FROM tmp_planifnod) LOOP
      SELECT COALESCE( COUNT( *), 0) INTO NR FROM planifnod WHERE codplanifnod = V_REC.codplanifnod;
      IF  NR = 0 THEN
        INSERT INTO PLANIFNOD(CODPLANIFNOD, CODPLANIFPROD1, CODPLANIFPROD, CANT, NECESAR, NODORIGINAL, POZITIE, CODRETETA, TIP, CODOBIECT, INDEXPARINTE, CODPRODMAT, NIVEL, ORDINE, CODPROIECTNOD, VERSIUNE, CANTPRODRETETA, CANTMATRETETA)
        VALUES(V_REC.CODPLANIFNOD, V_REC.CODPLANIFPROD1, RECID, V_REC.CANT, V_REC.NECESAR, V_REC.NODORIGINAL, V_REC.POZITIE, V_REC.CODRETETA, V_REC.TIP, V_REC.CODOBIECT, V_REC.INDEXPARINTE, V_REC.CODPRODMAT, V_REC.NIVEL, V_REC.ORDINE, V_REC.CODPROIECTNOD, V_REC.VERSIUNE, V_REC.CANTPRODRETETA, V_REC.CANTMATRETETA);
      ELSE
        UPDATE PLANIFNOD
        SET
        CANT           = V_REC.CANT,
        NECESAR        = V_REC.NECESAR,
        NODORIGINAL    = V_REC.NODORIGINAL,
        POZITIE        = V_REC.POZITIE,
        CODRETETA      = V_REC.CODRETETA,
        TIP            = V_REC.TIP,
        CODOBIECT      = V_REC.CODOBIECT,
        INDEXPARINTE   = V_REC.INDEXPARINTE,
        CODPRODMAT     = V_REC.CODPRODMAT,
        NIVEL          = V_REC.NIVEL,
        ORDINE         = V_REC.ORDINE,
        CODPROIECTNOD  = V_REC.CODPROIECTNOD,
        VERSIUNE       = V_REC.VERSIUNE,
        CANTPRODRETETA = V_REC.CANTPRODRETETA,
        CANTMATRETETA  = V_REC.CANTMATRETETA
        WHERE
         CODPLANIFNOD = V_REC.CODPLANIFNOD;
      END IF;
    END LOOP;
  ELSE
    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_PLANIFPROD.CT_MONITOR', true))))
    THEN
      PERFORM pkg_userfirme_postlogcucommit( 'PLANIFPROD', (current_setting('PKG_GLOBALS.USERNAME', true)), 'A', RECID, (current_setting('PKG_GLOBALS.FIRMANAME', true)), (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL)), aDataDoc, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    SELECT NEXTVAL('SEQ_PLANIFPROD_CODPLANIFPROD') INTO RecId;

    INSERT INTO PLANIFPROD(CODPLANIFPROD, CODLANSPROD, AN, LUNA, SUBUNITATEA, USERID, DATACREARE, OBS, ANULAT, OPERAT, BLOCAT, SAPTAMANA, NRDOC, DATADOC, CARNETDOC, SERIADOC, INSAPTAMANA)
    (SELECT RecId, CODLANSPROD, AN, LUNA, SUBUNITATEA, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), SYSTIMESTAMP, OBS, ANULAT, OPERAT, BLOCAT, SAPTAMANA, NRDOC, DATADOC, CARNETDOC, SERIADOC, INSAPTAMANA
     FROM TMP_PLANIFPROD
    );

    FOR v_rec IN (SELECT * FROM tmp_planifprod1) LOOP
      SELECT NEXTVAL('SEQ_PLANIFPROD1_CODPLANIFPROD1') INTO vCod;

      UPDATE tmp_planifnod SET codplanifprod1 = vCod WHERE CodPlanifProd1 = v_rec.codplanifprod1;

      INSERT INTO PLANIFPROD1(CODPLANIFPROD1, CODPLANIFPROD, CODLANSPROD1, CODOBIECT, CODRETETA, OBS, NECESAR, CANT, CUPROIECT, CODPROIECT)
      VALUES(vCod, RecId, V_REC.CODLANSPROD1, V_REC.CODOBIECT, V_REC.CODRETETA, V_REC.OBS, V_REC.NECESAR, V_REC.CANT, V_REC.CUPROIECT, V_REC.CODPROIECT);
    END LOOP;

    INSERT INTO PLANIFNOD(CODPLANIFNOD, CODPLANIFPROD1, CODPLANIFPROD, CANT, NECESAR, NODORIGINAL, POZITIE, CODRETETA, TIP, CODOBIECT, INDEXPARINTE, CODPRODMAT, NIVEL, ORDINE, CODPROIECTNOD, VERSIUNE, CANTPRODRETETA, CANTMATRETETA)
    SELECT CODPLANIFNOD, CODPLANIFPROD1, RECID, CANT, NECESAR, NODORIGINAL, POZITIE, CODRETETA, TIP, CODOBIECT, INDEXPARINTE, CODPRODMAT, NIVEL, ORDINE, CODPROIECTNOD, VERSIUNE, CANTPRODRETETA, CANTMATRETETA
    FROM TMP_PLANIFNOD;
  END IF;

  IF (TO_NUMBER((current_setting('PKG_PLANIFPROD.CARNETDOC_I', true)),'999999999999999999') &lt;&gt; 0)  AND (TO_NUMBER((current_setting('PKG_PLANIFPROD.NRDOC_I', true)),'999999999999999999') &lt;&gt; 0)  AND (ACARNETDOC &lt;&gt; TO_NUMBER((current_setting('PKG_PLANIFPROD.CARNETDOC_I', true)),'999999999999999999') OR  ANRDOC &lt;&gt; TO_NUMBER((current_setting('PKG_PLANIFPROD.NRDOC_I', true)),'999999999999999999'))
  THEN
    PERFORM PKG_CARNETEDOC_RELEASENUMARDOC( TO_NUMBER((current_setting('PKG_PLANIFPROD.CARNETDOC_I', true)),'999999999999999999'), TO_NUMBER((current_setting('PKG_PLANIFPROD.NRDOC_I', true)),'999999999999999999'));
    PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE( TO_NUMBER((current_setting('PKG_PLANIFPROD.CARNETDOC_I', true)),'999999999999999999'));
  END IF;

  IF  ACARNETDOC &lt;&gt; 0 THEN
    PERFORM PKG_CARNETEDOC_SOLVENUMARDOC( ACARNETDOC, ANRDOC::varchar);
  END IF;

  IF  aCurentWeek &lt;&gt; 1 THEN
    IF  aSetimana = 1 THEN
      aSetimana := 53;
      aAn       := aAn - 1;
    ELSE
      aSetimana := aSetimana - 1;
    END IF;
  END IF;

  UPDATE lansz SET dirty = 1 WHERE saptamana = asetimana and  an = aAn and  subunitatea = asubunit and  COALESCE( finalizat, 0) = 0;

  --IF  aOldWeek &lt;&gt; aCurentWeek THEN
    IF  aOldWeek &lt;&gt; 1 THEN
      IF  aOldSetimana = 1 THEN
        aOldSetimana := 53;
        aOldAn       := aOldAn - 1;
      ELSE
        aOldSetimana := aOldSetimana - 1;
      END IF;
    END IF;

    UPDATE lansz SET dirty = 1 WHERE saptamana = aOldSetimana and  an = aOldAn and  subunitatea = asubunit and  COALESCE( finalizat, 0) = 0;
  --END IF;

  PERFORM NotifyModif( Operation, RecId, 'PLANIFPROD');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plati_sp_gotorecord</obj_name>
  <obj_hashval>0e62e5cfbc8b946022a29a533d1d163b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plati_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODCONT numeric := 0;
  CodA     numeric;
  aLuna    numeric;
  aLuna1   numeric;
  aLuna2   numeric;
  aAn      numeric;
  aTip     numeric;
  aTipSold numeric;
  CursOrd  numeric;
  AnP      numeric;
  LunaP    numeric;
BEGIN
  --Florin 19.11.2024 - sinc. Oracle
  --Florin 16.05.2024 - sinc. Oracle
  --Florin 22.08.2022 - sinc. Oracle(19.08.2022)
  --Florin 11.11.2020 - fixat 40952
  --Florin 11.03.2021 - fixat 44849
  perform PKG_GLOBALS_SETLUNATEMP(current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric, current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric);

  select NEWAN, NEWLUNA into ANP, LUNAP
  from
     PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA(current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric, current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric,
                                            ANP, LUNAP);
  perform set_config('PKG_GLOBALS.ANPRECEDENT'   ,AnP::varchar  ,false);
  perform set_config('PKG_GLOBALS.LunaPRECEDENTA',LunaP::varchar,false);

  /*
  perform PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA(current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric,
  current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric,
  current_setting('PKG_GLOBALS.ANPRECEDENT', true)::numeric,
  current_setting('PKG_GLOBALS.LUNAPRECEDENTA', true)::numeric);
  */
  INSERT INTO TMP_PLATI (
    CODPLATA,
    data,
    TipDoc,
    CodAnaliza,
    userid,
    --datacreare,
   CODBANKCONT,
    VALOARE,
    CARNETDOC,
    NRDOC,
    SIMBOLMONEDA,
    VALOAREDEREPARTIZAT,
    CODBANK,
    NRCONT,
    AN,
    LUNA,
    CODMONEDA,
    APROBAT,
    OBS,
    CURS )
  (SELECT
      CODPLATA,
      data,
      TipDoc,
      CodAnaliza,
      userid,
      --datacreare,
       BK.CODBANKCONT,
      VALOARE,
      CARNETDOC,
      NRDOC,
      M.SIMBOL,
      VALOAREDEREPARTIZAT,
      BK.CODBANK,
      BK.NRCONT,
      AN,
      LUNA,
      M.CODMONEDA,
      APROBAT,
      P.OBS,
      CURS
   FROM PLATI P
    left join NBANKCONT BK ON BK.CODBANKCONT = P.CODBANKCONT
    left join NMONEDE   M  ON BK.CODMONEDA   = M.CODMONEDA
    WHERE P.CODPLATA = RECID );

  UPDATE TMP_PLATI P
  SET
    SOLDCONT = CASE when coalesce(CODMONEDA, 0) = 0 then (SELECT SOLDLEI FROM V_SOLDURIBANCILUNA WHERE CODBANKCONT = P.CODBANKCONT )
                    else (SELECT SOLDVALUTA FROM V_SOLDURIBANCILUNA WHERE CODBANKCONT = P.CODBANKCONT )
               end ;

  SELECT CodAnaliza, coalesce(TipDoc, 0) INTO CodA, aTip FROM TMP_Plati;

  if aTip = 0 then
    INSERT INTO TMP_PLATI1 (
      CODPLATA1,
      CODOBLIGPIF,
      VALOARE,
      CODMONEDA,
      CONTDEST,
      ADRESAFURN,
      INDEXLOCAL,
      STINSA,
      CODSWIFT,
      CODBNR,
      CODSTATISTICBNR,
      TIPCOMISION,
      CODBANK,
      CODPART,
      SPLITTVA,
      REST,
      DENPART,
      DOC,
      NRDOC,
      VALDOC,
      TERMEN,
      SUBUNITATEA,
      CodAnalizaNod,
      codanalizanodx,
      codpers,
      codcont,
      codfiscal,
      SIMBOLCLASA,
      Obs)
    (SELECT
        P1.CODPLATA1,
        P1.CODOBLIGPIF,
        P1.VALOARE,
        P1.CODMONEDA,
        P1.CONTDEST,
        P1.ADRESAFURN,
        P1.INDEXLOCAL,
        P1.STINSA,
        P1.CODSWIFT,
        P1.CODBNR,
        P1.CODSTATISTICBNR,
        P1.TIPCOMISION,
        P1.CODBANK,
        P.CODPART,
        coalesce(P1.SPLITTVA, 0),
        P1.REST,
        P.DEN_PART,
        I.PREFIXDOC,
        I. NRDOC,
        CASE when coalesce(P1.SPLITTVA, 0) = 0 then O.VALOARE - coalesce(O.DINCARETVA, 0) else O.DINCARETVA end VALOARE,
        O.TERMEN,
        I.SUBUNITATEA,
        O.Codanalizanod,
        P1.codanalizanodx,
        P1.codpers,
        P1.codcont,
        CF.CODFISCAL,
        CLA.SIMBOL,
        I.Obs
     FROM PLATI1 P1,
          OBLIGPIF O,
          general G,
          INTRARI I,
          NPART P
         LEFT JOIN NCLASEP      CLA ON CLA.CODCLASEP = P.CODCLASA
         left join NPARTCODFISC CF  ON CF.CODPART    = P.CODPART and CF.PRINCIPAL = 1
     WHERE
          CODPLATA = RECID
          and O.CODOBLIGPIF = P1.CODOBLIGPIF
          and G.CODGENERAL = O.CODGENERAL
          and G.TIPDOC = I.TIPDOC
          and G.CODDOC = I.CODINTR
          AND G.SEMNIFICATIE = 100
          and P.CODPART = O.CODPART
     union all
     SELECT
          P1.CODPLATA1,
          P1.CODOBLIGPIF,
          P1.VALOARE,
          P1.CODMONEDA,
          P1.CONTDEST,
          P1.ADRESAFURN,
          P1.INDEXLOCAL,
          P1.STINSA,
          P1.CODSWIFT,
          P1.CODBNR,
          P1.CODSTATISTICBNR,
          P1.TIPCOMISION,
          P1.CODBANK,
          P.CODPART,
          coalesce(P1.SPLITTVA, 0),
          P1.REST,
          P.DEN_PART,
          'DVOT',
          D.NRDOC,
          O.VALOARE,
          O.TERMEN,
          I.SUBUNITATEA,
          O.Codanalizanod,
          P1.codanalizanodx,
          P1.codpers,
          P1.codcont,
          CF.CODFISCAL,
          CLA.SIMBOL,
          P.Obs
     FROM PLATI1 P1,
          OBLIGPIF O,
          general G,
          DVI D,
          INTRARI I,
          NPART P
         LEFT JOIN NCLASEP      CLA ON CLA.CODCLASEP = P.CODCLASA
         left join NPARTCODFISC CF  ON CF.CODPART    = P.CODPART and CF.PRINCIPAL = 1
     WHERE
          CODPLATA = RECID
          and O.CODOBLIGPIF = P1.CODOBLIGPIF
          and G.CODGENERAL = O.CODGENERAL
          AND G.SEMNIFICATIE = 130
          and G.TIPDOC = 5
          and G.CODDOC = D.CODDVI
          and D.CODINTR = I.CODINTR
          and P.CODPART = O.CODPART );
  ELSE
    aLuna := current_setting('PKG_GLOBALS.LUNALUCRU', true)::NUMERIC;
    aAn   := current_setting('PKG_GLOBALS.AnLUCRU'  , true)::NUMERIC;

    execute 'DO $$
             BEGIN
               DELETE FROM TMP_BUGETANALIZA;' || coalesce(chr(10), '') ||
            '  PERFORM PKG_ANALIZA_GetBugete( ' || coalesce(CodA::varchar , '') || ', ' || coalesce(current_setting('PKG_GLOBALS.ANLUCRU', true)::varchar, '') || ', 1, 12, 9, 0 );' || coalesce(chr(10), '') ||
            '  DELETE FROM TMP_BUGETANALIZA WHERE CODANALIZANOD IN (SELECT DISTINCT NODPARINTE FROM ANALIZANOD WHERE CODANALIZA = ' || coalesce(CodA::varchar , '') || ');
             END$$;';

    INSERT INTO TMP_PLATI1 (
    CODPLATA1,
    CODOBLIGPIF,
    VALOARE,
    CODMONEDA,
    CONTDEST,
    ADRESAFURN,
    INDEXLOCAL,
    STINSA,
    CODSWIFT,
    CODBNR,
    CODSTATISTICBNR,
    TIPCOMISION,
    CODBANK,
    CODPART,
    DENPART,
    DOC,
    NRDOC,
    VALDOC,
    TERMEN,
    SUBUNITATEA,
    CodAnalizaNod,
    SoldBuget,
    codanalizanodx,
    codpers,
    codcont,
    codfiscal,
    simbolclasa,
    Obs) (
    SELECT
      P1.CODPLATA1,
      P1.CODOBLIGPIF,
      P1.VALOARE,
      P1.CODMONEDA,
      P1.CONTDEST,
      P1.ADRESAFURN,
      P1.INDEXLOCAL,
      P1.STINSA,
      P1.CODSWIFT,
      P1.CODBNR,
      P1.CODSTATISTICBNR,
      P1.TIPCOMISION,
      P1.CODBANK,
      P.CODPART,
      P.DEN_PART,
      I.PREFIXDOC,
      I. NRDOC,
      O.VALOARE,
      O.TERMEN,
      I.SUBUNITATEA,
      O.Codanalizanod,
      0,
      coalesce(P1.codanalizanodx, O.Codanalizanod),
      P1.codpers,
      P1.codcont,
      CF.CODFISCAL,
      CLA.SIMBOL,
      I.Obs
    FROM
      PLATI1 P1,
      OBLIGPIF O,
      general G,
      INTRARI I,
      NPART P
      LEFT JOIN NCLASEP      CLA ON CLA.CODCLASEP = P.CODCLASA
      left join NPARTCODFISC CF  ON CF.CODPART    = P.CODPART and CF.PRINCIPAL = 1
    WHERE
          CODPLATA = RECID
      and O.CODOBLIGPIF = P1.CODOBLIGPIF
      and G.CODGENERAL  = O.CODGENERAL
      and G.TIPDOC  = I.TIPDOC
      and G.CODDOC  = I.CODINTR
      and P.CODPART = O.CODPART
    union all
    SELECT
      P1.CODPLATA1,
      P1.CODOBLIGPIF,
      P1.VALOARE,
      P1.CODMONEDA,
      P1.CONTDEST,
      P1.ADRESAFURN,
      P1.INDEXLOCAL,
      P1.STINSA,
      P1.CODSWIFT,
      P1.CODBNR,
      P1.CODSTATISTICBNR,
      P1.TIPCOMISION,
      P1.CODBANK,
      P.CODPART,
      P.DEN_PART,
      'DVOT',
      D.NRDOC,
      O.VALOARE,
      O.TERMEN,
      I.SUBUNITATEA,
      O.Codanalizanod,
      0,
      coalesce(P1.codanalizanodx, O.Codanalizanod),
      P1.codpers,
      P1.codcont,
      CF.CODFISCAL,
      CLA.SIMBOL,
      D.Obs
    FROM
      PLATI1 P1,
      OBLIGPIF O,
      general G,
      DVI D,
      INTRARI I,
      NPART P
      LEFT JOIN NCLASEP      CLA ON CLA.CODCLASEP = P.CODCLASA
      left join NPARTCODFISC CF  ON CF.CODPART    = P.CODPART and CF.PRINCIPAL = 1
    WHERE
          CODPLATA = RECID
      and O.CODOBLIGPIF = P1.CODOBLIGPIF
      and G.CODGENERAL  = O.CODGENERAL
      and G.TIPDOC  = 5
      and G.CODDOC  = D.CODDVI
      and D.CODINTR = I.CODINTR
      and P.CODPART = O.CODPART );
  end if;

  INSERT INTO TMP_PLATI1 (
    CODPLATA1,
    CODOBLIGPIF,
    VALOARE,
    CODMONEDA,
    CONTDEST,
    ADRESAFURN,
    INDEXLOCAL,
    STINSA,
    CODSWIFT,
    CODBNR,
    CODSTATISTICBNR,
    TIPCOMISION,
    CODBANK,
    CODPART,
    DENPART,
    VALDOC,
    SUBUNITATEA,
    AVANS,
    Codanalizanod,
    Codanalizanodx,
    codpers,
    codcont,
    CODFISCAL,
    SIMBOLCLASA)
  SELECT
    P1.CODPLATA1,
    P1.CODOBLIGPIF,
    P1.VALOARE,
    P1.CODMONEDA,
    P1.CONTDEST,
    P1.ADRESAFURN,
    P1.INDEXLOCAL,
    P1.STINSA,
    P1.CODSWIFT,
    P1.CODBNR,
    P1.CODSTATISTICBNR,
    P1.TIPCOMISION,
    P1.CODBANK,
    P1.CODPART,
    case
      when P1.CODOBLIGPIF = 0 then P.DEN_PART
      when P1.CODOBLIGPIF = 1 then coalesce(A.NUME, '') || ' ' || coalesce(A.PRENUME, '')
      when P1.CODOBLIGPIF = 2 then C.Simbol
    end ,
    P1.VALOARE,
    current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric,
    P1.CODOBLIGPIF + 1,
    P1.codanalizanodx,
    P1.codanalizanodx,
    P1.codpers,
    P1.codcont,
    CF.CODFISCAL,
    CLA.SIMBOL
  FROM PLATI1 P1
    left join NPART        P   ON P.CodPart     = P1.CodPart
    LEFT JOIN NCLASEP      CLA ON CLA.CODCLASEP = P.CODCLASA
    left join NPARTCODFISC CF  ON CF.CODPART    = P.CODPART and CF.PRINCIPAL = 1
    left join NPERS        A   ON A.CodPers     = P1.CodPers
    left join NCont        C   ON C.CodCont     = P1.CodCont
  WHERE
      CODPLATA = RECID and P1.CODOBLIGPIF &lt; 10;

  INSERT INTO TMP_PLATI2(CODPLATA2, CODPLATA, CODPERS, CONTDEST, CODSWIFT, VALOARE,NRDOC, NUME, PRENUME )
  SELECT P2.CODPLATA2, P2.CODPLATA, P2.CODPERS, P2.CONTDEST, P2.CODSWIFT, P2.VALOARE, P2.NRDOC, P.NUME, P.PRENUME
  FROM
   PLATI2 P2
   INNER JOIN NPERS P ON P.CODPERS = P2.CODPERS
  WHERE
   CODPLATA = RecID;

  DELETE FROM TMP_PLATI1_INITIAL;

  INSERT INTO TMP_PLATI1_INITIAL
  SELECT * FROM TMP_PLATI1;

  SELECT coalesce(Curs, 1) INTO CursOrd FROM TMP_PLATI;

  if CursOrd = 0 then CursOrd := 1; end if;

  UPDATE TMP_PLATI1 P1
  SET
    SOLDBUGET = (SELECT sum(case when codcentru = 1 then B1 + B2 + B3 + B4 + B5 + B6 + B7 + B8 + B9 + B10 + B11 + B12 else 0 end )
                 FROM TMP_BUGETANALIZA WHERE codanalizanod = P1.Codanalizanod
                )
                -
                (SELECT sum(case when codcentru = 4 then B1 + B2 + B3 + B4 + B5 + B6 + B7 + B8 + B9 + B10 + B11 + B12 else 0 end )
                 FROM TMP_BUGETANALIZA WHERE codanalizanod = P1.Codanalizanod
                ) ;

  INSERT INTO TMP_PLATIPART ( CODPART, DEN_PART, SUMA, SUMADETALII, Avans, CodPers, CodCont, CodFiscal, SIMBOLCLASA)
  SELECT CODPART, DENPART, round((sum(VALOARE))::numeric, 2), round((sum(VALOARE))::numeric, 2), Avans, CodPers, CodCont, CodFiscal, SIMBOLCLASA
  FROM TMP_PLATI1
  group BY CODPART, DENPART, Avans, CodPers, CodCont, CodFiscal, SIMBOLCLASA;

    INSERT INTO TMP_PLATIPART (DEN_PART, SUMA, SUMADETALII, CodPers)
    SELECT
     NUME || ' ' || PRENUME,
     ROUND(SUM(VALOARE), 2),
     ROUND(SUM(VALOARE), 2),
     CodPers
   FROM
     TMP_PLATI2
   GROUP BY
     NUME || ' ' || PRENUME, CodPers;

  UPDATE TMP_PLATIPART SET DOCLEGATURA = 'X' ;

  DELETE FROM TMP_PLATIPART_INITIAL;

  INSERT INTO TMP_PLATIPART_INITIAL
  SELECT * FROM TMP_PLATIPART;

  if RECID &gt; 0 then
    begin
      SELECT coalesce(CODBANKCONT, 0) INTO aCODCONT FROM TMP_PLATI;
    exception
      when others then aCODCONT := 0;
    end;

    if aCODCONT = 0 then
      UPDATE TMP_PLATI SET CODMONEDA = (SELECT distinct coalesce(CODMONEDA, 0) FROM TMP_PLATI1 ) ;

      UPDATE TMP_PLATI P SET SIMBOLMONEDA = (SELECT SIMBOL FROM NMONEDE M WHERE M.CODMONEDA = P.CODMONEDA ) ;
    end if;
  end if;
  PERFORM PKG_CFGTABLES_EXT_GOTORECORD(105);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_postretail_preia_preturi_noi</obj_name>
  <obj_hashval>16540472589fdae24d691a2bb35daaa7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_postretail_preia_preturi_noi(INOUT acodpostretail numeric, INOUT idprel numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC    RECORD;
  V_REC_D  RECORD;
  V_REC_PA RECORD;
  NR       numeric := 0;
BEGIN
  --Adina 12.03.2021 - prc_al_refresh, alstart, alstop
  CALL prc_al_refresh('tmp_nart1',     0);
  CALL prc_al_refresh('tmp_nartobj11', 0);

  IDPREL := NEXTVAL('SEQ_PRELPRET_RETAIL');

  FOR V_REC IN (SELECT * FROM TMP_NUM) LOOP
    BEGIN
      SELECT COUNT( *) INTO NR FROM NUM WHERE CODUM = V_REC.CODUM;
    EXCEPTION WHEN OTHERS THEN
      NR := 0;
    END;

    IF  NR = 0 THEN
      INSERT INTO NUM(CODUM, DEN_UM, TIP, ZECIMALE, TIPUM, COEF)
      VALUES(V_REC.CODUM, V_REC.DEN_UM, V_REC.TIP, V_REC.ZECIMALE, V_REC.TIPUM, V_REC.COEF);
    ELSE
      UPDATE NUM
      SET
      DEN_UM   = V_REC.DEN_UM,
      TIP      = V_REC.TIP,
      ZECIMALE = V_REC.ZECIMALE,
      TIPUM    = V_REC.TIPUM,
      COEF     = V_REC.COEF
      WHERE
       CODUM = V_REC.CODUM;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_NUM1) LOOP
    BEGIN
      SELECT COUNT( *) INTO NR FROM NUM1 WHERE CODUM1 = V_REC.CODUM1;
    EXCEPTION WHEN OTHERS THEN
      NR := 0;
    END;

    IF  NR = 0 THEN
      INSERT INTO NUM1(CODUM1, CODUM, SECUNDARA, DEN_UM1, PARITATE, ZECIMALE, OBS, CODEXTERN)
      VALUES(V_REC.CODUM1, V_REC.CODUM, V_REC.SECUNDARA, V_REC.DEN_UM1, V_REC.PARITATE, V_REC.ZECIMALE, V_REC.OBS, V_REC.CODEXTERN);
    ELSE
      UPDATE NUM1
      SET
      CODUM     = V_REC.CODUM,
      SECUNDARA = V_REC.SECUNDARA,
      DEN_UM1   = V_REC.DEN_UM1,
      PARITATE  = V_REC.PARITATE,
      ZECIMALE  = V_REC.ZECIMALE,
      OBS       = V_REC.OBS,
      CODEXTERN = V_REC.CODEXTERN
      WHERE
       CODUM1 = V_REC.CODUM1;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_NART) LOOP
    BEGIN
      SELECT COUNT( *) INTO NR FROM NART WHERE CODARTICOL = V_REC.CODARTICOL;
    EXCEPTION WHEN OTHERS THEN
      NR := 0;
    END;

    IF  NR = 0 THEN
      INSERT INTO NART(CODARTICOL, DEN_ARTICOL, TIPARTICOL, UM, TIPSERIE, ARETG, CONTSERVICIU, CASADEMARCAT, CODEXTERNART, SUFIXCODEXTERN)
      VALUES(V_REC.CODARTICOL, V_REC.DEN_ARTICOL, V_REC.TIPARTICOL, V_REC.UM, V_REC.TIPSERIE, V_REC.ARETG, V_REC.CONTSERVICIU, V_REC.CASADEMARCAT, V_REC.CODEXTERNART, V_REC.SUFIXCODEXTERN);
    ELSE
      UPDATE NART
      SET
      CODARTICOL     = V_REC.CODARTICOL,
      DEN_ARTICOL    = V_REC.DEN_ARTICOL,
      TIPARTICOL     = V_REC.TIPARTICOL,
      UM             = V_REC.UM,
      TIPSERIE       = V_REC.TIPSERIE,
      ARETG          = V_REC.ARETG,
      CONTSERVICIU   = V_REC.CONTSERVICIU,
      CASADEMARCAT   = V_REC.CASADEMARCAT,
      CODEXTERNART   = V_REC.CODEXTERNART,
      SUFIXCODEXTERN = V_REC.SUFIXCODEXTERN
      WHERE
       CODARTICOL = V_REC.CODARTICOL;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_NTAXE) LOOP
    BEGIN
      SELECT COUNT( *) INTO NR FROM NTAXE WHERE CODTAXA = V_REC.CODTAXA;
    EXCEPTION WHEN OTHERS THEN
      NR := 0;
    END;

    IF  NR = 0 THEN
      INSERT INTO NTAXE(CODTAXA, DEN_TAXA, CENTRALIZAT)
      VALUES(V_REC.CODTAXA, V_REC.DEN_TAXA, V_REC.CENTRALIZAT);
    ELSE
      UPDATE NTAXE
      SET
      DEN_TAXA    = V_REC.DEN_TAXA,
      CENTRALIZAT = V_REC.CENTRALIZAT
      WHERE
       CODTAXA = V_REC.CODTAXA;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_NART1) LOOP
    BEGIN
      SELECT COUNT( *) INTO NR FROM NART1 WHERE CODARTICOL1 = V_REC.CODARTICOL1;
    EXCEPTION WHEN OTHERS THEN
      NR := 0;
    END;

    IF  NR = 0 THEN
      INSERT INTO NART1(CODARTICOL1, CODARTICOL, CODTVA, CODACCIZE, CODTAXA1, CODTAXA2, ANSTART, LUNASTART, ALSTART, ALSTOP)
      VALUES(V_REC.CODARTICOL1, V_REC.CODARTICOL, V_REC.CODTVA, V_REC.CODACCIZE, V_REC.CODTAXA1, V_REC.CODTAXA2, V_REC.ANSTART, V_REC.LUNASTART, V_REC.ALSTART, V_REC.ALSTOP);
    ELSE
      UPDATE NART1
      SET
      CODARTICOL = V_REC.CODARTICOL,
      CODTVA     = V_REC.CODTVA,
      CODACCIZE  = V_REC.CODACCIZE,
      CODTAXA1   = V_REC.CODTAXA1,
      CODTAXA2   = V_REC.CODTAXA2,
      ANSTART    = V_REC.ANSTART,
      LUNASTART  = V_REC.LUNASTART,
      ALSTART    = V_REC.ALSTART,
      ALSTOP     = V_REC.ALSTOP
      WHERE
       CODARTICOL1 = V_REC.CODARTICOL1;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_NARTOBJ) LOOP
    BEGIN
      SELECT COUNT( *) INTO NR FROM NARTOBJ WHERE CODOBIECT = V_REC.CODOBIECT;
    EXCEPTION WHEN OTHERS THEN
      NR := 0;
    END;

    IF  NR = 0 THEN
      INSERT INTO NARTOBJ(CODOBIECT, CODARTICOL, CODEXTERN, CODINTERN, ROTUNJIRE, PROMOTIE, DENUMIRE, BLOCAT, INACTIV)
      VALUES(V_REC.CODOBIECT, V_REC.CODARTICOL, V_REC.CODEXTERN, V_REC.CODINTERN, V_REC.ROTUNJIRE, V_REC.PROMOTIE, V_REC.DENUMIRE, V_REC.BLOCAT, V_REC.INACTIV);
    ELSE
      UPDATE NARTOBJ
      SET
      CODARTICOL = V_REC.CODARTICOL,
      CODEXTERN  = V_REC.CODEXTERN,
      CODINTERN  = V_REC.CODINTERN,
      ROTUNJIRE  = V_REC.ROTUNJIRE,
      PROMOTIE   = V_REC.PROMOTIE,
      DENUMIRE   = V_REC.DENUMIRE,
      BLOCAT     = V_REC.BLOCAT,
      INACTIV    = V_REC.INACTIV
      WHERE
       CODOBIECT = V_REC.CODOBIECT;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_CODEXTALT) LOOP
    BEGIN
      SELECT COUNT(*) INTO NR FROM CODEXTALT WHERE COD = V_REC.COD;
    EXCEPTION WHEN OTHERS THEN
      NR := 0;
    END;

    IF NR = 0 THEN
      INSERT INTO CODEXTALT (COD, CODOBIECT, CODEXTERN) VALUES(V_REC.COD, V_REC.CODOBIECT, V_REC.CODEXTERN);
     ELSE
      UPDATE CODEXTALT SET CODEXTERN  =  V_REC.CODEXTERN WHERE COD = V_REC.COD;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_NARTOBJ1) LOOP
    BEGIN
      SELECT COUNT( *) INTO NR FROM NARTOBJ1 WHERE CODOBIECT1 = V_REC.CODOBIECT1;
    EXCEPTION WHEN OTHERS THEN
      NR := 0;
    END;

    IF  NR = 0 THEN
      INSERT INTO NARTOBJ1(CODOBIECT1, CODOBIECT, PRETMAXIMAL, PROCADAOSMAXIMAL, ADAOSLA, ANSTART, LUNASTART, PRETREFERINTA, TIPPRETMAX, COMPENSAT, TIPCOMPENSARE, GRUPA, ALSTART, ALSTOP)
      VALUES(V_REC.CODOBIECT1, V_REC.CODOBIECT, V_REC.PRETMAXIMAL, V_REC.PROCADAOSMAXIMAL, V_REC.ADAOSLA, V_REC.ANSTART, V_REC.LUNASTART, V_REC.PRETREFERINTA, V_REC.TIPPRETMAX, V_REC.COMPENSAT, V_REC.TIPCOMPENSARE, V_REC.GRUPA, V_REC.ALSTART, V_REC.ALSTOP);
    ELSE
      UPDATE NARTOBJ1
      SET
      CODOBIECT        = V_REC.CODOBIECT,
      PRETMAXIMAL      = V_REC.PRETMAXIMAL,
      PROCADAOSMAXIMAL = V_REC.PROCADAOSMAXIMAL,
      ADAOSLA          = V_REC.ADAOSLA,
      ANSTART          = V_REC.ANSTART,
      LUNASTART        = V_REC.LUNASTART,
      PRETREFERINTA    = V_REC.PRETREFERINTA,
      TIPPRETMAX       = V_REC.TIPPRETMAX,
      COMPENSAT        = V_REC.COMPENSAT,
      TIPCOMPENSARE    = V_REC.TIPCOMPENSARE,
      GRUPA            = V_REC.GRUPA,
      ALSTART          = V_REC.ALSTART,
      ALSTOP           = V_REC.ALSTOP
      WHERE
       CODOBIECT1 = V_REC.CODOBIECT1;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_NCATPRET) LOOP
    BEGIN
      SELECT COUNT( *) INTO NR FROM NCATPRET WHERE CODCATPRET = V_REC.CODCATPRET;
    EXCEPTION WHEN OTHERS THEN
      NR := 0;
    END;

    IF  NR = 0 THEN
      INSERT INTO NCATPRET(CODCATPRET, DEN_CATPRET, TIP, SIMBOL)
      VALUES(V_REC.CODCATPRET, V_REC.DEN_CATPRET, V_REC.TIP, V_REC.SIMBOL);
    ELSE
      UPDATE NCATPRET
      SET
      DEN_CATPRET = V_REC.DEN_CATPRET,
      TIP         = V_REC.TIP,
      SIMBOL      = V_REC.SIMBOL
      WHERE
       CODCATPRET = V_REC.CODCATPRET;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_PRETM) LOOP
    FOR V_REC_D IN (SELECT * FROM PRETM WHERE CODOBIECT = V_REC.CODOBIECT AND  CODCATPRET = V_REC.CODCATPRET AND  SUBUNITATEA = V_REC.SUBUNITATEA) LOOP
      DELETE FROM PRETMAMB WHERE CODPRETM = V_REC_D.CODPRETM;
      DELETE FROM PRETM     WHERE CODPRETM = V_REC_D.CODPRETM;
    END LOOP;

    BEGIN
      SELECT COUNT( *) INTO NR FROM PRETM WHERE CODPRETM = V_REC.CODPRETM;
    EXCEPTION WHEN OTHERS THEN
      NR := 0;
    END;

    IF  NR = 0 THEN
      INSERT INTO PRETM(CODPRETM, CODOBIECT, CODCATPRET, LEI, VALUTA, MONEDA, IMPLICIT, PROC, INDEXLOCAL, SUBUNITATEA)
      VALUES(V_REC.CODPRETM, V_REC.CODOBIECT, V_REC.CODCATPRET, V_REC.LEI, V_REC.VALUTA, V_REC.MONEDA, V_REC.IMPLICIT, V_REC.PROC, V_REC.INDEXLOCAL, V_REC.SUBUNITATEA);
    ELSE
      UPDATE PRETM
      SET
      CODOBIECT   = V_REC.CODOBIECT,
      CODCATPRET  = V_REC.CODCATPRET,
      LEI         = V_REC.LEI,
      VALUTA      = V_REC.VALUTA,
      MONEDA      = V_REC.MONEDA,
      IMPLICIT    = V_REC.IMPLICIT,
      PROC        = V_REC.PROC,
      INDEXLOCAL  = V_REC.INDEXLOCAL,
      SUBUNITATEA = V_REC.SUBUNITATEA
      WHERE
       CODPRETM = V_REC.CODPRETM;
    END IF;

    FOR V_REC_PA IN (SELECT * FROM TMP_PRETMAMB PA WHERE PA.CODPRETM = V_REC.CODPRETM) LOOP
      UPDATE PRETMAMB
      SET
      CODAMB = V_REC_PA.CODAMB,
      LEI    = V_REC_PA.LEI
      WHERE
       CODPRETMAMB = V_REC_PA.CODPRETMAMB;

      IF NOT FOUND THEN
        INSERT INTO PRETMAMB(CODPRETMAMB, CODPRETM, CODAMB, LEI, VALUTA)
        VALUES(V_REC_PA.CODPRETMAMB, V_REC_PA.CODPRETM, V_REC_PA.CODAMB, V_REC_PA.LEI, V_REC_PA.VALUTA);
      END IF;
    END LOOP;
  END LOOP;

  FOR V_REC IN (SELECT O.CODOBIECT, PM.LEI AS PRETNOU, PM.CODCATPRET FROM TMP_PRETM PM, NARTOBJ O WHERE PM.CODOBIECT = O.CODOBIECT) LOOP
    INSERT INTO SYNCPRETRETAIL(CODSYNC, CODPOSTRETAIL, CODOBIECT, CODCATPRET, PRETNOU, DATA, SINCRONIZAT, IDPRELUARE)
    VALUES(NEXTVAL('SEQ_SYSNPRETRETAIL_CODSYNC'), aCODPOSTRETAIL, V_REC.CODOBIECT, V_REC.CODCATPRET, V_REC.PRETNOU, CURRENT_TIMESTAMP, 1, IDPREL);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_debug</obj_name>
  <obj_hashval>ac7400ee1106b68292df9fa27a1139f8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_debug()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  rez numeric;
begin
  PERFORM pkg_globals_SetLunaLucru(2012, 2,NULL);
  PERFORM PKG_PRETPROD_Get_DifPretProdAllSubunit();
  rez := (SELECT PKG_PRETPROD_UpdatePretNS1Partial.WME_RESULT FROM PKG_PRETPROD_UpdatePretNS1Partial(NULL,24));
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_get_valore_produs</obj_name>
  <obj_hashval>b1d74604651dbcd75627f7b9090f09f7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_get_valore_produs(INOUT wme_result numeric, INOUT acodcomanda1 numeric, INOUT adeazagrezare numeric, INOUT apmp numeric DEFAULT 0)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  iResult          numeric;
  iResultS         NUMERIC(20,6);
  TipCoefIndirecte numeric;
  aAn              numeric;
  aLuna            numeric;
BEGIN
  --Florin 16.03.2023 - sinc. Oracle (14/15.03.2023)
  aAn   := current_setting('PKG_GLOBALS.ANLUCRU'  , true)::numeric;
  aLuna := current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric;

  BEGIN
    SELECT COALESCE((fnc_GetValConstanta('TipCoefIndirecte', aAn, aLuna)::numeric), 0) INTO TipCoefIndirecte;
  EXCEPTION WHEN OTHERS THEN
    TipCoefIndirecte := 1;
  END;

  IF  aPMP &gt; 0 THEN
    IF  TipCoefIndirecte = 2 THEN
      IF  aDeazagrezare = 0 THEN
        SELECT COALESCE(SUM(coalesce(L1.PMP, 0) * L1.CANT
               +  COALESCE(C1.COEFINDIRECTE, 0) * round((CASE
         WHEN COALESCE(ART.RELATIEUM1, 0) = 0 THEN 0
         WHEN ART.RELATIEUM1 IN (1, 7) AND  COALESCE(ART.D1, 0) &lt;&gt; 0                                             THEN L1.cant / ART.D1
         WHEN ART.RELATIEUM1 IN (2, 8) AND  COALESCE(ART.D1, 0) * COALESCE(ART.D2, 0) &lt;&gt; 0                       THEN L1.cant / (  COALESCE(ART.D1, 0) * COALESCE(ART.D2, 0))
         WHEN ART.RELATIEUM1 IN (3, 9) AND  COALESCE(ART.D1, 0) * COALESCE(ART.D2, 0) * COALESCE(ART.D3, 0) &lt;&gt; 0 THEN L1.cant / (  COALESCE(ART.D1, 0) * COALESCE(ART.D2, 0) * COALESCE(ART.D3, 0))
         WHEN ART.RELATIEUM1 IN (4, 10) THEN L1.cant * COALESCE(ART.D1, 0)
         WHEN ART.RELATIEUM1 IN (5, 11) THEN L1.cant * COALESCE(ART.D1, 0) * COALESCE(ART.D2, 0)
         WHEN ART.RELATIEUM1 IN (6, 12) THEN L1.cant * COALESCE(ART.D1, 0) * COALESCE(ART.D2, 0) * COALESCE(ART.D3, 0)
                                                        END )::numeric, (COALESCE(UM1.ZECIMALE, 1))::int
                                                      ) * COALESCE(NUM.COEF, 1)), 0)
        INTO IRESULT
        FROM IESIRI I, IESIRI1 I1
            INNER JOIN NUM1    UM1 ON  UM1.CODUM1     = I1.UMSEC, LIVR1 L1, LIVR L, NIRSTOC NS
            INNER JOIN NIR         ON  NIR.CODNIR     = NS.CODNIR
            INNER JOIN NARTOBJ OBJ ON  OBJ.CODOBIECT  = NS.CODOBIECT
            INNER JOIN NART    ART ON  ART.CODARTICOL = OBJ.CODARTICOL
            INNER JOIN NUM         ON  NUM.CODUM      = ART.UM
            LEFT  JOIN DVI         ON  DVI.CODINTR    = NIR.CODNIR, COMANDA1 C1
        WHERE  I.CODIES = I1.CODIES AND  L.CODIES = I.CODIES AND  I1.CODIES1 = L1.CODIES1 AND  L.CODLIVR = L1.CODLIVR AND  L.TIPLIVR = 24
          AND  L1.CODNIRSTOC = NS.CODNIRSTOC AND  C1.CODCOMANDA1 = I1.CODCMDINT1 AND  C1.CODCOMANDA1 = aCodcomanda1 AND  COALESCE(DVI.TIPIMPORT, 0) = 0;
      ELSE
        SELECT COALESCE(SUM(coalesce(L1.PMP, 0) * L1.CANT
               +  COALESCE(C1.COEFINDIRECTE, 0) * round((CASE
         WHEN  COALESCE(ART.RELATIEUM1, 0) = 0 THEN 0
         WHEN ART.RELATIEUM1 IN (1, 7) AND  COALESCE(ART.D1, 0) &lt;&gt; 0                                             THEN L1.cant / ART.D1
         WHEN ART.RELATIEUM1 IN (2, 8) AND  COALESCE(ART.D1, 0) * COALESCE(ART.D2, 0) &lt;&gt; 0                       THEN L1.cant / (  COALESCE(ART.D1, 0) * COALESCE(ART.D2, 0))
         WHEN ART.RELATIEUM1 IN (3, 9) AND  COALESCE(ART.D1, 0) * COALESCE(ART.D2, 0) * COALESCE(ART.D3, 0) &lt;&gt; 0 THEN L1.cant / (  COALESCE(ART.D1, 0) * COALESCE(ART.D2, 0) * COALESCE(ART.D3, 0))
         WHEN ART.RELATIEUM1 IN (4, 10) THEN L1.cant * COALESCE(ART.D1, 0)
         WHEN ART.RELATIEUM1 IN (5, 11) THEN L1.cant * COALESCE(ART.D1, 0) * COALESCE(ART.D2, 0)
         WHEN ART.RELATIEUM1 IN (6, 12) THEN L1.cant * COALESCE(ART.D1, 0) * COALESCE(ART.D2, 0) * COALESCE(ART.D3, 0)
                                                         END )::numeric, (COALESCE(UM1.ZECIMALE, 1))::int
                                                        ) * COALESCE(NUM.COEF, 1)), 0)
        INTO IRESULT
        FROM IESIRI I, IESIRI1 I1
        INNER JOIN NUM1    UM1 ON  UM1.CODUM1     = I1.UMSEC, LIVR1 L1, LIVR L, NIRSTOC NS
        INNER JOIN NIR         ON  NIR.CODNIR     = NS.CODNIR
        INNER JOIN NARTOBJ OBJ ON  OBJ.CODOBIECT  = NS.CODOBIECT
        INNER JOIN NART    ART ON  ART.CODARTICOL = OBJ.CODARTICOL
        INNER JOIN NUM         ON  NUM.CODUM      = ART.UM
        LEFT  JOIN DVI         ON  DVI.CODINTR    = NIR.CODNIR, COMANDA1 C1
        WHERE  I.CODIES = I1.CODIES AND  L.CODIES = I.CODIES AND  I1.CODIES1 = L1.CODIES1 AND  L.CODLIVR = L1.CODLIVR AND  L.TIPLIVR = 24
          AND  L1.CODNIRSTOC = NS.CODNIRSTOC AND  C1.CODCOMANDA1 = I1.CODCMDINT1 AND  C1.CODCOMANDA1 = aCodcomanda1 AND  COALESCE(DVI.TIPIMPORT, 0) = 0;
      END IF;
    ELSE
      IF  TipCoefIndirecte = 3 THEN
        IF  aDeazagrezare = 0 THEN
          BEGIN
            SELECT SUM(coalesce(L1.PMP, 0) * L1.CANT) + COALESCE(C1.COEFINDIRECTE, 0) * COALESCE(PM.CANTUM1, TipCoefIndirecte - 2) / PM.CANT * L1.CANT
            INTO IRESULT
            FROM CMDPRODMAT CMD, PRODMAT PM, IESPRODLINK IES, LIVR1 L1, LIVR L, NIRSTOC NS
                INNER JOIN NIR ON  NIR.CODNIR  = NS.CODNIR
                LEFT  JOIN DVI ON  DVI.CODINTR = NIR.CODNIR, COMANDA1 C1
            WHERE  CMD.CODCMDPRODMAT = IES.CODCMDPRODMAT AND  PM.CODMAT = CMD.CODPRODMAT AND  IES.CODIES1 = L1.CODIES1 AND  L.CODLIVR = L1.CODLIVR
              AND  L.TIPLIVR = 24 AND  L1.CODNIRSTOC = NS.CODNIRSTOC AND  C1.CODCOMANDA1 = CMD.CODCOMANDA1 AND  CMD.CODCOMANDA1 = aCodcomanda1
              AND  COALESCE(DVI.TIPIMPORT, 0) = 0
            GROUP BY COALESCE(C1.COEFINDIRECTE, 0) * COALESCE(PM.CANTUM1, TipCoefIndirecte - 2) / PM.CANT * L1.CANT;
          EXCEPTION WHEN others THEN
            IRESULT := 0;
          END;
        ELSE
          BEGIN
            SELECT SUM(coalesce(L1.PMP, 0) * L1.CANT) + COALESCE(C1.COEFINDIRECTE, 0) * COALESCE(PM.CANTUM1, TipCoefIndirecte - 2) / PM.CANT * L1.CANT
            INTO IRESULT
            FROM CMDPRODMAT CMD, PRODCOMP PM, IESPRODLINK IES, LIVR1 L1, LIVR L, NIRSTOC NS
            INNER JOIN NIR ON  NIR.CODNIR  = NS.CODNIR
            LEFT  JOIN DVI ON  DVI.CODINTR = NIR.CODNIR, COMANDA1 C1
            WHERE CMD.CODCMDPRODMAT = IES.CODCMDPRODMAT AND  PM.CODPRODCOMP = C1.CODRETETA AND  IES.CODIES1 = L1.CODIES1 AND  L.CODLIVR = L1.CODLIVR
              AND  L.TIPLIVR = 24 AND  L1.CODNIRSTOC = NS.CODNIRSTOC AND  C1.CODCOMANDA1 = CMD.CODCOMANDA1 AND  CMD.CODCOMANDA1 = aCodcomanda1
              AND  COALESCE(DVI.TIPIMPORT, 0) = 0
            GROUP BY COALESCE(C1.COEFINDIRECTE, 0) * COALESCE(PM.CANTUM1, TipCoefIndirecte - 2) / PM.CANT * L1.CANT;
          EXCEPTION WHEN others THEN
            IRESULT := 0;
          END;
        END IF;
      ELSE
        BEGIN
          SELECT COALESCE(SUM(coalesce(L1.PMP, 0) * L1.CANT * (  COALESCE(C1.COEFINDIRECTE, 0) + 1) ), 0)
          INTO IRESULT
          FROM IESIRI I, IESIRI1 I1, LIVR1 L1, LIVR L, NIRSTOC NS
          INNER JOIN NIR         ON  NIR.CODNIR     = NS.CODNIR
          INNER JOIN NARTOBJ OBJ ON  OBJ.CODOBIECT  = NS.CODOBIECT
          INNER JOIN NART    ART ON  ART.CODARTICOL = OBJ.CODARTICOL
          INNER JOIN NUM         ON  NUM.CODUM      = ART.UM
          LEFT  JOIN DVI         ON  DVI.CODINTR    = NIR.CODNIR, COMANDA1 C1
          WHERE I.CODIES = I1.CODIES AND  L.CODIES = I.CODIES AND  I1.CODIES1 = L1.CODIES1 AND  L.CODLIVR = L1.CODLIVR AND  L.TIPLIVR = 24
            AND  L1.CODNIRSTOC = NS.CODNIRSTOC AND  C1.CODCOMANDA1 = I1.CODCMDINT1 AND  C1.CODCOMANDA1 = aCodcomanda1 AND  COALESCE(DVI.TIPIMPORT, 0) = 0;
        EXCEPTION WHEN others THEN
          IRESULT := 0;
        END;
      END IF;
    END IF;
  ELSE
    IF  TipCoefIndirecte = 2 THEN
      IF  aDeazagrezare = 0 THEN
        SELECT COALESCE(SUM((  COALESCE(NS.PRET, 0) - COALESCE(NS.ADAOS, 0))  * L1.CANT
               + COALESCE(C1.COEFINDIRECTE, 0) * round((CASE
         WHEN  COALESCE(ART.RELATIEUM1, 0) = 0 THEN 0
         WHEN ART.RELATIEUM1 IN (1, 7) AND  COALESCE(ART.D1, 0) &lt;&gt; 0                                             THEN L1.cant / ART.D1
         WHEN ART.RELATIEUM1 IN (2, 8) AND  COALESCE(ART.D1, 0) * COALESCE(ART.D2, 0) &lt;&gt; 0                       THEN L1.cant / (  COALESCE(ART.D1, 0) * COALESCE(ART.D2, 0))
         WHEN ART.RELATIEUM1 IN (3, 9) AND  COALESCE(ART.D1, 0) * COALESCE(ART.D2, 0) * COALESCE(ART.D3, 0) &lt;&gt; 0 THEN L1.cant / (  COALESCE(ART.D1, 0) * COALESCE(ART.D2, 0) * COALESCE(ART.D3, 0))
         WHEN ART.RELATIEUM1 IN (4, 10) THEN L1.cant * COALESCE(ART.D1, 0)
         WHEN ART.RELATIEUM1 IN (5, 11) THEN L1.cant * COALESCE(ART.D1, 0) * COALESCE(ART.D2, 0)
         WHEN ART.RELATIEUM1 IN (6, 12) THEN L1.cant * COALESCE(ART.D1, 0) * COALESCE(ART.D2, 0) * COALESCE(ART.D3, 0)
                                                        END )::numeric, (COALESCE(UM1.ZECIMALE, 1))::int
                                                       ) * COALESCE(NUM.COEF, 1)), 0)
        INTO IRESULT
        FROM IESIRI I, IESIRI1 I1
        INNER JOIN NUM1 UM1    ON  UM1.CODUM1     = I1.UMSEC, LIVR1 L1, LIVR L, NIRSTOC NS
        INNER JOIN NIR         ON  NIR.CODNIR     = NS.CODNIR
        INNER JOIN NARTOBJ OBJ ON  OBJ.CODOBIECT  = NS.CODOBIECT
        INNER JOIN NART    ART ON  ART.CODARTICOL = OBJ.CODARTICOL
        INNER JOIN NUM         ON  NUM.CODUM      = ART.UM
        LEFT  JOIN DVI         ON  DVI.CODINTR    = NIR.CODNIR, COMANDA1 C1
        WHERE  I.CODIES = I1.CODIES AND  L.CODIES = I.CODIES AND  I1.CODIES1 = L1.CODIES1 AND  L.CODLIVR = L1.CODLIVR AND  L.TIPLIVR = 24
          AND  L1.CODNIRSTOC = NS.CODNIRSTOC AND  C1.CODCOMANDA1 = I1.CODCMDINT1 AND  C1.CODCOMANDA1 = aCodcomanda1 AND  COALESCE(DVI.TIPIMPORT, 0) = 0;
      ELSE
        SELECT COALESCE(SUM((  COALESCE(NS.PRET, 0) - COALESCE(NS.ADAOS, 0))  * L1.CANT
               + COALESCE(C1.COEFINDIRECTE, 0) * round((CASE
         WHEN  COALESCE(ART.RELATIEUM1, 0) = 0 THEN 0
         WHEN ART.RELATIEUM1 IN (1, 7) AND  COALESCE(ART.D1, 0) &lt;&gt; 0                                             THEN L1.cant / ART.D1
         WHEN ART.RELATIEUM1 IN (2, 8) AND  COALESCE(ART.D1, 0) * COALESCE(ART.D2, 0) &lt;&gt; 0                       THEN L1.cant / (  COALESCE(ART.D1, 0) * COALESCE(ART.D2, 0))
         WHEN ART.RELATIEUM1 IN (3, 9) AND  COALESCE(ART.D1, 0) * COALESCE(ART.D2, 0) * COALESCE(ART.D3, 0) &lt;&gt; 0 THEN L1.cant / (  COALESCE(ART.D1, 0) * COALESCE(ART.D2, 0) * COALESCE(ART.D3, 0))
         WHEN ART.RELATIEUM1 IN (4, 10) THEN L1.cant * COALESCE(ART.D1, 0)
         WHEN ART.RELATIEUM1 IN (5, 11) THEN L1.cant * COALESCE(ART.D1, 0) * COALESCE(ART.D2, 0)
         WHEN ART.RELATIEUM1 IN (6, 12) THEN L1.cant * COALESCE(ART.D1, 0) * COALESCE(ART.D2, 0) * COALESCE(ART.D3, 0)
                                                        END )::numeric, (COALESCE(UM1.ZECIMALE, 1))::int
                                                       ) * COALESCE(NUM.COEF, 1)), 0)
        INTO IRESULT
        FROM IESIRI I, IESIRI1 I1
        INNER JOIN NUM1 UM1    ON  UM1.CODUM1     = I1.UMSEC, LIVR1 L1, LIVR L, NIRSTOC NS
        INNER JOIN NIR         ON  NIR.CODNIR     = NS.CODNIR
        INNER JOIN NARTOBJ OBJ ON  OBJ.CODOBIECT  = NS.CODOBIECT
        INNER JOIN NART    ART ON  ART.CODARTICOL = OBJ.CODARTICOL
        INNER JOIN NUM         ON  NUM.CODUM      = ART.UM
        LEFT  JOIN DVI         ON  DVI.CODINTR    = NIR.CODNIR, COMANDA1 C1
        WHERE  I.CODIES = I1.CODIES AND  L.CODIES = I.CODIES AND  I1.CODIES1 = L1.CODIES1 AND  L.CODLIVR = L1.CODLIVR AND  L.TIPLIVR = 24
          AND  L1.CODNIRSTOC = NS.CODNIRSTOC AND  C1.CODCOMANDA1 = I1.CODCMDINT1 AND  C1.CODCOMANDA1 = aCodcomanda1 AND  COALESCE(DVI.TIPIMPORT, 0) = 0;
      END IF;
    ELSE
      IF  TipCoefIndirecte = 3 THEN
        IF  aDeazagrezare = 0 THEN
          BEGIN
            SELECT SUM((  COALESCE(NS.PRET, 0) - COALESCE(NS.ADAOS, 0))  * L1.CANT) + COALESCE(C1.COEFINDIRECTE, 0) * COALESCE(PM.CANTUM1, TipCoefIndirecte - 2) / PM.CANT * L1.CANT
            INTO IRESULT
            FROM CMDPRODMAT CMD, PRODMAT PM, IESPRODLINK IES, LIVR1 L1, LIVR L, NIRSTOC NS
                INNER JOIN NIR ON  NIR.CODNIR  = NS.CODNIR
                LEFT  JOIN DVI ON  DVI.CODINTR = NIR.CODNIR, COMANDA1 C1
            WHERE  CMD.CODCMDPRODMAT = IES.CODCMDPRODMAT AND  PM.CODMAT = CMD.CODPRODMAT AND  IES.CODIES1 = L1.CODIES1 AND  L.CODLIVR = L1.CODLIVR
              AND  L.TIPLIVR = 24 AND  L1.CODNIRSTOC = NS.CODNIRSTOC AND  C1.CODCOMANDA1 = CMD.CODCOMANDA1 AND  CMD.CODCOMANDA1 = aCodcomanda1
              AND  COALESCE(DVI.TIPIMPORT, 0) = 0
            GROUP BY COALESCE(C1.COEFINDIRECTE, 0) * COALESCE(PM.CANTUM1, TipCoefIndirecte - 2) / PM.CANT * L1.CANT;
          EXCEPTION WHEN others THEN
            IRESULT := 0;
          END;
        ELSE
          BEGIN
            SELECT SUM((  COALESCE(NS.PRET, 0) - COALESCE(NS.ADAOS, 0))  * L1.CANT) + COALESCE(C1.COEFINDIRECTE, 0) * COALESCE(PM.CANTUM1, TipCoefIndirecte - 2) / PM.CANT * L1.CANT
            INTO IRESULT
            FROM CMDPRODMAT CMD, PRODCOMP PM, IESPRODLINK IES, LIVR1 L1, LIVR L, NIRSTOC NS
                INNER JOIN NIR ON  NIR.CODNIR  = NS.CODNIR
                LEFT  JOIN DVI ON  DVI.CODINTR = NIR.CODNIR, COMANDA1 C1
            WHERE CMD.CODCMDPRODMAT = IES.CODCMDPRODMAT AND  PM.CODPRODCOMP = C1.CODRETETA AND  IES.CODIES1 = L1.CODIES1 AND  L.CODLIVR = L1.CODLIVR AND  L.TIPLIVR = 24 AND  L1.CODNIRSTOC = NS.CODNIRSTOC AND  C1.CODCOMANDA1 = CMD.CODCOMANDA1 AND  CMD.CODCOMANDA1 = aCodcomanda1 AND  COALESCE(DVI.TIPIMPORT, 0) = 0
            GROUP BY COALESCE(C1.COEFINDIRECTE, 0) * COALESCE(PM.CANTUM1, TipCoefIndirecte - 2) / PM.CANT * L1.CANT;
          EXCEPTION WHEN others THEN
            IRESULT := 0;
          END;
        END IF;
      ELSE
        BEGIN
          SELECT COALESCE(SUM((  COALESCE(NS.PRET, 0) - COALESCE(NS.ADAOS, 0))  * L1.CANT * (  COALESCE(C1.COEFINDIRECTE, 0) + 1) ), 0)
          INTO IRESULT
          FROM IESIRI I, IESIRI1 I1, LIVR1 L1, LIVR L, NIRSTOC NS
          INNER JOIN NIR         ON  NIR.CODNIR = NS.CODNIR
          INNER JOIN NARTOBJ OBJ ON  OBJ.CODOBIECT = NS.CODOBIECT
          INNER JOIN NART    ART ON  ART.CODARTICOL = OBJ.CODARTICOL
          INNER JOIN NUM         ON  NUM.CODUM = ART.UM
          LEFT  JOIN DVI         ON  DVI.CODINTR = NIR.CODNIR, COMANDA1 C1
          WHERE  I.CODIES = I1.CODIES AND  L.CODIES = I.CODIES AND  I1.CODIES1 = L1.CODIES1 AND  L.CODLIVR = L1.CODLIVR AND  L.TIPLIVR = 24
            AND  L1.CODNIRSTOC = NS.CODNIRSTOC AND  C1.CODCOMANDA1 = I1.CODCMDINT1 AND  C1.CODCOMANDA1 = aCodcomanda1 AND  COALESCE(DVI.TIPIMPORT, 0) = 0;
        EXCEPTION WHEN others THEN
          IRESULT := 0;
        END;
      END IF;
    END IF;
  END IF;

  BEGIN
    SELECT coalesce(SUM(I1.PU * I1.CANT),0) * case when coalesce(i.moneda,0) &gt; 0 then i.curs else 1 end INTO IRESULTS
    FROM INTRARI I,
    INTRARI1 I1
    WHERE I1.CODCMDINT1 = aCodcomanda1
     AND COALESCE(I.ANULAT,0) = 0 AND I.OPERAT = 1 AND I1.TIPLINIE = 'S'
     AND I.CODINTR = I1.CODINTR
     and exists (
       select mat.codobiect
       from prodmat mat
         inner join cmdprodmat cmd on cmd.codprodmat = mat.codmat
         inner join comanda1 c1 on c1.codcomanda1 = cmd.codcomanda1
       where c1.codcomanda1 = aCodComanda1 and mat.tip = 6 and mat.codobiect = i1.codobiect
     );
  exception when others then IRESULTS := 0;
  END;
  WME_Result :=  coalesce(iResult,0) + coalesce(iResultS,0);
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_tras_maketmpserii</obj_name>
  <obj_hashval>5e847de6f6afbf4dc67c269198afb4fd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_tras_maketmpserii()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  AnPrec   numeric;
  LunaPrec numeric;
  AnTemp   numeric;
  LunaTemp numeric;
  vDataIni date := add_months(last_day(PKG_LIST_SELTRAS_getDataIni),-1);
  vDataFin date := PKG_LIST_SELTRAS_getDataFin;
  sView    TEXT;
  vSQL     TEXT;
BEGIN
  --Stef 12.05.2022 - curatenie PKG_LIST_BASE_UTILS CT_XXX
  AnTemp   := EXTRACT( YEAR  FROM PKG_LIST_SELTRAS_getDataIni);
  LunaTemp := EXTRACT( MONTH FROM PKG_LIST_SELTRAS_getDataIni);
  PERFORM pkg_globals_SetLunaTemp( anTemp, LunaTemp);
  SELECT NEWAN, newLuna FROM PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA(AnTemp, LunaTemp, AnPrec, LunaPrec) INTO AnPrec, LunaPrec;
  PERFORM pkg_globals_SetLunaPRECEDENTA( Anprec, LunaPrec);

  SELECT v_stoc_luna_prec() INTO sView;

  vSQL =
  'INSERT INTO tmp_manevra_liste(filtru, valoare)
  SELECT  DISTINCT ''CODNIRSTOC'', CODNIRSTOC::varchar
  FROM (
      SELECT v.codnirstoc
      FROM tmp_manevra_liste tmp
      INNER JOIN nirstoc ns ON  ns.codobiect::varchar = tmp.valoare
      INNER JOIN ('||sView||') v ON  ns.codnirstoc = v.CODNIRSTOC
      WHERE tmp.filtru = ''CODOBIECT''
      union
      SELECT ns.codnirstoc
      FROM tmp_manevra_liste tmp
      INNER JOIN nirstoc ns ON  ns.codobiect::varchar = tmp.valoare
      LEFT JOIN nir n ON  ns.codnir = n.codnir
      LEFT JOIN LIVR1 L1 ON  NS.CODNIRSTOC = L1.CODNIRSTOC
      LEFT JOIN LIVR L ON  L1.CODLIVR = L.CODLIVR
      WHERE tmp.filtru = ''CODOBIECT'' AND COALESCE( n.datanir, l.datalivr, vDataIni - 1) BETWEEN vDataIni AND vDataFin
  ) A_PG';

  EXECUTE vSQL;
  PERFORM pkg_list_base_utils_BAGA_SERII_IN_TMP( PKG_LIST_BASE_UTILS_CT_TOATE() );
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_tras_processlist</obj_name>
  <obj_hashval>e126f730f2a8838cdf974cbc2ed50f0e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_tras_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     TEXT;
  sTipC       TEXT    := '';
  sGest       TEXT    := '';
  gSuplCols   VARCHAR := 'nartobj nobj, nart n, npart furn, npart prod, npart part, nsubunit nsub, ngest gestprod, ngest ng, ioart io, ioart1 io1, ncont ncont, nlocatii loc, nirstoc ns, nirstoc nsroot, ' || 'ngest gestdest, nirser nser, nserii ser, nsubunit sub, nclaseas ncls, num um, num um1, num um2, num1 num1, nartamb aa, comanda cint';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Stef 16.05.2022 - curatenie PKG_LIST_BASE_UTILS CT_XXX
  --PERFORM pkg_globals_setdebugmode(true);
  UPDATE TMP_MANEVRA_LISTE SET VALOARE1 = NULLIF (VALOARE1, ''), VALOARE2 = NULLIF (VALOARE2, '');

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_AddSuplTabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = NOBJ.CODOBIECT');
  call pkg_list_struct_AddSuplTabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = NOBJ.CODOBIECT');
  call pkg_list_struct_AddSuplTabs(gSuplCols, 'IESIRI1',    'IES1', 'IES1.CODIES1 = CRS.CODIES1'     , 1);
  call pkg_list_struct_AddSuplTabs(gSuplCols, 'IESIRI',     'IES',  'IES.CODIES = IES1.CODIES');
  call pkg_list_struct_AddSuplTabs(gSuplCols, 'INTRARI1',   'INTR1','INTR1.CODINTR1 = CRS.CODINTR1'  , 1);
  call pkg_list_struct_AddSuplTabs(gSuplCols, 'INTRARI',    'INTR', 'INTR.CODINTR = INTR1.CODINTR');
  call pkg_list_struct_AddSuplTabs(gSuplCols, 'TRANSF1',    'TR1',  'TR1.CODTRANSF1 = CRS.CODTRANSF1', 1);
  call pkg_list_struct_AddSuplTabs(gSuplCols, 'TRANSF',     'TR',   'TR.CODTRANSF = TR1.CODTRANSF');
  call pkg_list_struct_AddSuplTabs(gSuplCols, 'NAGENDA',    'SLIVR','SLIVR.CODAGENDA = CRS.CODSLIVR' , 1);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);

  sInsert :=
  'INSERT INTO '||tmpname||'(
    NAV_CODDOC, NAV_TIPDOC, CODNIRSTOC, DENUMIRE, INTRARE, IESIRE, STOC_FAKE, PACHIZ, PINREG, PUMAXIMAL, DATAEXP,
    DENFURN, DENPROD,
    PREFIXDOC, SERIADOC, NRDOC, DATADOC, DATAMISC,
    DINTRPREFIX, DINTRSERIA, DINTRNR, DINTRDATA,
    DIESPREFIX, DIESSERIA, DIESNR, DIESDATA,
    ORDINE, PARTENER, DEN_GEST, DEN_IOART, SIMBOL, DENLOCATIE,
    SERII,CODLIVR1,SUBUNITATEA_DOC, D1,D2,D3,CLASAS,CODEXTERN,UM,UM1,UM2, NRCOMINT,DATACOMINT'||gUserFields||')';

  IF NOT PKG_LIST_SELTRAS_isAllTipCont() THEN
    sTipC := '
        AND NS.CODIOART::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'') ' ;
  END IF;
  IF NOT PKG_LIST_SELTRAS_isAllGest() THEN
    sGest := '
        AND (
          N.GEST::varchar        IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') OR
          NS.CODLOCATIE::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'')
        ) ';
  END IF;

  PERFORM set_config('PKG_LIST_BASE_TRAS.gSuplCols',  gSuplCols,  false);
  PERFORM set_config('PKG_LIST_BASE_TRAS.gUserFields',gUserFields,false);
  PERFORM set_config('PKG_LIST_BASE_TRAS.gUserAlias', gUserAlias, false);
  PERFORM set_config('PKG_LIST_BASE_TRAS.gNullAlias', gNullAlias, false);
  PERFORM set_config('PKG_LIST_BASE_TRAS.gSuplJoins', gSuplJoins, false);

  CALL PRC_AL_CHECK('IOART1');
  PERFORM pkg_list_base_tras_MakeSQLStocIni(sInsert, sTipC, sGest);
  PERFORM pkg_list_base_tras_MakeSQLMiscari(sInsert, sTipC, sGest);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_trascmdint_processlist</obj_name>
  <obj_hashval>e2c4d3de3cc37b3bf8626a90ebc113e6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_trascmdint_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar := '';
  sSelect     varchar := '';
  gSuplCols   varchar := 'comanda1 c1,comanda c,cmdprodmat mat,cmdprodman man';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 14.09.2020

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_TRASCMDINT.gSuplCols', gSuplCols, FALSE);

  PERFORM PKG_LIST_BASE_TRASCMDINT_UmpleTemporar();

  IF NOT current_setting('PKG_LIST_SELECTPERIOADA.vOpt1', TRUE)::NUMERIC = 1 THEN
    sInsert := 'INSERT INTO ' || TMPNAME || '(
           COD,
           NRDOC,
           DataDoc,
           PRODUS,
           SERIEPRODUS,
           IOARTPRODUS,
           CANTPRODUS,
           PRETPRODUS,
           VALPRODUS,
           MATERIAL,
           SERIEMATERIAL,
           IOARTMATERIAL,
           CANTMATERIAL,
           PRETMATERIAL,
           VALMATERIAL,
           OPERATIE,
           NROP,
           VALOP
           ' || gUserFields || ')';
    sSelect := '
      select
        tmp.COD,
        c.NRDOC,
        c.DataDoc,
        tmp.PRODUS,
        tmp.SERIEPRODUS,
        tmp.IOARTPRODUS,
        tmp.CANTPRODUS,
        tmp.PRETPRODUS,
        tmp.VALPRODUS,
        tmp.MATERIAL,
        tmp.SERIEMATERIAL,
        tmp.IOARTMATERIAL,
        tmp.CANTMATERIAL,
        tmp.PRETMATERIAL,
        tmp.VALMATERIAL,
        tmp.OPERATIE,
        tmp.NROP,
        tmp.VALOP ' || gUserAlias || '
      from tmp_trascmdint        tmp
           inner join comanda1   c1  on tmp.codcomanda1   = c1.codcomanda1
           inner join comanda    c   on c1.codcomanda     = c.codcomanda
           left  join cmdprodmat mat on mat.codcmdprodmat = tmp.codcmdprodmat
           left  join cmdprodman man on man.codcmdprodman = tmp.codcmdprodman' || gSuplJoins;
  ELSE
    sInsert := 'INSERT INTO ' || TMPNAME || '(
           COD,
           NRDOC,
           DataDoc,
           PRODUS,
           IOARTPRODUS,
           CANTPRODUS,
           PRETPRODUS,
           VALPRODUS,
           MATERIAL,
           IOARTMATERIAL,
           CANTMATERIAL,
           PRETMATERIAL,
           VALMATERIAL,
           OPERATIE,
           NROP,
           VALOP
           ' || gUserFields || ')';
    sSelect := '
      select
        tmp.COD,
        c.NRDOC,
        c.DataDoc,
        tmp.PRODUS,
        tmp.IOARTPRODUS,
        tmp.CANTPRODUS,
        tmp.PRETPRODUS,
        tmp.VALPRODUS,
        tmp.MATERIAL,
        tmp.IOARTMATERIAL,
        tmp.CANTMATERIAL,
        tmp.PRETMATERIAL,
        tmp.VALMATERIAL,
        tmp.OPERATIE,
        tmp.NROP,
        tmp.VALOP ' || gUserAlias || '
      from tmp_trascmdint tmp
           inner join comanda1   c1  on tmp.codcomanda1   = c1.codcomanda1
           inner join comanda    c   on c1.codcomanda     = c.codcomanda
           left  join cmdprodmat mat on mat.codcmdprodmat = tmp.codcmdprodmat
           left  join cmdprodman man on man.codcmdprodman = tmp.codcmdprodman' || gSuplJoins;
  END IF;
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_trascmdint_setjoinuri</obj_name>
  <obj_hashval>9f6152716776bae4fa8b7812b761c7bd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_trascmdint_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_TRASCMDINT.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_trascmdint_test</obj_name>
  <obj_hashval>1be693c1b08fd85019fdf6afdba4fea9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_trascmdint_test()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  V_BC RECORD;
  V_RP RECORD;
  V_NP RECORD;
  cnp numeric;
  cbc numeric;
  crp numeric;
BEGIN
  CALL PRC_AL_CHECK('tarifeman1', 0);

  DELETE FROM TMP_TRASCMDINT;
  DELETE FROM TMP_TRASNP;
  DELETE FROM TMP_TRASBC;
  DELETE FROM TMP_TRASRP;

  INSERT INTO TMP_TRASNP(CODCOMANDA1, PRODUS, SERIEPRODUS, IOARTPRODUS, CANTPRODUS, PRETPRODUS, VALPRODUS, COD)
  SELECT C1.CODCOMANDA1, O.DENUMIRE, SER.SERIE, IO.DEN_IOART, SUM(NSE.CANTNIR), NS.PRET, SUM(NSE.CANTNIR * NS.PRET),
         ROW_NUMBER() OVER (PARTITION BY C1.CODCOMANDA1 ORDER BY C.DATADOC)
  FROM COMANDA1 C1
      INNER JOIN COMANDA  C   ON  C1.CODCOMANDA = C.CODCOMANDA
      INNER JOIN INTRARI1 I1  ON  I1.CODCMDINT1 = C1.CODCOMANDA1
      INNER JOIN INTRARI  I   ON  I1.CODINTR = I.CODINTR
      INNER JOIN NIR          ON  I.CODINTR = NIR.CODINTR
      INNER JOIN NIRSTOC  NS  ON  NS.CODNIR = NIR.CODNIR AND  I1.CODINTR1 = NS.CODINTR1
      INNER JOIN NARTOBJ  O   ON  I1.CODOBIECT = O.CODOBIECT
      INNER JOIN IOART    IO  ON  NS.CODIOART = IO.CODIOART
      LEFT  JOIN NIRSER   NSE ON  NSE.CODNIRSTOC = NS.CODNIRSTOC
      LEFT  JOIN NSERII   SER ON  SER.CODSERIE = NSE.CODSERIE
  WHERE
     I.OPERAT = 1 AND  I.ANULAT = 0 AND  C.ANULAT = 0 AND  C.OPERAT = 1 AND  C.TIPDOC = 53 AND C.DATADOC BETWEEN TO_DATE('01.03.2019', 'DD.MM.YYYY') AND TO_DATE('01.03.2019', 'DD.MM.YYYY')
  GROUP BY
    C1.CODCOMANDA1, O.DENUMIRE, SER.SERIE, IO.DEN_IOART, NS.PRET, C.DATADOC;

  INSERT INTO TMP_TRASBC(CODCOMANDA1, MATERIAL, SERIEMATERIAL, IOARTMATERIAL, CANTMATERIAL, PRETMATERIAL, VALMATERIAL, COD)
  SELECT C1.CODCOMANDA1, O.DENUMIRE, SER.SERIE, IO.DEN_IOART, SUM(L1.CANT), NS.PRET, SUM(L1.CANT * NS.PRET),
         ROW_NUMBER() OVER (PARTITION BY C1.CODCOMANDA1 ORDER BY C.DATADOC)
  FROM COMANDA1 C1
      INNER JOIN COMANDA C   ON  C.CODCOMANDA = C1.CODCOMANDA
      INNER JOIN IESIRI1 I1  ON  I1.CODCMDINT1 = C1.CODCOMANDA1
      INNER JOIN IESIRI  I   ON  I1.CODIES = I.CODIES
      INNER JOIN LIVR    L   ON  L.CODIES = I.CODIES
      INNER JOIN LIVR1   L1  ON  L.CODLIVR = L1.CODLIVR AND  L1.CODIES1 = I1.CODIES1
      INNER JOIN NIRSTOC NS  ON  NS.CODNIRSTOC = L1.CODNIRSTOC
      INNER JOIN IOART   IO  ON  IO.CODIOART = NS.CODIOART
      INNER JOIN NARTOBJ O   ON  O.CODOBIECT = I1.CODOBIECT
      LEFT  JOIN NIRSER  NSE ON  NSE.CODNIRSER = L1.CODNIRSER
      LEFT  JOIN NSERII  SER ON  SER.CODSERIE = NSE.CODSERIE
  WHERE
     I.OPERAT = 1 AND  I.ANULAT = 0 AND  C.ANULAT = 0 AND  C.OPERAT = 1 AND  C.TIPDOC = 53 AND C.DATADOC BETWEEN TO_DATE('01.03.2019', 'DD.MM.YYYY') AND TO_DATE('01.03.2019', 'DD.MM.YYYY')
  GROUP BY
    C1.CODCOMANDA1, O.DENUMIRE, SER.SERIE, IO.DEN_IOART, NS.PRET, C.DATADOC;

  INSERT INTO TMP_TRASRP(CODCOMANDA1, OPERATIE, NROP, VALOP, COD)
  SELECT C1.CODCOMANDA1, O.DENUMIRE, SUM(R2.REALIZAT), SUM(T1.TARIF * R2.REALIZAT * R2.TU / 60), ROW_NUMBER() OVER (PARTITION BY C1.CODCOMANDA1 ORDER BY C.DATADOC)
  FROM COMANDA1 C1
      INNER JOIN COMANDA     C   ON  C.CODCOMANDA = C1.CODCOMANDA
      INNER JOIN CMDPRODMAN  MAN ON  MAN.CODCOMANDA1 = C1.CODCOMANDA1
      INNER JOIN MANPRODLINK L   ON  MAN.CODCMDPRODMAN = L.CODCMDPRODMAN
      INNER JOIN RAPORTP2    R2  ON  R2.CODRAPORTP2 = L.CODRAPORTP2
      INNER JOIN RAPORTP1    R1  ON  R2.CODRAPORTP1 = R1.CODRAPORTP1
      INNER JOIN RAPORTP     R   ON  R1.CODRAPORTP = R.CODRAPORTP
      INNER JOIN NOPER       O   ON  O.CODOP = R2.CODOP
      INNER JOIN TARIFEMAN1  T1  ON  T1.CODTARIF = R2.CODTARIF AND (R.AN * 12 + R.LUNA) BETWEEN T1.ALSTART AND T1.ALSTOP
  WHERE
     C.ANULAT = 0 AND  C.OPERAT = 1 AND  C.TIPDOC = 53 AND C.DATADOC BETWEEN TO_DATE('01.03.2019', 'DD.MM.YYYY') AND TO_DATE('01.03.2019', 'DD.MM.YYYY')
  GROUP BY
    C1.CODCOMANDA1, O.DENUMIRE, C.DATADOC;

  FOR V_REC IN
  (
    SELECT C1.CODCOMANDA1
    FROM COMANDA1 C1
    INNER JOIN COMANDA C ON  C1.CODCOMANDA = C.CODCOMANDA
    WHERE
      C.DATADOC BETWEEN TO_DATE('01.03.2019', 'DD.MM.YYYY') AND TO_DATE('01.03.2019', 'DD.MM.YYYY') AND  C.TIPDOC = 53 AND  C.OPERAT = 1 AND  C.ANULAT = 0
  )
  LOOP
    SELECT COUNT(*) INTO CNP FROM TMP_TRASNP WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;
    SELECT COUNT(*) INTO CBC FROM TMP_TRASBC WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;
    SELECT COUNT(*) INTO CRP FROM TMP_TRASRP WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;

    IF  cnp &gt;= cbc and  cnp &gt;= crp THEN
      INSERT INTO TMP_TRASCMDINT(COD, CODCOMANDA1, PRODUS, SERIEPRODUS, IOARTPRODUS, CANTPRODUS, PRETPRODUS, VALPRODUS)
      SELECT COD, CODCOMANDA1, PRODUS, SERIEPRODUS, IOARTPRODUS, CANTPRODUS, PRETPRODUS, VALPRODUS
      FROM TMP_TRASNP
      WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;

      FOR V_BC IN (SELECT CODCOMANDA1, MATERIAL, SERIEMATERIAL, IOARTMATERIAL, CANTMATERIAL, PRETMATERIAL, VALMATERIAL, COD
                   FROM TMP_TRASBC
                   WHERE CODCOMANDA1 = V_REC.CODCOMANDA1
                  )
      LOOP
        UPDATE TMP_TRASCMDINT
        SET
          MATERIAL = V_BC.MATERIAL,
          SERIEMATERIAL = V_BC.SERIEMATERIAL,
          IOARTMATERIAL = V_BC.IOARTMATERIAL,
          CANTMATERIAL = V_BC.CANTMATERIAL,
          PRETMATERIAL = V_BC.PRETMATERIAL,
          VALMATERIAL = V_BC.VALMATERIAL
        WHERE
         CODCOMANDA1 = V_BC.CODCOMANDA1 AND  COD = V_BC.COD
        ;
      END LOOP;

      FOR V_RP IN (SELECT CODCOMANDA1, OPERATIE, NROP, VALOP, COD  FROM TMP_TRASRP WHERE CODCOMANDA1 = V_REC.CODCOMANDA1) LOOP
        UPDATE TMP_TRASCMDINT
        SET
        OPERATIE = V_RP.OPERATIE,
        NROP = V_RP.NROP,
        VALOP = V_RP.VALOP
        WHERE
         CODCOMANDA1 = V_RP.CODCOMANDA1 AND  COD = V_RP.COD
        ;
      END LOOP;
    END IF;

    IF  cbc &gt;= cnp and  cbc &gt;= crp THEN
      INSERT INTO TMP_TRASCMDINT(CODCOMANDA1, MATERIAL, SERIEMATERIAL, IOARTMATERIAL, CANTMATERIAL, PRETMATERIAL, VALMATERIAL, COD)
      SELECT CODCOMANDA1, MATERIAL, SERIEMATERIAL, IOARTMATERIAL, CANTMATERIAL, PRETMATERIAL, VALMATERIAL, COD
      FROM TMP_TRASBC
      WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;

      FOR V_NP IN (SELECT CODCOMANDA1, PRODUS, SERIEPRODUS, IOARTPRODUS, CANTPRODUS, PRETPRODUS, VALPRODUS, COD
                   FROM TMP_TRASNP
                   WHERE CODCOMANDA1 = V_REC.CODCOMANDA1
                  )
      LOOP
        UPDATE TMP_TRASCMDINT
        SET
        PRODUS = V_NP.PRODUS,
        SERIEPRODUS = V_NP.SERIEPRODUS,
        IOARTPRODUS = V_NP.IOARTPRODUS,
        CANTPRODUS = V_NP.CANTPRODUS,
        PRETPRODUS = V_NP.PRETPRODUS,
        VALPRODUS = V_NP.VALPRODUS
        WHERE
         CODCOMANDA1 = V_NP.CODCOMANDA1 AND  COD = V_NP.COD
        ;
      END LOOP;

      FOR V_RP IN (SELECT CODCOMANDA1, OPERATIE, NROP, VALOP, COD FROM TMP_TRASRP WHERE CODCOMANDA1 = V_REC.CODCOMANDA1) LOOP
        UPDATE TMP_TRASCMDINT
        SET
        OPERATIE = V_RP.OPERATIE,
        NROP = V_RP.NROP,
        VALOP = V_RP.VALOP
        WHERE
         CODCOMANDA1 = V_RP.CODCOMANDA1 AND  COD = V_RP.COD
        ;
      END LOOP;
    END IF;

    IF  crp &gt;= cnp and  crp &gt;= cbc THEN
      INSERT INTO TMP_TRASCMDINT(CODCOMANDA1, OPERATIE, NROP, VALOP, COD)
      SELECT CODCOMANDA1, OPERATIE, NROP, VALOP, COD
      FROM TMP_TRASrp
      WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;

      FOR V_BC IN (SELECT CODCOMANDA1, MATERIAL, SERIEMATERIAL, IOARTMATERIAL, CANTMATERIAL, PRETMATERIAL, VALMATERIAL, COD
                   FROM TMP_TRASBC
                   WHERE CODCOMANDA1 = V_REC.CODCOMANDA1
                  )
      LOOP
        UPDATE TMP_TRASCMDINT
        SET
        MATERIAL = V_BC.MATERIAL,
        SERIEMATERIAL = V_BC.SERIEMATERIAL,
        IOARTMATERIAL = V_BC.IOARTMATERIAL,
        CANTMATERIAL = V_BC.CANTMATERIAL,
        PRETMATERIAL = V_BC.PRETMATERIAL,
        VALMATERIAL = V_BC.VALMATERIAL
        WHERE
         CODCOMANDA1 = V_BC.CODCOMANDA1 AND  COD = V_BC.COD
        ;
      END LOOP;

      FOR V_NP IN (SELECT CODCOMANDA1, PRODUS, SERIEPRODUS, IOARTPRODUS, CANTPRODUS, PRETPRODUS, VALPRODUS, COD
                   FROM TMP_TRASNP
                   WHERE CODCOMANDA1 = V_REC.CODCOMANDA1
                  )
      LOOP
        UPDATE TMP_TRASCMDINT
        SET
        PRODUS = V_NP.PRODUS,
        SERIEPRODUS = V_NP.SERIEPRODUS,
        IOARTPRODUS = V_NP.IOARTPRODUS,
        CANTPRODUS = V_NP.CANTPRODUS,
        PRETPRODUS = V_NP.PRETPRODUS,
        VALPRODUS = V_NP.VALPRODUS
        WHERE
         CODCOMANDA1 = V_NP.CODCOMANDA1 AND  COD = V_NP.COD
        ;
      END LOOP;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_traseelivrare_insertrec</obj_name>
  <obj_hashval>2a4714d39d3fa09b442f2c7f1ee68e92</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_traseelivrare_insertrec(tmpname character varying, vline record, amasa numeric, avolum numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar := '';
BEGIN
  --Adina 16.10.2020
  sInsert :=
  'INSERT INTO ' || tmpName || '(
     Traseu, PozTraseu, Client, SerieDoc, NrDoc, DataDoc, Sofer, MijlTransp, NrTransp,
     MasaDoc, VolumDoc, MasaTraseu, VolumTraseu, MasaUtila, VolumUtil,
     CodTraseu, LungTransp, LatTransp, InaltTransp)
  VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19 )';

  EXECUTE sInsert
  USING
    vLine.Traseu   , vLine.PozTraseu , vLine.Client   , vLine.SerieDoc   , vLine.NrDoc    , vLine.DataDoc, vLine.Sofer, vLine.MijlTransp, vLine.NrInreg,
    vLine.MasaDoc  , vLine.VolumDoc  , aMasa, aVolum  , vLine.MasaUtila  , vLine.VolumUtil,
    vLine.CodTraseu, vLine.LungTransp, vLine.LatTransp, vLine.InaltTransp;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_traseelivrare_processlist</obj_name>
  <obj_hashval>360711f72f5dc633e05c0322b9c91748</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_traseelivrare_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vLine   RECORD;
  lMasa   numeric;
  lVolum   numeric;
BEGIN
  --Adina 16.10.2020
  FOR vLine IN  ( SELECT
                    TL.DenTraseu Traseu, TTC.PozTraseu,
                    (CASE C.TipDoc WHEN 18 THEN P.Den_Part WHEN 43 THEN G.Den_Gest WHEN 44 THEN S.Den_Subunit END) Client,
                    C.SeriaDoc SerieDoc, C.NrDoc, C.DataDoc,
                    NumePrenume(PERS.Prenume, PERS.Nume) Sofer, A.Den_Articol MijlTransp, PA.NrInreg,
                    SUM(TTC.Masa) MasaDoc, SUM(TTC.Volum) VolumDoc, 0 MasaTraseu, 0 VolumTraseu, PA.MasaU MasaUtila, PA.VolumU VolumUtil,
                    TL.CodTraseuLivr CodTraseu, PA.Lung LungTransp, PA.Lat LatTransp, PA.Inalt InaltTransp
                  FROM   TMP_TraseuLivr_Comenzi TTC
                        LEFT JOIN TraseuLivr TL ON TL.CodTraseuLivr = TTC.CodTraseu
                        LEFT JOIN Comanda C     ON C.CodComanda     = TTC.CodComanda
                        LEFT JOIN NPart P       ON P.CodPart        = TTC.CodClient
                        LEFT JOIN NSubunit S    ON S.CodSubunit     = C.Subunitatea
                        LEFT JOIN NGest G       ON G.CodGest        = C.CodGest
                        LEFT JOIN NParcAut PA   ON PA.CodNParcAut   = TTC.CodMijlTransp
                        LEFT JOIN NArtObj AO    ON AO.CodObiect     = PA.CodArt
                        LEFT JOIN NArt A        ON A.CodArticol     = AO.CodArticol
                        LEFT JOIN NPers PERS    ON PERS.CodPers     = PA.Sofer
                  GROUP BY
                    TL.DenTraseu, TTC.PozTraseu,
                    (CASE C.TipDoc WHEN 18 THEN P.Den_Part WHEN 43 THEN G.Den_Gest WHEN 44 THEN S.Den_Subunit END), C.SeriaDoc, C.NrDoc, C.DataDoc,
                    PERS.Prenume, PERS.Nume, A.Den_Articol, PA.NrInreg, PA.MasaU, PA.VolumU, TL.CodTraseuLivr, PA.Lung, PA.Lat, PA.Inalt
                )
  LOOP
    SELECT SUM(COALESCE(Masa, 0)), SUM(COALESCE(Volum, 0))
    INTO lMasa, lVolum
    FROM TMP_TraseuLivr_Comenzi
    WHERE CodTraseu = vLine.CodTraseu;

    PERFORM pkg_list_base_traseelivrare_InsertRec(tmpName, vLine, lMasa, lVolum);
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_traseelivrare_setparams</obj_name>
  <obj_hashval>f1a08f40c0940129dd4afbc0aff71b9d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_traseelivrare_setparams()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  null;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_trasfact_processlist</obj_name>
  <obj_hashval>5cf121eefa51a6860fa4ff21c5e7b973</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_trasfact_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := 'iesiri i, nagenda ag, traseulivr tl';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 16.10.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_TRASFACT.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '
   (DENPERS,
    NRINREG,
    DENTRASEU,
    PREFIXDOC,
    NRDOC,
    DATADOC,
    DEN_PART,
    VALDOC,
    SERIEDOC,
    SIMBOLMONEDA,
    ORA,
    DENTRASEUP ' || gUserFields || ')
    SELECT
      df.DEN_PERS,
      i.nrtransp,
      d1.dentraseu,
      df.PREFIXDOC,
      df.NRDOC,
      i.DATADOC,
      df.Den_Part,
      df.ValDoc,
      df.seriedoc,
      df.simbolmoneda,
      df.ora,
      TL.DENTRASEU ' || gUserAlias || '
    FROM tmp_distrib_fact df
         inner join iesiri i              on df.codies             = i.codies
         left  join tmp_distrib1 d1       on i.agent               = d1.codpers
         inner join tmp_manevra_liste man on d1.codtraseu::varchar = man.valoare and man.filtru = ''CODTRASEU''
         left  join nagenda ag            on i.codlocatie          = ag.codagenda
         left  join traseulivr TL on ag.codtraseu                  = tl.codtraseulivr' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_trasfact_setjoinuri</obj_name>
  <obj_hashval>175f14d715c3596df47f4267ec92290a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_trasfact_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 16.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_TRASFACT.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_trasfact_setparams</obj_name>
  <obj_hashval>fa1e7ef8a19ae1c7d2582abd0f66ab4b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_trasfact_setparams(pcoddistrib numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 16.10.2020
  perform set_config('PKG_LIST_BASE_TRASFACT.vCodDistrib',(pCodDistrib)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_trasfactinc_setjoinuri</obj_name>
  <obj_hashval>0e9813285dd632f3893271a2c4db884d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_trasfactinc_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 16.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_TRASFACTINC.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_trasfactinc_setparams</obj_name>
  <obj_hashval>3717ae2672f24f59b17adf7428c92c00</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_trasfactinc_setparams(pcoddistrib numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 16.10.2020
  perform set_config('PKG_LIST_BASE_TRASFACTINC.vCodDistrib',(pCodDistrib)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_trasinc_processlist</obj_name>
  <obj_hashval>97d5bf8b55126c2dc99acf70e32a2a22</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_trasinc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := 'trezor1 t1, trezor t, iesiri i, nagenda ag, traseulivr tl';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 16.10.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_TRASINC.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '
   (DENPERS,
    NRINREG,
    DENTRASEU,
    PREFIXDOC,
    NRDOC,
    DATADOC,
    DEN_PART,
    VALDOC,
    SERIEDOC,
    SIMBOLMONEDA,
    ORA,
    PREFIXDOCS,
    NRDOCS,
    DATADOCS,
    VALDOCS,
    DENTRASEUS
   ' || gUserFields || ')
    SELECT
      di.DEN_PERS,
      d1.nrinreg,
      d1.dentraseu,
      di.PREFIXDOC,
      di.NRDOC,
      di.DATADOC,
      di.Den_Part,
      di.ValDoc,
      di.seriedoc,
      di.simbolmoneda,
      di.ora,
      i.prefixdoc,
      i.nrdoc,
      i.datadoc,
      i.valdoc,
      tl.dentraseu
       ' || gUserAlias || '
    FROM tmp_distrib_inc di
         inner join trezor1 t1            on di.codtrezor1          = t1.codtrezor1
        inner join trezor t               on t1.codtrezor           = t.codtrezor
         left  join tmp_distrib1 d1       on di.CodPers             = d1.codpers
         inner join tmp_manevra_liste man on d1.codtraseu::varchar  = man.valoare   and man.filtru = ''CODTRASEU''
         inner join general gt            on gt.coddoc              = t1.codtrezor1 and gt.tipdoc  = t.tipdoc
         inner join obligpif ostingator   on gt.codgeneral          = ostingator.codgeneral
         inner join stingere st           on ostingator.codobligpif = st.codstingatorpif
         inner join obligpif ostins       on st.codstinspif         = ostins.codobligpif
         inner join general gs            on gs.codgeneral          = ostins.codgeneral
         inner join iesiri i              on i.codies               = gs.coddoc and i.tipdoc = gs.tipdoc
         inner join nagenda ag            on i.codlocatie           = ag.codagenda
         inner join traseulivr tl         on tl.codtraseulivr       = ag.codtraseu
         ' || gSuplJoins;

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_traspart_getstatuspart</obj_name>
  <obj_hashval>efe811bcba131b31d44edbb0cbec008a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_traspart_getstatuspart(vcoddistrib2 numeric, van numeric, vluna numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCount numeric;
BEGIN
  --Adina 16.10.2020
  SELECT Count(*) INTO aCount FROM tmp_distrib3 WHERE coddistrib2 = vCodDistrib2;

  IF  aCount = 0 THEN
    RETURN 'SOLD 0';
  ELSE
    SELECT Count(*) INTO aCount FROM tmp_distrib3
    WHERE coddistrib2 = vCodDistrib2 and  COALESCE(ZILESCADENTE, 0) &gt; COALESCE(fnc_GetValConstanta('ZileDepasireAccept', vAn, vLuna), '0')::numeric;

    IF  aCount &gt; 0 THEN
      RETURN 'BLOCAT';
    ELSE
      RETURN 'DEBITOR';
    END IF;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_traspart_processlist</obj_name>
  <obj_hashval>657d1abdf00052fd464f291e2091eee1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_traspart_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := 'tmp_distrib d';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 16.10.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_TRASPART.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '
   (DENPERS,
    NRINREG,
    DENTRASEU,
    SOLD,
    POZTRASEU,
    DEN_PART,
    OBS,
    ADRESA,
    DEN_JUDET,
    DEN_LOCALIT,
    DOC,
    PREFIXDOC,
    NRDOC,
    DATADOC,
    VALREAL,
    RESTREAL,
    TERMEN,
    ZILESCADENTE,
    STATUS
   ' || gUserFields || ')
    SELECT
      d1.DENPERS,
      d1.NRINREG,
      d1.DENTRASEU,
      d2.SOLD,
      d2.POZTRASEU,
      d2.DEN_PART,
      d2.OBS,
      d2.ADRESA,
      d2.DEN_JUDET,
      d2.DEN_LOCALIT,
      d3.DOC,
      d3.PrefixDoc,
      d3.NRDOC,
      d3.DATADOC,
      d3.VALREAL,
      d3.RESTREAL,
      d3.TERMEN,
      d3.ZILESCADENTE,
      PKG_LIST_BASE_TRASPART_GetStatusPart(d2.coddistrib2, d.an, d.luna)' || gUserAlias || '
    FROM tmp_distrib d
         left  JOIN tmp_distrib1 d1       ON d.Coddistrib          = d1.Coddistrib
         inner join tmp_manevra_liste man ON d1.codtraseu::varchar = man.valoare and man.filtru = ''CODTRASEU''
         left  JOIN tmp_distrib2 d2       ON d1.Coddistrib1        = d2.coddistrib1
         left  JOIN tmp_distrib3 d3       ON d2.Coddistrib2        = d3.Coddistrib2' || gSuplJoins;

  sInsert := sInsert || ' WHERE D.CodDistrib = ' || coalesce(current_setting('PKG_LIST_BASE_TRASPART.vCodDistrib', true),'');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_traspart_setparams</obj_name>
  <obj_hashval>b464ba63b2546b377f781328cc252328</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_traspart_setparams(pcoddistrib numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 16.10.2020
  perform set_config('PKG_LIST_BASE_TRASPART.vCodDistrib',(pCodDistrib)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmaecli_getvalachiz</obj_name>
  <obj_hashval>9549daab8aab2feac2aae2f2a2e8857e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmaecli_getvalachiz(acodies1 numeric, acantf numeric DEFAULT 0, aanf numeric DEFAULT 0, alunaf numeric DEFAULT 0)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aVal         numeric;
  aCant        numeric;
  vStornoAvize NUMERIC;
  vAnF         NUMERIC;
  vLunaF       NUMERIC;
BEGIN
  --Adina 19 august 2020
  vAnF          := COALESCE(current_setting('PKG_LIST_BASE_URMAECLI.vAnF'  , true)::numeric, 0)::numeric;
  vLunaF        := COALESCE(current_setting('PKG_LIST_BASE_URMAECLI.vLunaF', true)::numeric, 0)::numeric;

  SELECT COALESCE(sum(l1.cant * (  ns.pret - ns.adaos) ), 0), COALESCE(sum(l1.cant), 0)
  INTO aVal, aCant
  FROM livr1 l1
    INNER JOIN livr    l  ON  l.codlivr     = l1.codlivr AND  l.tiplivr = 20
    INNER JOIN nirstoc ns ON  l1.codnirstoc = ns.codnirstoc
  WHERE l1.codies1 = aCodIes1;

  IF  aCantF &lt;&gt; 0 THEN
    IF  vAnF &lt;&gt; aAnF AND  vLunaF &lt;&gt; aLunaF THEN
      perform set_config('PKG_LIST_BASE_URMAECLI.vAnF'        ,(aAnF)::varchar  ,false);
      perform set_config('PKG_LIST_BASE_URMAECLI.vLunaF'      ,(aLunaF)::varchar,false);
      perform set_config('PKG_LIST_BASE_URMAECLI.vStornoAvize',(COALESCE((fnc_GetValConstanta('StornoAvize', vAnF, vLunaF)), '0'))::varchar,false);
    END IF;

    vStornoAvize := COALESCE(current_setting('PKG_LIST_BASE_URMAECLI.vStornoAvize', true)::numeric, 0)::numeric;

    IF  vStornoAvize = 1 THEN
      SELECT aVal + COALESCE(sum(l1.cant * (  ns.pret - ns.adaos) ), 0), aCant + COALESCE(sum(l1.cant), 0)
      INTO aVal, aCant
      FROM iesiri1 i1
        INNER JOIN livr1   l1 ON  l1.codies1    = i1.CodIes1
        INNER JOIN livr    l  ON  l.codlivr     = l1.codlivr AND  l.tiplivr = 20
        INNER JOIN nirstoc ns ON  l1.codnirstoc = ns.codnirstoc
      WHERE i1.codies1storno = aCodIes1;
    END IF;

    IF  aCant = 0 THEN
      aVal := 0;
    ELSE
      aVal := aVal * aCantF / aCant;
    END IF;
  END IF;

  RETURN  aVal;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmaecli_setjoinuri</obj_name>
  <obj_hashval>d5e4233672499c3a2f2eb1be5e108e52</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmaecli_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 19 august 2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_URMAECLI.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmaefurn_setjoinuri</obj_name>
  <obj_hashval>8cc0a6cc82db54fc6d621ae611f501c2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmaefurn_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 19 august 2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_URMAEFURN.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmarire_predari_processlist</obj_name>
  <obj_hashval>8548af8200cb46cc38efc3dea6af1293</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmarire_predari_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sSelect     varchar;
  sDataS      varchar := current_setting('pkg_list_alegperioada.gDataS', TRUE);
  sDataF      varchar := current_setting('pkg_list_alegperioada.gDataF', TRUE);
  gSuplCols   varchar:= 'comanda c, comanda1 c1, intrari i, intrari1 i1, nartobj o, programf pf, programf1 pf1';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 14.09.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_URMARIRE_PREDARI.gSuplCols', gSuplCols, FALSE);

  sInsert := 'INSERT INTO ' || TMPNAME || '(
         NAV_CodDoc,
         NAV_TipDoc,
         Doc,
         CmdInt,
         Produs,
         FB,
         Cant,
         Ordine,
         DataDoc,
         restpr,
         restnpr,
         rest' || gUserFields || ')';
  sSelect := '
        select
          c.codcomanda NAV_CodDoc,
          c.tipdoc NAV_TipDoc,
          c.prefixdoc||'' ''||c.nrdoc||''/''||to_char(c.datadoc,''dd.mm.yyyy'') doc,
          c.prefixdoc||'' ''||c.nrdoc||''/''||to_char(c.datadoc,''dd.mm.yyyy'') cmdint,
          o.denumire produs,
          null PF,
          c1.cantacceptat cant,
          0 ordine,
          c.datadoc,
          0 restpr,
          c1.cantacceptat restnpr,
          c1.cantacceptat rest
          ' || gUserAlias || '
        from comanda c
             inner join comanda1  c1  on c.codcomanda   = c1.codcomanda
             inner join nartobj   o   on o.codobiect    = c1.codobiect
             left  join intrari   i   on i.codintr      = o.codobiect - o.codobiect
             left  join intrari1  i1  on i1.codintr1    = o.codobiect - o.codobiect
             left  join programf  pf  on pf.codprogramf = o.codobiect - o.codobiect
             left  join programf1 pf1 on pf.codprogramf = o.codobiect - o.codobiect
             ' || gSuplJoins || '
        where c.anulat = 0 and c.operat = 1 and c.tipdoc = 53 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C', 'SUBUNITATEA', 'AND',NULL),'') || '
              and c.datadoc BETWEEN TO_DATE(''' || sDataS || ''',''dd.mm.yyyy'') AND TO_DATE(''' || sDataF || ''',''dd.mm.yyyy'')
        union all
        select
          pf.codprogramf NAV_CodDoc,
          68 NAV_TipDoc,
          COALESCE(pf.prefixdoc,''PF'')||'' ''||pf.nrdoc||''/''||to_char(pf.datainreg,''dd.mm.yyyy'') doc,
          c.prefixdoc||'' ''||c.nrdoc||''/''||to_char(c.datadoc,''dd.mm.yyyy'') cmdint,
          o.denumire produs,
          pf.prefixdoc||'' ''||pf.nrdoc||''/''||to_char(pf.datainreg,''dd.mm.yyyy'') pf,
          pf1.cantprogramat cant,
          1 ordine,
          pf.datainreg datadoc,
          pf1.cantprogramat restpr,
          - pf1.cantprogramat restnpr,
          0 rest
          ' || gUserAlias || '
        from programf pf
             inner join programf1 pf1 on pf1.codprogramf = pf.codprogramf
             inner join comanda1  c1  on pf1.codcomanda1 = c1.codcomanda1
             inner join comanda   c   on c.codcomanda    = c1.codcomanda
             inner join nartobj   o   on o.codobiect     = c1.codobiect
             left  join intrari   i   on i.codintr       = o.codobiect - o.codobiect
             left  join intrari1  i1  on i1.codintr1     = o.codobiect - o.codobiect
             ' || gSuplJoins || '
        where c.anulat = 0 and c.operat = 1 and c.tipdoc = 53 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C', 'SUBUNITATEA', 'AND',NULL),'') || '
              and c.datadoc BETWEEN TO_DATE(''' || sDataS || ''',''dd.mm.yyyy'') AND TO_DATE(''' || sDataF || ''',''dd.mm.yyyy'')
        union all
        select
          i.codintr NAV_CodDoc,
          i.tipdoc NAV_TipDoc,
          i.prefixdoc||'' ''||i.nrdoc||''/''||to_char(i.datadoc,''dd.mm.yyyy'') doc,
          c.prefixdoc||'' ''||c.nrdoc||''/''||to_char(c.datadoc,''dd.mm.yyyy'') cmdint,
          o.denumire produs,
          null PF,
          i1.cant,
          3 ordine,
          i.datadoc,
          0 restpr,
          -i1.cant restnpr,
          -i1.cant rest
          ' || gUserAlias || '
        from intrari i
             inner join intrari1     i1   on i1.codintr         = i.codintr
             inner join comanda1     c1   on i1.codcmdint1      = c1.codcomanda1 and i1.codobiect = c1.codobiect
             inner join cmdprodmat   prod on prod.tip           = 0 and prod.codcomanda1 = c1.codcomanda1
             inner join comanda      c    on c.codcomanda       = c1.codcomanda
             inner join nartobj      o    on c1.codobiect       = o.codobiect
             left  join programf     pf   on pf.codprogramf     = o.codobiect - o.codobiect
             left  join programf1    pf1  on pf.codprogramf     = o.codobiect - o.codobiect
             left  join intrprodlink l    on prod.codcmdprodmat = l.codliniecomanda and l.codintr1 = i1.codintr1
             ' || gSuplJoins || '
        where c.anulat = 0 and c.operat = 1 and c.tipdoc = 53 and COALESCE(l.codprogramf1,0) = 0 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C', 'SUBUNITATEA', 'AND',NULL),'') || '
              and c.datadoc BETWEEN TO_DATE(''' || sDataS || ''',''dd.mm.yyyy'') AND TO_DATE(''' || sDataF || ''',''dd.mm.yyyy'')
              and i.anulat = 0 and i.operat = 1 and i.tipdoc = 7
        union all
        select
          i.codintr NAV_CodDoc,
          i.tipdoc NAV_TipDoc,
          i.prefixdoc||'' ''||i.nrdoc||''/''||to_char(i.datadoc,''dd.mm.yyyy'') doc,
          c.prefixdoc||'' ''||c.nrdoc||''/''||to_char(c.datadoc,''dd.mm.yyyy'') cmdint,
          o.denumire produs,
          pf.prefixdoc||'' ''||pf.nrdoc||''/''||to_char(pf.datainreg,''dd.mm.yyyy'') PF,
          i1.cant,
          2 ordine,
          i.datadoc,
          -i1.cant restpr,
          0 restnpr,
          -i1.cant rest
          ' || gUserAlias || '
        from intrari i
             inner join intrari1     i1   on i1.codintr         = i.codintr
             inner join comanda1     c1   on i1.codcmdint1      = c1.codcomanda1 and i1.codobiect = c1.codobiect
             inner join comanda      c    on c.codcomanda       = c1.codcomanda
             inner join cmdprodmat   prod on prod.tip           = 0 and prod.codcomanda1 = c1.codcomanda1
             inner join intrprodlink l    on prod.codcmdprodmat = l.codliniecomanda and l.codintr1 = i1.codintr1
             inner join programf1    pf1  on pf1.codprogramf1   = l.codprogramf1
             inner join programf     pf   on pf.codprogramf     = pf1.codprogramf
             inner join nartobj      o    on o.codobiect        = c1.codobiect
             ' || gSuplJoins || '
        where c.anulat = 0 and c.operat = 1 and c.tipdoc = 53 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C', 'SUBUNITATEA', 'AND',NULL),'') || '
              and c.datadoc BETWEEN TO_DATE(''' || sDataS || ''',''dd.mm.yyyy'') AND TO_DATE(''' || sDataF || ''',''dd.mm.yyyy'')
              and i.anulat = 0 and i.operat = 1 and i.tipdoc = 7';
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmarireplati_setjoinuri</obj_name>
  <obj_hashval>52b14c710e3591785217cecce68a342d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmarireplati_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 08 septembrie 2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_URMARIREPLATI.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmartpefurn_get_cant_umprinc</obj_name>
  <obj_hashval>05129463b3cb266f9103dc7557525fc1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmartpefurn_get_cant_umprinc(cant numeric, codumsec numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  iResult numeric;
BEGIN
  --Adina 07 Septembrie 2020
  SELECT cant * COALESCE(num1.paritate, 1)
  INTO iResult
  FROM num1
  WHERE num1.codum1 = CODUMSEC;

  RETURN  COALESCE(iResult, CANT);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmartpefurn_setdatacodobiect</obj_name>
  <obj_hashval>95e3e98a0ddb8508ab018cc5eda7e223</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmartpefurn_setdatacodobiect()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  bToateArt boolean;
  vCodPart  NUMERIC;
  g_DataIni  varchar := '';
  g_DataFin  varchar := '';
BEGIN
  --Adina 07 septembrie 2020
  bToateArt := current_setting('PKG_LIST_BASE_URMARTPEFURN.g_bToateArt', true)::boolean;
  vCodPart  := current_setting('PKG_LIST_BASE_URMARTPEFURN.g_CodPart',   true)::NUMERIC;
  g_DataIni := current_setting('PKG_LIST_BASE_URMARTPEFURN.g_DataIni',   true);
  g_DataFin := current_setting('PKG_LIST_BASE_URMARTPEFURN.g_DataFin',   true);

  DELETE FROM TMP_LST_URMARTPEFURN;

  IF bToateArt THEN
    INSERT INTO TMP_LST_URMARTPEFURN(CODOBIECT, DATA)
    WITH RECURSIVE aa(dataini,nivel) AS
    (
     SELECT TO_DATE(g_DataIni,'DD.MM.YYYY')-1 dataini, 1 nivel
     UNION ALL
     SELECT aa.dataini+1,  (aa.nivel+1) as nivel FROM aa WHERE aa.nivel&lt;=(TO_DATE(g_DataFin,'DD.MM.YYYY')+1-TO_DATE(g_DataIni,'DD.MM.YYYY')+1)
    )
    SELECT  DISTINCT NS.CODOBIECT, T.DATA
    FROM (
          SELECT dataini AS DATA
                 FROM aa WHERE nivel&lt;=(TO_DATE(g_DataFin,'DD.MM.YYYY')+1-TO_DATE(g_DataIni,'DD.MM.YYYY')+1)
         ) T, NIRSTOC NS
    WHERE NS.FURN = vCodPart;
  ELSE
    INSERT INTO TMP_LST_URMARTPEFURN(CODOBIECT, DATA)
    SELECT NOBJ.CODOBIECT, T.DATA
    FROM (
          SELECT dataini AS DATA
                 FROM aa WHERE nivel&lt;=(TO_DATE(g_DataFin,'DD.MM.YYYY')+1-TO_DATE(g_DataIni,'DD.MM.YYYY')+1)
         ) T, NARTOBJ NOBJ
    WHERE NOBJ.CODOBIECT::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODOBIECT');
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmartpefurn_setjoinuri</obj_name>
  <obj_hashval>3fc9e9084af1d8c6035515246bcddf48</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmartpefurn_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 03.02.2021
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('pkg_list_base_urmartpefurn.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmartpefurn_setlistaparams</obj_name>
  <obj_hashval>21f8c7a89e4a9bc23c76bd51b40074bd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmartpefurn_setlistaparams(datafin character varying, acodpart numeric, btoateart numeric DEFAULT 1, pcodjob1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  AnTemp     numeric;
  LunaTemp   numeric;
  AnPrec     numeric;
  LunaPrec   numeric;
  g_DataIni  varchar := '';
  g_DataFin  varchar := '';
  pToateArt numeric;
BEGIN
  --Adina 30.06.2021 - modif.param.fct.pkg_list_selfisamag_setallparams din bool in numeric
  --Adina 07 septembrie 2020
  perform set_config('PKG_LIST_BASE_URMARTPEFURN.g_DataFin',DataFin,false);
  g_DataFin := current_setting('PKG_LIST_BASE_URMARTPEFURN.g_DataFin',   true);

  IF  COALESCE(pCodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_DATA_DINAMIC(pCODJOB1, to_date(current_setting('PKG_LIST_BASE_URMARTPEFURN.g_DataFin', true),'dd.mm.yyyy') );
  END IF;

  perform set_config('PKG_LIST_BASE_URMARTPEFURN.g_DataIni'  ,to_char(DATE_TRUNC('month',to_date(g_DataFin,'dd.mm.yyyy')),'dd.mm.yyyy' ),false);
  perform set_config('PKG_LIST_BASE_URMARTPEFURN.g_CodPart'  ,(aCodPart)::varchar                                                       ,false);
  perform set_config('PKG_LIST_BASE_URMARTPEFURN.g_bToateArt',(trunc(COALESCE(bToateArt,1)) = 1)::varchar                               ,false);

  g_DataIni := current_setting('PKG_LIST_BASE_URMARTPEFURN.g_DataIni',   true);
  pToateArt := CASE WHEN current_setting('PKG_LIST_BASE_URMARTPEFURN.g_bToateArt', true)::boolean THEN 1 ELSE 0 END;

  AnTemp   := EXTRACT( YEAR  FROM to_date(g_DataFin,'dd.mm.yyyy'));
  LunaTemp := EXTRACT( MONTH FROM to_date(g_DataFin,'dd.mm.yyyy'));

  PERFORM pkg_globals_SetLunaTemp(AnTemp, LunaTemp);
  SELECT newan,newluna INTO AnPrec, LunaPrec FROM pkg_globals_CALCULEAZA_LUNA_PRECEDENTA(AnTemp, LunaTemp, AnPrec, LunaPrec);
  PERFORM pkg_globals_SetLunaPRECEDENTA(AnPrec, LunaPrec);

  PERFORM pkg_list_selfisamag_setAllParams(g_DataIni, g_DataFin, g_DataFin, 1, 1, pToateArt);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmartpefurn_setparamspentrufiltru</obj_name>
  <obj_hashval>3cfe2a5a99c7a6f21dbf58e9fa743d0f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmartpefurn_setparamspentrufiltru(datafin character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  AnTemp     numeric;
  LunaTemp   numeric;
  AnPrec     numeric;
  LunaPrec   numeric;
  g_DataIni  varchar := '';
  g_DataFin  varchar := '';
BEGIN
  --Adina 30.06.2021 - modif.param.fct.pkg_list_selfisamag_setallparams din bool in numeric
  --Adina 07 septembrie 2020
  perform set_config('PKG_LIST_BASE_URMARTPEFURN.g_DataFin',DataFin,false);
  perform set_config('PKG_LIST_BASE_URMARTPEFURN.g_DataIni',to_char(DATE_TRUNC('month',to_date(current_setting('PKG_LIST_BASE_URMARTPEFURN.g_DataFin', true),'dd.mm.yyyy')),'dd.mm.yyyy'),false);

  g_DataIni := current_setting('PKG_LIST_BASE_URMARTPEFURN.g_DataIni',   true);
  g_DataFin := current_setting('PKG_LIST_BASE_URMARTPEFURN.g_DataFin',   true);

  AnTemp    := EXTRACT( YEAR  FROM to_date(g_DataFin,'dd.mm.yyyy'));
  LunaTemp := EXTRACT( MONTH FROM to_date(g_DataFin,'dd.mm.yyyy'));

  PERFORM pkg_globals_SetLunaTemp(AnTemp, LunaTemp);
  SELECT newan,newluna INTO AnPrec, LunaPrec FROM pkg_globals_CALCULEAZA_LUNA_PRECEDENTA(AnTemp, LunaTemp, AnPrec, LunaPrec);
  PERFORM pkg_globals_SetLunaPRECEDENTA(AnPrec, LunaPrec);
  PERFORM pkg_list_selfisamag_setAllParams(g_DataIni, dataFin, datafin, 1, 1, 1);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmbuget_setjoinuri</obj_name>
  <obj_hashval>ebacb0d898e9c4b008712ed8976d6da9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmbuget_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 22.09.2020
  PERFORM pkg_list_struct_SetTableSpec (current_setting ('PKG_LIST_BASE_URMBUGET.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmbuget_setparams</obj_name>
  <obj_hashval>5643fff3620a757b9cc318c76d1d4124</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmbuget_setparams(afiltrunrinv character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 22.09.2020
  perform set_config ('PKG_LIST_BASE_URMBUGET.pFiltru',aFiltruNrInv,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmcomcli_setjoinuri</obj_name>
  <obj_hashval>5db960f9280245e05f70cc204684d9b6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmcomcli_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 01.09.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_URMCOMCLI.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmcomenzi_setjoinuri</obj_name>
  <obj_hashval>76f02d6ce65775f8a6cad0ebb984a2cf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmcomenzi_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 01.09.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_URMCOMENZI.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmcomfactsa_setjoinuri</obj_name>
  <obj_hashval>64aa3813c17ff5c5d570e7c3148a6eb2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmcomfactsa_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 16.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_URMCOMFACTSA.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmcomfurn_setjoinuri</obj_name>
  <obj_hashval>d219168ef6ceab879c2ff1887b7d1e6c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmcomfurn_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 01.09.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_URMCOMFURN.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmcontr_processlist</obj_name>
  <obj_hashval>3e4b947d67795ea2009fc054c2e9e296</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmcontr_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sInsIes     varchar;
  sInsIntr    varchar;
  sInsCom     varchar;
  sSelect     varchar;
  sSelectX    varchar;
  sData1      varchar := 'to_date(''' || coalesce(current_setting('PKG_LIST_ALEGPERIOADA.gDataS', TRUE),'') || ''',''dd.mm.yyyy'')';
  sData2      varchar := 'to_date(''' || coalesce(current_setting('PKG_LIST_ALEGPERIOADA.gDataF', TRUE),'') || ''',''dd.mm.yyyy'')';
  gSuplCols   varchar := 'contract c, contract1 c1, intrari intr, intrari1 intr1, iesiri ies, iesiri1 ies1, comanda com, comanda1 com1, npart p, nartobj o, num1 um, ncont ncont, nclasep clsp, npers agent';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 12.06.2024 - fixat 62326
  --Florin 05.01.2022 - sinc. Oracle (04.01.2022)
  --Florin 20.05.2021 - sincron Oracle
  --Adina 17.05.2021 - sinc.Oracle din 14.05.2021
  --Adina 14.05.2021 - sinc.Oracle din 13.05.2021
  --Adina 26.04.2021 - sinc.Oracle din 24.04.2021
  --Florin 11.09.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = O.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = O.CODOBIECT',NULL);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_URMCONTR.gSuplCols', gSuplCols, FALSE);

  DELETE FROM TMP_LST_URMCONTR;
  sInsIes := '
      INSERT INTO TMP_LST_URMCONTR (
        codcontract, codcontract1,
        tipdoc, coddoc, coddoc1, idxdoc,
        intrare,
        prefixdoc, nrdoc, datadoc,
        cant,
        pretorig, pu, tva, coefdiscmaj,
        codpart, codcont,
        codcomanda1, cantsold, cantdoc
      )
      SELECT
        c.codcontract, c1.codcontract1,
        ies.tipdoc, ies.codies, ies1.codies1, ies1.indexlocal,
        0,
        ies.prefixdoc, ies.nrdoc, ies.datadoc,
        ies1.cant, ies1.pretorig, ies1.pu, ies1.tva, Coalesce(ies1.coefdiscmaj,1),
        ies.partener, Coalesce(ies1.contserv,ies1.contdiscount,0) codcont,
        ( SELECT ilc.codliniecomanda
          FROM ieslink il LEFT JOIN ieslink ilc ON ilc.codies1 = COALESCE(il.codlinieaviz, il.codies1)
          WHERE il.codies1 = ies1.codies1
        ) codcomanda1, ies1.cant, ies1.cant
      FROM iesiri ies
        INNER JOIN iesiri1   ies1 ON ies1.codies     = ies.codies
        INNER JOIN contract1 c1   ON c1.codcontract1 = ies1.codcontract1
        INNER JOIN contract  c    ON c.codcontract   = c1.codcontract
      WHERE ies.operat = 1 AND ies.anulat = 0
        AND ies.DataDoc BETWEEN ' || coalesce(sData1, '') || ' AND ' || coalesce(sData2, '') || '
        AND ies.tipdoc &lt;&gt; ' || coalesce(CASE WHEN TRUNC(current_setting('PKG_LIST_ALEGPERIOADA.gCriteriu', TRUE)::NUMERIC) = 0 THEN 20 ELSE 26 END , 0)
        || coalesce(pkg_list_base_utils_cond_subunitinclactiv('C',NULL,NULL,NULL),'');

  sInsIntr := '
      INSERT INTO TMP_LST_URMCONTR (
        codcontract, codcontract1,
        tipdoc, coddoc, coddoc1, idxdoc,
        intrare,
        prefixdoc, nrdoc, datadoc,
        cant,
        pretorig, pu, tva, coefdiscmaj,
        codpart, codcont,
        codcomanda1, cantdoc, cantsold
      )
      SELECT
        c.codcontract, c1.codcontract1,
        intr.tipdoc, intr.codintr, intr1.codintr1, intr1.indexlocal,
        1,
        intr.prefixdoc, intr.nrdoc, intr.datadoc,
        intr1.cant, intr1.pretorig, intr1.pu, intr1.tva, Coalesce(intr1.coefdiscmaj,1),
        intr.partener, Coalesce(intr1.contserv,intr1.contdiscount,0) codcont,
        ( SELECT ilc.codliniecomanda
          FROM intrlink il LEFT JOIN intrlink ilc ON ilc.codintr1 = COALESCE(il.codlinieaviz, il.codintr1)
          WHERE il.codintr1 = intr1.codintr1
        ) codcomanda1, intr1.cant, intr1.cant
      FROM intrari intr
        INNER JOIN intrari1  intr1 ON intr1.codintr   = intr.codintr
        INNER JOIN contract1 c1    ON c1.codcontract1 = intr1.codcontract1
        INNER JOIN contract  c     ON c.codcontract   = c1.codcontract
      WHERE intr.operat = 1 AND intr.anulat = 0
        AND intr.DataDoc BETWEEN ' || coalesce(sData1,'') || ' AND ' || coalesce(sData2,'') || '
        AND intr.tipdoc &lt;&gt; ' || coalesce(CASE WHEN TRUNC(current_setting('PKG_LIST_ALEGPERIOADA.gCriteriu', TRUE)::NUMERIC) = 0 THEN 2 ELSE 9 END , 0)
        || coalesce(pkg_list_base_utils_cond_subunitinclactiv('C',NULL,NULL,NULL),'');

  sInsCom := '
      INSERT INTO TMP_LST_URMCONTR (
        codcontract, codcontract1,
        tipdoc, coddoc, coddoc1, idxdoc,
        intrare,
        prefixdoc, nrdoc, datadoc,
        cant, pretorig, pu, tva, coefdiscmaj,
        codpart, codcont, cantsold, cantdoc
      )
      SELECT
        c.codcontract, c1.codcontract1,
        com.tipdoc, com.codcomanda, com1.codcomanda1, com1.indexlocal,
        CASE WHEN com.tipdoc = 8 THEN 1 ELSE 0 END,
        com.prefixdoc, com.nrdoc, com.datadoc,
        com1.cantacceptat - coalesce((select sum(l.cant) from cmdlivrlink l where l.codliniecomanda = com1.codcomanda1),0) - Coalesce(fact.cant, 0),
        com1.pretorig, com1.pu, 0 tva, Coalesce(com1.coefdiscmaj,1),
        com.partener, 0 codcont, com1.restacceptat, com1.cantacceptat
      FROM comanda com
        INNER JOIN comanda1  com1 ON com1.codcomanda = com.codcomanda
        INNER JOIN contract1 c1   ON c1.codcontract1 = Coalesce(com1.codcontract1, com1.codsursa)
        INNER JOIN contract  c    ON c.codcontract   = c1.codcontract
        LEFT JOIN (SELECT codcomanda1, sum(cant) cant FROM TMP_LST_URMCONTR GROUP BY codcomanda1) fact ON fact.codcomanda1 = com1.codcomanda1
      WHERE com.operat = 1 AND com.anulat = 0
        AND coalesce(com.inchisa,0) = 0
        AND CASE WHEN com1.codcontract1 IS NOT NULL THEN 1 WHEN com1.tipsursa IN (10, 27) AND com1.codsursa IS NOT NULL THEN 1 ELSE 0 END = 1
        AND com1.restacceptat &gt; 0
        AND com.DataDoc BETWEEN ' || coalesce(sData1,'') || ' AND ' || coalesce(sData2,'') || coalesce(pkg_list_base_utils_cond_subunitinclactiv('C',NULL,NULL,NULL),'');

  sInsert := 'INSERT INTO ' || tmpName || '(
        NAV_CodDoc, NAV_TipDoc, CONTRNR, CONTRDATA, CONTRDATAI, CONTRDATAS,
        TipDoc,
        PrefixDoc, NrDoc, DataDoc, Part, Art, Cont, UM,
        TipLin,
        NrLinC,
        CantC, CantD,
        Ord,
        RestC,
        RestCNoCom,
        Pret, PU, PD, VAL, VALTVA, CantDoc ' || gUserFields || ')';

  sSelect := '
      SELECT
        c.codcontract, c.tipdoc, c.NrDoc, c.Datadoc, c.DataStart, c.DataStop,
        CASE
          WHEN tmp.intrare = 1 AND com.codcomanda IS NULL THEN ''Intrare''
          WHEN tmp.intrare = 0 AND com.codcomanda IS NULL THEN ''Iesire''
          WHEN tmp.intrare = 1                            THEN ''Comanda furnizor''
          ELSE                                                 ''Comanda client''
        END tipdoc,
        tmp.prefixdoc, tmp.nrdoc, tmp.datadoc, p.den_part, o.denumire, ncont.simbol, um.den_um1,
        CASE c1.tipobiect
          WHEN 1 THEN ''Avans facturat''
          WHEN 2 THEN ''Dobanda avans''
          WHEN 3 THEN ''Asig.baza materiala''
          WHEN 4 THEN ''Garantie materiala''
          WHEN 5 THEN ''Plata in natura''
          ELSE ''Scop contract''
        END TipLin,
        c1.indexlocal NrLinC,
        c1.cant/Coalesce(um.paritate,1), tmp.cant/Coalesce(um.paritate,1),
        Dense_Rank() OVER (PARTITION BY c1.codcontract1 ORDER BY tmp.datadoc, tmp.tipdoc, tmp.coddoc, tmp.idxdoc, tmp.coddoc1) Ord,
        (Coalesce(c1.cant,0) - SUM(coalesce(tmp.cantsold,0)) OVER (PARTITION BY c1.codcontract1 ORDER BY tmp.datadoc, tmp.tipdoc, tmp.coddoc, tmp.idxdoc, tmp.coddoc1 RANGE UNBOUNDED PRECEDING))/Coalesce(um.paritate,1) RestC,
        (Coalesce(c1.cant,0) - SUM(CASE WHEN com.codcomanda IS NULL THEN coalesce(tmp.cantsold,0) ELSE 0 END) OVER (PARTITION BY c1.codcontract1 ORDER BY tmp.datadoc, tmp.tipdoc, tmp.coddoc, tmp.idxdoc, tmp.coddoc1 RANGE UNBOUNDED PRECEDING))/Coalesce(um.paritate,1) RestCNoCom,
        tmp.pretorig*um.paritate, tmp.pu*um.paritate, tmp.pretorig*um.paritate*tmp.coefdiscmaj, tmp.cant*tmp.pu, tmp.tva, tmp.cantdoc ' || gUserAlias || '
      FROM TMP_LST_URMCONTR tmp
        LEFT JOIN contract  c     ON  c.codcontract  = tmp.codcontract
        LEFT JOIN contract1 c1    ON c1.codcontract1 = tmp.codcontract1
        LEFT JOIN intrari   intr  ON intr.codintr    = tmp.coddoc     AND intr.tipdoc      = tmp.tipdoc
        LEFT JOIN intrari1  intr1 ON intr1.codintr   = intr.codintr   AND intr1.codintr1   = tmp.coddoc1
        LEFT JOIN iesiri    ies   ON ies.codies      = tmp.coddoc     AND ies.tipdoc       = tmp.tipdoc
        LEFT JOIN iesiri1   ies1  ON ies1.codies     = ies.codies     AND ies1.codies1     = tmp.coddoc1
        LEFT JOIN comanda   com   ON com.codcomanda  = tmp.coddoc     AND com.tipdoc       = tmp.tipdoc
        LEFT JOIN comanda1  com1  ON com1.codcomanda = com.codcomanda AND com1.codcomanda1 = tmp.coddoc1
        LEFT JOIN npart     p     ON p.codpart       = tmp.codpart
        LEFT JOIN nclasep   clsp  on p.codclasa      = clsp.codclasep
        LEFT JOIN npers     agent on agent.codpers   = c.agent
        LEFT JOIN nartobj   o     ON o.codobiect     = c1.codobiect
        LEFT JOIN num1      um    ON um.codum1       = c1.umsec
        LEFT JOIN ncont           ON ncont.codcont   = tmp.codcont ' || gSuplJoins;

  sSelectX := '
      SELECT
        c.codcontract, c.tipdoc, c.NrDoc, c.Datadoc, c.DataStart, c.DataStop, ''...'' tipdoc, intr.prefixdoc, intr.nrdoc, intr.datadoc, p.den_part, o.denumire, ncont.simbol, um.den_um1,
        (case when c1.tipobiect = 1 then ''Avans facturat''when c1.tipobiect = 2 then ''Dobanda avans'' when c1.tipobiect = 3 then ''Asig.baza materiala''
          when c1.tipobiect = 4 then ''Garantie materiala'' when c1.tipobiect = 5 then ''Plata in natura'' else ''Scop contract'' end) TipLin,
        c1.indexlocal NrLinC,
        c1.cant/Coalesce(um.paritate,1), 0 CantD,
        1 Ord,
        c1.cant/Coalesce(um.paritate,1) RestC,
        c1.cant/Coalesce(um.paritate,1) RestCNoCom,
        0 Pret, 0 PU, 0 PD, 0 VAL, 0 VALTVA, c1.cant/Coalesce(um.paritate,1) ' || gUserAlias || '
      FROM contract c
        INNER JOIN contract1 c1    ON  c.codcontract  = c1.codcontract
        LEFT  JOIN intrari   intr  ON intr.codintr    = 0
        LEFT  JOIN intrari1  intr1 ON intr1.codintr   = intr.codintr
        LEFT  JOIN iesiri    ies   ON ies.codies      = 0
        LEFT  JOIN iesiri1   ies1  ON ies1.codies     = ies.codies
        LEFT  JOIN comanda   com   ON com.codcomanda  = 0
        LEFT  JOIN comanda1  com1  ON com1.codcomanda = com.codcomanda
        LEFT  JOIN npart     p     ON p.codpart       = c.partener
        LEFT  JOIN nclasep   clsp  on p.codclasa      = clsp.codclasep
        LEFT  JOIN npers     agent on agent.codpers   = c.agent
        LEFT  JOIN nartobj   o     ON o.codobiect     = c1.codobiect
        LEFT  JOIN num1      um    ON um.codum1       = c1.umsec
        LEFT  JOIN ncont           ON ncont.codcont   = Coalesce(intr1.contserv,intr1.contdiscount,0) ' || gSuplJoins || '
      WHERE c.operat = 1 AND c.anulat = 0
        AND NOT c1.codcontract1 IN (SELECT DISTINCT CodContract1 FROM TMP_LST_URMCONTR)
        AND Coalesce(c1.DataStart, c.datastart) &lt;= ' || coalesce(sData2,'') || '
        AND Coalesce(c1.DataStop , c.datastop ) &gt;= ' || coalesce(sData1,'') || coalesce(pkg_list_base_utils_cond_subunitinclactiv('C',NULL,NULL,NULL),'');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsIes , aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsIntr, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsCom , aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);

  IF current_setting('PKG_LIST_ALEGPERIOADA.gOpt1', TRUE)::boolean THEN
    PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelectx,''), aListID, aListVer);
  END IF;

  EXECUTE 'UPDATE ' || tmpName || ' SET CantC = 0 WHERE Ord &gt; 1';
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmcontr_setjoinuri</obj_name>
  <obj_hashval>77110c6e6a0413c4115ac9d64c37690f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmcontr_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 11.09.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_URMCONTR.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmcontrabon_processlist</obj_name>
  <obj_hashval>631ca4df602ca7d9323da2d17118d49f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmcontrabon_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplCols   VARCHAR := '';
  gSuplJoins  VARCHAR := '';

  sInsert     varchar;
  sSelect     varchar;
  pBancaV     varchar;
begin
  --Bogdan 08.09.2020
    gSuplCols := 'contract c, contract2 c2, iesiri i, npart p, nmonede mc, nmonede md, nclasep cp, nagenda slivr, npartcodfisc codf ';

  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config ('PKG_LIST_BASE_URMCONTRABON.gSuplCols',gSuplCols,false);

  pBancaV := Coalesce (fnc_GetValConstantaLucru ('BancaCursPUV') , '0');
  sInsert := 'INSERT INTO '|| coalesce (tmpName,'')
            || ' (NAV_CodDoc,
            NAV_TipDoc,
            CONTRNR,
            CONTRDATA,
            CONTRDATAI,
            CONTRDATAS,
            CONTRDATAF,
            CONTRMoneda,
            CONTRVal,
            PrefixDoc,
            NrDoc,
            DataDoc,
            Part,
            Moneda,
            ValDoc,
            TVADoc,
            VALTOTDOC '
            || coalesce (gUserFields ,'')
            || ')';
  sSelect := '
        SELECT c.codcontract,
          c.tipdoc,
          c.NrDoc,
          c.Datadoc,
          c.DataStart,
          c.DataStop,
          c2.data,
          mc.den_moneda,
          c2.suma,
          i.prefixdoc,
          i.nrdoc,
          i.datadoc,
          p.den_part,
          md.den_moneda,
          i.valdoc - i.tvadoc,
          i.tvadoc,
          i.valdoc '
            || coalesce (gUserAlias ,'')|| '
        FROM contract          c
          INNER JOIN contract2 c2 ON c2.codcontract = c.codcontract
          LEFT JOIN iesiri     i  ON i.codies       = c2.coddoc AND i.tipdoc = c2.tipdoc
          LEFT JOIN npart      p  ON p.codpart      = c.partener
          LEFT JOIN nmonede    mc ON mc.codmoneda   = c.moneda
          LEFT JOIN nmonede    md ON md.codmoneda   = i.moneda
          LEFT JOIN ( SELECT DISTINCT CodMoneda,
                             LAST_VALUE (x.codmoneda1) OVER (PARTITION BY CodMoneda ORDER BY X.DATA range between unbounded preceding and unbounded following) CodMoneda1
                      FROM nmonede1 x
                      WHERE coalesce (x.valoare,0) &lt;&gt; 0 AND x.codbanca = '|| coalesce (pBancaV,'')
                || ') xc1 ON xc1.codmoneda = c.moneda
          LEFT JOIN nmonede1     mc1 ON mc1.codmoneda1 = xc1.codmoneda1'
          || coalesce (gSuplJoins ,'')|| '
        WHERE
          c.tipdoc = 34
          AND c.operat = 1
          AND c.anulat = 0 '
            || coalesce ( (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT (NULL,'C',NULL,NULL,NULL)) ,'')|| '
          AND c2.data BETWEEN To_date ('''||coalesce(To_Char((SELECT PKG_LIST_ALEGPERIOADA_getDataS.WME_RESULT FROM PKG_LIST_ALEGPERIOADA_getDataS (NULL,NULL))  ,'dd.mm.yyyy') ,'')|| ''',''dd.mm.yyyy'')
                          AND To_date ('''||coalesce(To_Char((SELECT PKG_LIST_ALEGPERIOADA_getDataF.WME_RESULT FROM PKG_LIST_ALEGPERIOADA_getDataF (NULL,NULL))  ,'dd.mm.yyyy') ,'')|| ''',''dd.mm.yyyy'') ';
  PERFORM LIST_EXECUTE_IMMEDIATE (coalesce (sInsert,'')|| coalesce (sSelect,'') , aLISTID, aLISTVER);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmcontrabon_setjoinuri</obj_name>
  <obj_hashval>56ddff8974ec6109a5e84654d03a5a27</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmcontrabon_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 08.09.2020
  PERFORM pkg_list_struct_SetTableSpec (current_setting ('PKG_LIST_BASE_URMCONTRABON.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmcontrarenda_setjoinuri</obj_name>
  <obj_hashval>48b5d38c5e3660088ec88fd1711b1176</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmcontrarenda_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 10 septembrie 2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_URMCONTRARENDA.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmcontrcom_setjoinuri</obj_name>
  <obj_hashval>54360140f1f4da573333f9bee9f60c3d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmcontrcom_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 07.09.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_URMCONTRCOM.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmcontrleasing_setjoinuri</obj_name>
  <obj_hashval>746775487e379fa8a368ac6f34b613ec</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmcontrleasing_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 10 septembrie 2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_URMCONTRLEASING.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmcontrleasing_setparams</obj_name>
  <obj_hashval>cd190872aeb9f02215bb894eb7dc5bba</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmcontrleasing_setparams(ptipsold numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 10 septembrie 2020
  perform set_config('PKG_LIST_BASE_URMCONTRLEASING.vTipSold',(pTipSold)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmcontrrac_processlist</obj_name>
  <obj_hashval>49fd6d8b2c6c5c3780636da4bb7f71dc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmcontrrac_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sSelect         varchar := '';
  gSuplCols        VARCHAR :=   'contract contr, contract1 contr1, nparcaut pauto, nmarciauto amarca, nmodeleauto amodel, nartobj obj, num1 um, nart na, nclasea ca, comanda1 com1, comanda com, '||
                               'iesiri1 ies1, iesiri ies, iesiri1 iesx1, iesiri iesx, npart p, nmonede mcontr, nmonede mcom, nmonede mies';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  gDataS          varchar := current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true);
  gDataF          varchar := current_setting('PKG_LIST_ALEGPERIOADA.gDataF', true);
BEGIN
  --Florin 09.02.2023 - fixat 57083
  --Adina 16.10.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_URMCONTRRAC.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  perform set_config('PKG_LIST_BASE_URMCONTRRAC.D1'  ,gDataS,false);
  perform set_config('PKG_LIST_BASE_URMCONTRRAC.D2'  ,gDataF,false);
  perform set_config('PKG_LIST_BASE_URMCONTRRAC.Luni',(Extract( Month FROM to_date(gDataF,'dd.mm.yyyy')) - Extract( Month FROM to_date(gDataS,'dd.mm.yyyy')) + 1)::varchar,false);

  sInsert :=
  'INSERT INTO ' || tmpName || '(
    NAV_CodDoc,NAV_TipDoc,
    CONTRNR, CONTRDATA, CONTRMONEDA, Part,
    COMNR, COMDATA, COMMONEDA,
    IesPrefix, IesNr, IesData, IesMoneda,
    OrdContr1,
    DenObj, SimbClasaA, NrAuto, MarcaAuto, ModelAuto, DenUm1,
    ContrCantX,
    ContrCant,
    ContrPret,
    ComCant, ComPU,
    IesCant, IesPu, MaxRezSimultan, MaxZileRez, TotCantCmd, Zile, TipPr  ' || gUserFields || ')';

  sSelect :=
  'with
    CantCmd as
    (Select x1.CodContract1, sum(x1.CantAcceptat) CantTot
     from Comanda1 x1
          inner join Comanda x on x.codcomanda = x1.codcomanda
           Inner Join Rac_Rez R ON x.codcomanda = R.codcomanda
     where R.DataStart BETWEEN to_date(''' || gDataS || ''', ''dd.mm.yyyy'') and to_date(''' || gDataF || ''', ''dd.mm.yyyy'')
           and x.Operat = 1  and x.TipDoc = 94
           and coalesce(x1.codcontract1, 0) &gt; 0
     group by x1.CodContract1
    ),
    CantCmdAll as
    (Select x1.CodContract1, sum(x1.CantAcceptat) CantTot
     from Comanda1 x1
          inner join Comanda x on x.codcomanda = x1.codcomanda
           Inner Join Rac_Rez R ON x.codcomanda = R.codcomanda
     where R.DataStart &lt;= to_date(''' || gDataF || ''', ''dd.mm.yyyy'')
           and x.Operat = 1  and x.TipDoc = 94
           and coalesce(x1.codcontract1, 0) &gt; 0
     group by x1.CodContract1
    )
       SELECT
        contr.codcontract, contr.tipdoc,
        contr.NrDoc, contr.Datadoc, mcontr.simbol, p.den_part,
        com.NrDoc, com.Datadoc, mcom.simbol,
        Case when Contr1.TipPret = 1 then iesx.prefixdoc else ies.prefixdoc end prefixdoc,
        Case when Contr1.TipPret = 1 then Iesx.NrDoc else Ies.NrDoc end  NrDoc,
        Case when Contr1.TipPret = 1 then iesx.datadoc else ies.datadoc end datadoc,
        Case when Contr1.TipPret = 1 then miesx.simbol else mies.simbol end simbol,
        Row_NUMBER() OVER (Partition BY contr1.codcontract1 ORDER BY com.datadoc, com.nrdoc, com1.codcomanda1, ies.datadoc, ies.nrdoc, iesl.codies1) OrdContr1,
        obj.denumire, ca.simbol, pauto.nrinreg, amarca.marca, amodel.model, um.den_um1,
        0 ContrCantX,
        Case when Contr1.TipPret = 3 then (' || coalesce(current_setting('PKG_LIST_BASE_URMCONTRRAC.Luni', true),'') || '*contr1.cant)/um.paritate
             else contr1.cant/um.paritate
        end contrcant,
        contr1.pret*um.paritate contrpret,
        coalesce(com1.cantacceptat/um.paritate,0) comcant, coalesce(com1.pu*um.paritate,0) compret,
        Case when Contr1.TipPret = 1 then coalesce(iesx1.cant/um.paritate,0) else coalesce(ies1.cant/um.paritate,0) end iescant,
        Case when Contr1.TipPret = 1 then coalesce(iesx1.pu*um.paritate,0) else coalesce(ies1.pu*um.paritate,0) end iespret,
        Contr.MAXREPLSIMULTANE MaxRezSimultan, Contr.MAXZILEREPLA MaxZileRez,
        Case when Contr1.TipPret = 4 then cc1All.CantTot else cc1.CantTot end TotCantCmd,
        0 Zile,
        Case when Contr1.TipPret = 1 then ''lunar''
             when Contr1.TipPret = 2 then ''pe zi''
             when Contr1.TipPret = 3 then ''cantitativ''
             when Contr1.TipPret = 4 then ''pachet''
        end TipPr ' || gUserAlias || '
      FROM contract contr
        INNER JOIN contract1 contr1   ON contr1.codcontract   = contr.codcontract
        LEFT  JOIN CantCmd cc1         on cc1.codcontract1     = contr1.codcontract1
        LEFT  JOIN CantCmdAll cc1All   on cc1All.codcontract1  = contr1.codcontract1
        LEFT  JOIN nparcaut pauto     ON pauto.codnparcaut    = contr1.codauto
        LEFT  JOIN nmarciauto amarca   ON amarca.codmarciauto  = pauto.marca
        LEFT  JOIN nmodeleauto amodel ON amodel.codmodeleauto = pauto.model
        LEFT  JOIN nartobj obj         ON obj.codobiect        = contr1.codobiect
        LEFT  JOIN num1 um             ON um.codum1            = contr1.umsec
        LEFT  JOIN nart na             ON na.codarticol        = obj.codarticol
        LEFT  JOIN nclasea ca         ON ca.codclasea         = na.clasa
        LEFT  JOIN (select c1.* from comanda1 c1 inner JOIN comanda c ON c.codcomanda = c1.codcomanda
                    where  c.tipdoc=18
                    and c.datadoc BETWEEN to_date(''' || gDataS || ''', ''dd.mm.yyyy'') and to_date(''' || gDataF || ''', ''dd.mm.yyyy'')
                    and C.Operat = 1
                    and coalesce(c1.codcontract1,0) &gt; 0
                   ) com1             ON com1.codcontract1    = contr1.codcontract1
        LEFT  JOIN comanda com         ON com.codcomanda       = com1.codcomanda
        LEFT  JOIN ieslink iesl       ON iesl.codliniecomanda = com1.codcomanda1 AND coalesce(iesl.codies1,0) &lt;&gt; 0
        LEFT  JOIN iesiri1 ies1       ON ies1.codies1         = iesl.codies1
        LEFT  JOIN iesiri ies         ON ies.codies           = ies1.codies
        LEFT  JOIN contract2 c2       ON c2.codcontract       = contr.codcontract
        LEFT  JOIN iesiri iesx         ON iesx.codies           = c2.coddoc AND iesx.tipdoc = c2.tipdoc
        LEFT  JOIN iesiri1 iesx1       ON iesx.codies           = iesx1.codies and iesx1.CodContract1 =  Contr1.CodContract1
        LEFT  JOIN npart p             ON p.codpart             = contr.partener
        LEFT  JOIN nmonede mcontr     ON mcontr.codmoneda     = contr.moneda
        LEFT  JOIN nmonede mcom       ON mcom.codmoneda       = com.moneda
        LEFT  JOIN nmonede mies       ON mies.codmoneda       = ies.moneda
        LEFT  JOIN nmonede miesx       ON miesx.codmoneda       = iesx.moneda ' || gSuplJoins || '
      WHERE  contr.tipdoc = 34 AND contr.operat = 1
             AND contr.anulat = 0
             AND contr.activ &lt;&gt; 0
             and (contr.activ = 3 or (1=1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('contr',NULL,NULL,NULL),'') || '))
             AND (coalesce(C2.CodContract, 0) = 0 or (c2.data is not null and c2.data BETWEEN to_date(''' || gDataS || ''', ''dd.mm.yyyy'') and to_date(''' || gDataF || ''', ''dd.mm.yyyy'')))
             and ( contr1.tippret = 1
                   or (contr1.tippret = 4 and contr1.cant &lt; coalesce(cc1All.canttot,0))
                   or (contr1.tippret = 3 and ' || coalesce(current_setting('PKG_LIST_BASE_URMCONTRRAC.Luni', true),'') || '*contr1.cant &lt; coalesce(cc1.canttot,0)))';

  PERFORM pkg_globals_CheckDebugMode(sInsert || sSelect, aListID, aListVer);
  PERFORM pkg_globals_CheckDebugMode('UPDATE ' || tmpName || ' SET ContrCantX = ContrCant WHERE OrdContr1 = 1', aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE('UPDATE ' || tmpName || ' SET ContrCantX = ContrCant WHERE OrdContr1 = 1', aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmcontrrac_setjoinuri</obj_name>
  <obj_hashval>2cd241d71c5a00060a1f587c8861a76d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmcontrrac_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 16.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_URMCONTRRAC.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmcontrrac1_processlist</obj_name>
  <obj_hashval>e7c5ca5dfc54c8aadbf4a6679c72e0cf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmcontrrac1_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sSelect     varchar;
  aInd        numeric;
  gSuplCols   varchar := 'contract contr, contract1 contr1, nparcaut pauto, nmarciauto amarca, nmodeleauto amodel, nartobj obj, num1 um, nart na, nclasea ca, comanda1 com1, comanda com, ' || 'iesiri1 ies1, iesiri ies, npart p, nmonede mcontr, nmonede mcom, nmonede mies';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  D1          date;
  D2          date;
  Luni        NUMERIC;
BEGIN
  --Florin 09.02.2023 - fixat 57084
  --Florin 05.10.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_URMCONTRRAC1.gSuplCols', gSuplCols, FALSE);

  D1   := current_setting('PKG_LIST_ALEGPERIOADA.gDataS', TRUE);
  D2   := current_setting('PKG_LIST_ALEGPERIOADA.gDataF', TRUE);
  Luni := Extract(Month from D2) - Extract(Month from D1) + 1;
  aInd := 1;
  sInsert := 'INSERT INTO ' || tmpName || '(
        NAV_CodDoc,NAV_TipDoc,
        CONTRNR, CONTRDATA, CONTRMONEDA, Part,
        COMNR, COMDATA, COMMONEDA,
        IesPrefix, IesNr, IesData, IesMoneda,
        OrdContr1,
        DenObj, SimbClasaA, NrAuto, MarcaAuto, ModelAuto, DenUm1,
        ContrCantX,
        ContrCant,
        ContrPret,
        ComCant, ComPU,
        IesCant, IesPu, MaxRezSimultan, MaxZileRez, TotCantCmd, Zile, TipPr ' || gUserFields || ')';
  sSelect := 'with CantCmd as
    (Select x1.CodContract1, sum(x1.CantAcceptat) CantTot
     from Comanda1 x1 inner join Comanda x on x.codcomanda = x1.codcomanda
     Inner Join Rac_Rez R ON x.codcomanda = R.codcomanda
     where R.DataStart BETWEEN to_date(''' || d1 || ''', ''dd.mm.yyyy'') and to_date(''' || d2 || ''', ''dd.mm.yyyy'')
     and x.Operat = 1 and x.TipDoc = 94
     and COALESCE(x1.codcontract1, 0) &gt; 0
     group by x1.CodContract1)
     SELECT
        contr.codcontract, contr.tipdoc,
        contr.NrDoc, contr.Datadoc, mcontr.simbol, p.den_part,
        crz.NrDoc, crz.Datadoc, mcom.simbol,
        ies.prefixdoc, ies.nrdoc, ies.datadoc, mies.simbol,
        Row_NUMBER() OVER (Partition BY contr1.codcontract1 ORDER BY crz.datadoc, crz.nrdoc, crz.codcomanda1, ies.datadoc, ies.nrdoc, iesl.codies1) OrdContr1,
        obj.denumire, ca.simbol, pauto.nrinreg, amarca.marca, amodel.model, um.den_um1,
        0 ContrCantX,
        Case when Contr1.TipPret = 3 then (' || coalesce(current_setting('PKG_LIST_BASE_URMCONTRRAC1.Luni', true)::numeric,0) || '*contr1.cant)/um.paritate
        else contr1.cant/um.paritate
        end contrcant,
        contr1.pret*um.paritate contrpret,
        COALESCE(crz.cantacceptat/um.paritate,0) comcant, COALESCE(crz.pu*um.paritate,0) compret,
        COALESCE(ies1.cant/um.paritate,0) iescant, COALESCE(ies1.pu*um.paritate,0) iespret,
        Contr.MAXREPLSIMULTANE MaxRezSimultan, Contr.MAXZILEREPLA MaxZileRez, cc1.CantTot TotCantCmd,
        Case when COALESCE(CRZ.TipRezervare,0) = 6 and E.Ind = ' || coalesce(aInd::varchar,'') || ' then crz.CantAcceptat else 0 end Zile,
        Case when Contr1.TipPret = 1 then ''lunar''
             when Contr1.TipPret = 2 then ''pe zi''
             when Contr1.TipPret = 3 then ''cantitativ''
             when Contr1.TipPret = 4 then ''pachet''
        end TipPr ' || gUserAlias || '
      FROM contract contr
        INNER JOIN contract1   contr1 ON contr1.codcontract   = contr.codcontract
        LEFT  JOIN nparcaut    pauto  ON pauto.codnparcaut    = contr1.codauto
        LEFT  JOIN nmarciauto  amarca ON amarca.codmarciauto  = pauto.marca
        LEFT  JOIN nmodeleauto amodel ON amodel.codmodeleauto = pauto.model
        LEFT  JOIN CantCmd     cc1    on cc1.codcontract1     = contr1.codcontract1
        LEFT  JOIN nartobj     obj    ON obj.codobiect        = contr1.codobiect
        LEFT  JOIN NEchiv      E      on Obj.CodObiect        = E.codobiect
        LEFT  JOIN num1        um     ON um.codum1            = contr1.umsec
        LEFT  JOIN nart        na     ON na.codarticol        = obj.codarticol
        LEFT  JOIN nclasea     ca     ON ca.codclasea         = na.clasa
        LEFT  JOIN (SELECT COM1.CODCOMANDA1, R.CODRAC_REZ, COM1.CODCONTRACT1,COM.MONEDA,COM.TIPDOC,COM.ANULAT,COM1.CANTACCEPTAT,
                           COM1.PU,R.TIPREZERVARE,COM.NRDOC,COM.DATADOC
                    FROM comanda1 com1
                        LEFT JOIN comanda com ON com.codcomanda = com1.codcomanda
                        LEFT JOIN Rac_Rez R ON com.codcomanda = R.codcomanda
                    WHERE R.dataStart is null or R.dataStart BETWEEN to_date(''' || d1 || ''', ''dd.mm.yyyy'') and to_date(''' || d2 || ''', ''dd.mm.yyyy'')
                   )           CRZ    ON CRZ.CODCONTRACT1     = CONTR1.CODCONTRACT1
        LEFT  JOIN COMANDA1    COM1   ON COM1.CODCOMANDA1     = CRZ.CODCOMANDA1
        LEFT  JOIN COMANDA     COM    ON COM1.CODCOMANDA      = COM.CODCOMANDA
        LEFT  JOIN ieslink     iesl   ON iesl.codliniecomanda = crz.codcomanda1 AND COALESCE(iesl.codies1,0) &lt;&gt; 0
        LEFT  JOIN iesiri1     ies1   ON ies1.codies1         = iesl.codies1
        LEFT  JOIN iesiri      ies    ON ies.codies           = ies1.codies
        LEFT  JOIN npart       p      ON p.codpart            = contr.partener
        LEFT  JOIN nmonede     mcontr ON mcontr.codmoneda     = contr.moneda
        LEFT  JOIN nmonede     mcom   ON mcom.codmoneda       = crz.moneda
        LEFT  JOIN nmonede     mies   ON mies.codmoneda       = ies.moneda ' || gSuplJoins || '
      WHERE contr.tipdoc = 34 AND contr.operat = 1 and COALESCE(crz.anulat,0)=0
        AND contr.anulat = 0 AND contr.activ &lt;&gt; 0 and (contr.activ = 3 or (1=1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('contr',NULL,NULL,NULL),'') || '))
        AND (crz.tipdoc is null or crz.tipdoc = 94) AND contr1.tippret in (1,3,4)';
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE('UPDATE ' || coalesce(tmpName,'') || ' SET ContrCantX = ContrCant WHERE OrdContr1 = 1', aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmcontrrac1_setjoinuri</obj_name>
  <obj_hashval>8f09ad67e61a02e85a8890b11ee40d5b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmcontrrac1_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 05.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_URMCONTRRAC1.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmincart_getcodcontract</obj_name>
  <obj_hashval>b1f24cbcd511e2ceea18fe0be0e1c988</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmincart_getcodcontract(acodpart numeric, adatadoc date)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodContract numeric;
begin
  --Bogdan 07.09.2020
  BEGIN
    SELECT COALESCE(CodContract, 0)
    INTO aCodContract
    FROM contract c
    WHERE
         c.tipdoc = 27 AND  c.partener = aCodPart AND aDataDoc BETWEEN c.datastart AND c.datastop;
  EXCEPTION WHEN others THEN
    aCodContract := 0;
  END;

  return  aCodContract;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmincart_processlist</obj_name>
  <obj_hashval>319f5218ccaf61cfb9313f3d34636a82</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmincart_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplCols   VARCHAR := '';
  gSuplJoins  VARCHAR := '';

  sInsert     varchar;
  sSelect     varchar;
  sInsertMan  varchar;
  sSelectMan  varchar;
  sInsMonet   varchar;
  sSelMonet   varchar    := '';
  sUpdateMan  varchar;
  sTipJoin    varchar    := 'INNER';
  sWhereUN    varchar    := '';
  sAUX1       varchar    := '';
  sUPD1       varchar    := '';
  sUPD2       varchar    := '';
  sAnS        numeric(4) := EXTRACT( YEAR  FROM (SELECT pkg_list_alegperioada_getDataS.WME_RESULT FROM pkg_list_alegperioada_getDataS(NULL,NULL)));
  sLunaS      numeric(2) := EXTRACT( MONTH FROM (SELECT pkg_list_alegperioada_getDataS.WME_RESULT FROM pkg_list_alegperioada_getDataS(NULL,NULL)));
  sDataS      varchar := To_Char((SELECT pkg_list_alegperioada_getDataS.WME_RESULT FROM pkg_list_alegperioada_getDataS(NULL,NULL)), 'dd.mm.yyyy');
  sDataF      varchar := To_Char((SELECT pkg_list_alegperioada_getDataF.WME_RESULT FROM pkg_list_alegperioada_getDataF(NULL,NULL)), 'dd.mm.yyyy');
  AnLunaLucru numeric;
  AnLunaIni   numeric;
  sCurs       varchar    := ', 1, 1, 1, 1';
  sBancaV     varchar;
  aBancaV     numeric;
  aMonedaV    numeric;

  sInsAux     varchar    := '';
BEGIN
  --Adina 10.05.2021 - sinc.Oracle din 10.05.2021
  --Adina 28.04.2021 - alstart,alstop
  --Adina 16.04.2021 - sinc.Oracle din 16.04.2021
  --Adina 31.03.2021 - sinc.Oracle din 30.03.2021
  --Adina 03.03.2021 - sinc.Oracle din 02.03.2021
  --Adina 16.01.2021 - sinc.Oracle - modificare facuta de Florentin (pe Oracle) pe 14.01.2021
  --Adina 17.12.2020 refacut complet dupa Oracle - tichet 41647
  gSuplCols := 'npart npart, nmonede mon, nagenda ag, npers agent, npers agent_inc, nsubunit substingatori, nsubunit substinsi, nartobj1 n1, nartobj o, nbankcont bc,'||
               'tmp_lst_stingatori TMP_INC, tmp_lst_stinsi TMP_DOC';

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT'    , 'OEXT.CODOBIECT     = O.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR'    , 'OATR.CODOBIECT     = O.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NAGENDA'   , 'SSOC'    , 'SSOC.CODPART       = UN.CODPART AND SSOC.SEDIUSOCIAL BETWEEN 4 AND 7 AND Coalesce(SSOC.INACTIV, 0) = 0', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPERS'     , 'AGP'     , 'AGP.CODPERS        = SSOC.CODAGENT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NMONEDE'   , 'MONPREST', 'MONPREST.CODMONEDA = Coalesce(N1.CODMONEDA,0)');
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI'    , 'I'       , 'I.CODIES           = UN.CODDOC AND I.TIPDOC = UN.TIPDOC', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI1'   , 'I1'      , 'I1.CODIES1         = UN.CODDOC1 AND I1.CODIES = I.CODIES', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CONTRACT2' , 'C2'      , 'C2.CODDOC          = I.CODIES AND C2.TIPDOC = I.TIPDOC',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NBANK'     , 'B'       , 'B.CODBANK          = BC.CODBANK',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'PRETM'     , 'PRETM'   , 'PRETM.CODOBIECT    = O.CODOBIECT AND PRETM.IMPLICIT = 1 AND PRETM.SUBUNITATEA = ' || coalesce(getSUBUNITATE()::varchar,''));
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTCLI'   , 'AC'      , 'AC.CODOBIECT       = O.CODOBIECT AND AC.CODPART = NPART.CODPART',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCLASEP'   , 'CLSP'    , 'CLSP.CODCLASEP     = Coalesce(NPART.CODCLASA, 0)');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NLOCALIT'  , 'LOC'     , 'LOC.CODLOCALIT     = AG.CODLOCALIT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NJUDET'    , 'JUD'     , 'JUD.CODJUDET       = LOC.CODJUDET' ,NULL);
  CALL pkg_list_struct_getsuplcols( aLISTID, aLISTVER, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config('PKG_LIST_BASE_URMINCART.gSuplCols',gSuplCols,false);

  CALL PRC_AL_CHECK('nartobj1',0);

  SELECT getanlucru() * 12 + getLunaLucru(), ANINITIAL * 12 + LUNAINITIALA
  INTO AnLunaLucru, AnLunaIni
  FROM FIRMALUNI;

  sBancaV  := fnc_GetValConstanta('BancaCursPUV', getANLUCRU(), getLunaLucru());
  aBancaV  := case when sBancaV='' then null else sBancaV::numeric end ;
  aMonedaV := (SELECT pkg_list_base_utils_GET_Cod_MonedaFactInValuta.WME_RESULT FROM pkg_list_base_utils_GET_Cod_MonedaFactInValuta(NULL,getanlucru(), getLunaLucru()));

  IF  Coalesce(aMonedaV, 0) &lt;&gt; 0 AND  Coalesce(aBancaV, 0) &lt;&gt; 0 THEN
    sCurs := ',
            (select wme_result from PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null,'
              || coalesce(aMonedaV::varchar,'') || ','
              || coalesce(aBancaV::varchar,'')
              || ', to_char(un.dstinsdata,''dd.mm.yyyy''))),
            (select wme_result from PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null,'
              || coalesce(aMonedaV::varchar,'') || ','
              || coalesce(aBancaV::varchar,'')
              || ', to_char(un.dstingdata,''dd.mm.yyyy'')))';
  ELSE
    sCurs := ',1, 1';
  END IF;

  IF  Coalesce(aBancaV, 0) &lt;&gt; 0 THEN
    sCurs := coalesce(sCurs,'')
      || ',
          (select wme_result from PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null,N1.CODMONEDA,'
            || coalesce(aBancaV::varchar,'')
            || ', to_char(un.dstinsdata,''dd.mm.yyyy''))),
          ( select wme_result from PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null,N1.CODMONEDA,'
            || coalesce(aBancaV::varchar,'')
            || ', to_char(un.dstingdata,''dd.mm.yyyy'')))';
  ELSE
    sCurs := coalesce(sCurs,'') || ',1, 1';
  END IF;

  IF (SELECT pkg_list_alegperioada_optiunea1.WME_RESULT FROM pkg_list_alegperioada_optiunea1(NULL,NULL)) THEN
    sTipJoin := 'LEFT';
  END IF;

  IF (SELECT pkg_list_alegperioada_optiunea1.WME_RESULT FROM pkg_list_alegperioada_optiunea1(NULL,NULL))
      AND (SELECT pkg_list_alegperioada_optiunea2.WME_RESULT FROM pkg_list_alegperioada_optiunea2(NULL,NULL)) THEN
    sWhereUN := '
            WHERE ( stingatori.codobligpif IS NOT NULL OR stinsi.datadoc BETWEEN TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'') AND TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'') )';

      IF (SELECT pkg_list_alegperioada_optiunea1.WME_RESULT FROM pkg_list_alegperioada_optiunea1(NULL,NULL)) THEN
        sWhereUN := coalesce(sWhereUN,'') || ' AND Coalesce(STINSI.INFOCM,0) = 0';
      END IF;
  ELSE
    IF (SELECT pkg_list_alegperioada_optiunea1.WME_RESULT FROM pkg_list_alegperioada_optiunea1(NULL,NULL)) THEN
      sWhereUN := coalesce(sWhereUN,'') || ' WHERE Coalesce(STINSI.INFOCM,0) = 0';
    END IF;
  END IF;

  EXECUTE 'TRUNCATE TABLE tmp_lst_stingatori';
  EXECUTE 'TRUNCATE TABLE tmp_lst_stinsi';
  EXECUTE 'TRUNCATE TABLE tmp_lst_urmincmon';

  sUpdateMan := '
      SET
        (GESTDEN, GESTSIMB, FURNIZORI, PRETACHIZ) =
        ( SELECT
            fnc_array_to_vc3200 (ARRAY_AGG(DISTINCT ng.den_gest)),
            fnc_array_to_vc3200 (ARRAY_AGG(DISTINCT ng.simbol  )),
            fnc_array_to_vc3200 (ARRAY_AGG(DISTINCT f.den_part )),
            CASE
              WHEN SUM(COALESCE(L1X.CANT,L1.CANT,I1.CANT)) = 0 THEN 0
              ELSE SUM((Coalesce(NS.PRET,0) - Coalesce(NS.ADAOS,0)) * COALESCE(L1X.CANT,L1.CANT,I1.CANT)) / SUM(COALESCE(L1X.CANT,L1.CANT,I1.CANT))
            END
          FROM iesiri1           i1
            INNER JOIN iesiri    i   ON i.codies         = i1.codies
            LEFT JOIN livr       l   ON l.codies         = i.codies
            LEFT JOIN livr1      l1  ON l1.codies1       = i1.codies1 AND l1.codlivr = l.codlivr
            LEFT JOIN ieslink    il  ON il.codies1       = i1.codies1
            LEFT JOIN IESIRI1    II1 ON IL.CODLINIEAVIZ = II1.CODIES1
            LEFT JOIN IESIRI     II  ON II.CODIES       = II1.CODIES
            LEFT JOIN LIVR       LL  ON LL.CODIES       = II.CODIES
            LEFT JOIN LIVR1      LL1 ON LL1.CODLIVR     = LL.CODLIVR AND LL1.CODIES1 = II1.CODIES1
            LEFT JOIN iesvallink ivl ON ivl.codlivr1     = l1.codlivr1
            LEFT JOIN iesiri1    i1x ON i1x.codies1     = ivl.codies1
            LEFT JOIN livr1      l1x ON l1x.codies1     = i1x.codies1
            LEFT JOIN livr       lx  ON lx.codlivr       = l1x.codlivr
            LEFT JOIN nirstoc    ns  ON ns.codnirstoc   = COALESCE(l1x.codnirstoc, LL1.CODNIRSTOC,l1.codnirstoc)
            LEFT JOIN nirstoc1   ns1 ON ns1.codnirstoc   = ns.codnirstoc
            LEFT JOIN nirstoc    nso ON nso.codnirstoc   = ns1.codnirstocorig
            LEFT JOIN nir        n   ON n.codnir         = ns.codnir
            LEFT JOIN livrval    lv  ON lv.codlivr1     = l1.codlivr1
            LEFT JOIN ngest      ng  ON ng.codgest       = coalesce(n.gest, lv.gest, 0)
            LEFT JOIN npart      f   ON f.codpart       = ns.furn
          WHERE i1.codies1 = t.coddoc1 AND Coalesce(ng.codgest,0) &lt;&gt; 0
        )
      WHERE t.tipstoc = 1 ';

  sInsertMan := 'INSERT INTO tmp_lst_stingatori(
        codobligpif, codgeneral, coddoc, coddoc1, tipdoc,coddocs,tipdocs,
        docstingator,
        datadecont, datadoc, datainc, agent, subunitatea, codstinspif, valoare, valftva,
        curs, moneda, an, luna, codbanca)';

  sSelectMan := '
    SELECT
      o.CodObligPIF, o.Codgeneral, tx.codtrezor CodDoc, t1x.codtrezor1 CodDoc1, g.TipDoc, 0 CodDocS, GD.TIPDOC TipDocS,
      t1x.doc||'' ''||t1x.nrdoc||''/''||to_char(t1x.datadoc, ''dd.mm.yyyy'') DOCSTINGATOR,
      t1x.datadecont, t1x.datadoc, t1x.datadoc DATAINC, t1x.agent, t.Subunitatea, s.codstinspif, o.valoare, o.valoare-Coalesce(g.tva,0) valftva,
      Coalesce(NULLIF(t1x.curs,0),1) curs, COALESCE(tx.monedapers, bc.codmoneda, 0) moneda, tx.an, tx.luna, tx.codbanca
    FROM trezor1          t1
      INNER JOIN trezor   t   ON t1.codtrezor       = t.codtrezor
      INNER JOIN general  g   ON g.tipdoc           = t.tipdoc AND g.coddoc = t1.codtrezor1
      INNER JOIN obligpif o   ON o.codgeneral       = g.codgeneral
      INNER JOIN stingere s   ON s.codstingatorpif   = o.codobligpif
      INNER JOIN general  gc  ON gc.coddoc           = g.coddoc AND gc.semnificatie = 600 AND gc.semnificatie &lt;&gt; g.semnificatie
      INNER JOIN obligpif oc  ON oc.codgeneral       = gc.codgeneral
      INNER JOIN stingere sc  ON sc.codstinspif     = Coalesce(oc.codobligpif, o.codobligpif)
      INNER JOIN obligpif ox  ON ox.codobligpif     = sc.codstingatorpif
      INNER JOIN general  gx  ON gx.codgeneral       = ox.codgeneral AND gx.tipdoc &lt;&gt; 31
      INNER JOIN trezor1  t1x ON t1x.codtrezor1     = gx.coddoc
      INNER JOIN trezor   tx  ON t1x.codtrezor       = tx.codtrezor
      INNER JOIN OBLIGPIF OD  ON OD.CODOBLIGPIF     = S.CODSTINSPIF
      INNER JOIN GENERAL  GD  ON GD.CODGENERAL      = OD.CODGENERAL
      LEFT JOIN nbankcont bc  ON bc.codbankcont     = tx.codbanca
    WHERE t.tipdoc = 31
      AND g.semnificatie IN (400,420,750,751)
      AND T1X.DATADOC BETWEEN TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'') AND TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')
    UNION ALL';

  IF (SELECT pkg_list_alegperioada_optiunea3.WME_RESULT FROM pkg_list_alegperioada_optiunea3(NULL,NULL)) THEN
    sSelectMan := '';
    sAUX1 := ',31';
  END IF;

  IF (SELECT pkg_list_alegperioada_optiunea4.WME_RESULT FROM pkg_list_alegperioada_optiunea4(NULL,NULL)) THEN
    sSelMonet := '
      UNION ALL
      SELECT
        coddoc NAV_CodDoc, coddoc1 NAV_CodDoc1, tipdoc NAV_TipDoc, doc DOCSTINS, vallin TOTAL_DOCUMENT,
        vallin VAL_STINGATOR, vallin - tvalin VAL_STINGFTVA,
        0 VAL_REST, COEFTVA,
        0 CODSTINGATORPIF,
        0 CODSTINSPIF,
        0 SOLD_LIN,
        0 SOLD_DOC,
        1 ORDINE,
        1 ORDINEMAX,
        ROW_NUMBER()  OVER (PARTITION BY coddoc, tipdoc ORDER BY indexlocal, coddoc1) ORDDOC,
        COUNT(1)      OVER (PARTITION BY coddoc, tipdoc ) ORDDOCMAX,
        doc DOCSTINGATOR, datadoc DATADECONT, datadoc DSTINGDATA, datadoc DATAINC, datadoc DSTINSDATA, datadoc TERMEN, datadoc SCADENTA, 0 DIFZILE,
        0 DEPZILE,
        0 DEPZILEDEC,
        0 DEPZILEINC,
        codpart, agent, agent agent_inc, cont, codlocatie, curs dstinscurs, moneda,
        subunitatea substinsi, subunitatea substingatori,
        coddoc, coddoc1, tipdoc, codobiect, codobiect1, an dstinsan, luna dstinsluna, an dstingan, luna dstingluna, curs dstingcurs,
        codbanca,
        tipstoc, gestact, pretachiz, pretvanz, cant, gestden, gestsimb, furnizori
      FROM tmp_lst_urmincmon';

    sInsMonet := 'INSERT INTO tmp_lst_urmincmon (
        CODDOC1, INDEXLOCAL, CODDOC, TIPDOC, DATADOC, CODPART, CODLOCATIE, SUBUNITATEA,
        CURS, MONEDA, AGENT, INITIALIZARI, AN, LUNA, DOC,
        CODOBIECT, CODOBIECT1,
        CONT,
        VALDOC, TVADOC, VALLIN, TVALIN,
        COEFTVA,
        PRETVANZ, CANT,
        CODBANCA, TIPSTOC, GESTACT,
        PRETACHIZ, GESTDEN, GESTSIMB, FURNIZORI
      )
      SELECT
        i1.codies1 coddoc1, i1.indexlocal, i.codies coddoc, i.tipdoc, i.datadoc, Coalesce(i.partener,0) codpart, Coalesce(i.codlocatie,0) codlocatie, i.subunitatea,
        i.curs, i.moneda, Coalesce(i1.codagentemulare,0) agent, Coalesce(i.initializari,0) initializari, i.an, i.luna, i.prefixdoc||'' ''|| i.nrdoc||''/''||to_char(i.datadoc, ''dd.mm.yyyy'') doc,
        i1.codobiect, o1.codobiect1,
        i1.contserv cont,
        i.valdoc, i.tvadoc, i1.pu * i1.cant + coalesce(i1.valdiscpret,0) vallin, i1.tva tvalin,
        CASE WHEN I1.PU * I1.CANT+I1.TVA &lt;&gt; 0 THEN (I1.PU * I1.CANT - I1.TVA)/(I1.PU * I1.CANT) ELSE 1 END COEFTVA,
        i1.pu - CASE WHEN i1.cant = 0 THEN 0 ELSE i1.tva/i1.cant END pretvanz, i1.cant,
        0 codbanca, CASE WHEN i1.tiplinie = ''='' THEN 1 ELSE 0 END tipstoc, i1.gestact,
        0 PRETACHIZ, NULL GESTDEN, NULL GESTSIMB, NULL FURNIZORI
      FROM iesiri i
        INNER JOIN iesiri1  i1 ON i1.codies    = i.codies
        LEFT  JOIN nartobj1 o1 ON o1.codobiect = i1.codobiect AND ' || coalesce(AnLunaLucru::varchar,'') || ' BETWEEN o1.ALStart and o1.ALStop
--                  (
--                   SELECT codobiect, Max(codobiect1) codobiect1  -- KEEP (DENSE_RANK LAST ORDER BY anstart*12+lunastart) codobiect1
--                   FROM (SELECT codobiect, codobiect1, dense_rank() over(ORDER BY anstart*12+lunastart desc) NR
--                         FROM nartobj1
--                         WHERE anstart*12+lunastart &lt;= ' || coalesce(AnLunaLucru::varchar,'') || '
--                        ) aa
--                   WHERE NR=1
--                   GROUP BY codobiect
--                  ) o1 ON o1.codobiect = i1.codobiect
      WHERE Coalesce(i.anulat, 0) = 0 AND Coalesce(i.initializari, 0) = 0
        AND I.TIPDOC = 16
        AND i.datadoc BETWEEN TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'') AND TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')
        AND Coalesce(i1.codobiect,0) &lt;&gt; 0' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL)),'');

    PERFORM LIST_EXECUTE_IMMEDIATE(sInsmonet, aListID, aListVer);
    PERFORM LIST_EXECUTE_IMMEDIATE('UPDATE tmp_lst_urmincmon t' || coalesce(sUpdateMan,''), aListID, aListVer);
  END IF;

  sSelectMan := coalesce(sSelectMan,'') || '
    SELECT
       o.CodObligPIF, o.Codgeneral, t.codtrezor CodDoc, t1.codtrezor1 CodDoc1, g.TipDoc, GS.CODDOC CodDocS, GS.TIPDOC TipDocS,
       t1.doc||'' ''||t1.nrdoc||''/''||to_char(t1.datadoc, ''dd.mm.yyyy'') DOCSTINGATOR,
       t1.datadecont, t1.datadoc, t1.datadoc DATAINC, t1.agent, t.Subunitatea, s.codstinspif, s.valoare, s.valoare-Coalesce(g.tva,0) valftva,
       Coalesce(NULLIF(t1.curs,0),1) curs, COALESCE(t.monedapers, bc.codmoneda, 0) moneda, t.an, t.luna, t.codbanca
     FROM trezor1          t1
       INNER JOIN trezor   t  ON t1.codtrezor      = t.codtrezor
       INNER JOIN general  g  ON g.tipdoc          = t.tipdoc AND g.coddoc = t1.codtrezor1
       INNER JOIN obligpif o  ON o.codgeneral      = g.codgeneral
       INNER JOIN stingere s  ON s.codstingatorpif = o.codobligpif
       INNER JOIN OBLIGPIF OS ON OS.CODOBLIGPIF    = S.CODSTINSPIF
       INNER JOIN GENERAL  GS ON GS.CODGENERAL     = OS.CODGENERAL
       LEFT JOIN nbankcont bc ON bc.codbankcont    = t.codbanca
     WHERE T.TIPDOC IN (29,30,33' || coalesce(sAUX1,'') || ')
       AND T1.DATADOC BETWEEN TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'') AND TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')
       AND g.semnificatie IN (400,420,750,751)
       AND s.valoare &lt;&gt; 0
     UNION ALL
     SELECT
       o.CodObligPIF, o.Codgeneral, c.codcompens CodDoc, NULL CodDoc1, g.TipDoc, GS.CODDOC CodDocS, GS.TIPDOC TipDocS,
       ''PV''||'' ''||c.nrdoc||''/''||to_char(c.datadoc, ''dd.mm.yyyy'') DOCSTINGATOR,
       null DATADECONT, c.datadoc, c.datadoc DATAINC, 0 Agent, c.Subunitatea, s.codstinspif, s.valoare, s.valoare-Coalesce(g.tva,0) valftva,
       Coalesce(NULLIF(g.curs,0),1) curs, Coalesce(g.moneda,0) moneda, c.an, c.luna, 0 codbanca
     FROM compens          c
       INNER JOIN general  g  ON G.TipDoc          = 28 AND g.coddoc = c.codcompens
       INNER JOIN obligpif o  ON o.codgeneral      = g.codgeneral
       INNER JOIN stingere s  ON s.codstingatorpif = o.codobligpif
       INNER JOIN obligpif os ON os.codobligpif    = s.codstinspif
       INNER JOIN GENERAL  GS ON GS.CODGENERAL     = OS.CODGENERAL
     WHERE C.DATADOC BETWEEN TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'') AND TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')
       AND OS.SEMNIFICATIE NOT IN (410)
       AND s.valoare &lt;&gt; 0
     UNION ALL
     --stef pentru ca emulare nu are obligpif unic asociat direct fac eu un nr negativ unic, pentru e evita repetiitiile si dublarea liniilor
     SELECT
       -1-(ROW_NUMBER() OVER()) *100  CodObligPIF, 0 Codgeneral, e.codemulare CodDoc, NULL CodDoc1, 64 TipDoc, I.CodIes CodDocS, I.TipDoc TipDocS,
       ''BON''||'' '' ||e.nrbon||''/''||to_char(e.databon, ''dd.mm.yyyy'') DOCSTINGATOR,
       e.databon DATADECONT, e.databon DATADOC, e.databon DATAINC, 0 Agent, i.Subunitatea, o.codobligpif codstinspif, es.valoare,(e.valoare-e.tvatotal)*es.valoare/e.valoare valftva,
       Coalesce(NULLIF(i.curs,0),1) curs, Coalesce(i.moneda,0) moneda, i.an, i.luna, 0 codbanca
     FROM emulare              e
       INNER JOIN emulare1     e1 on e1.codemulare       = e.codemulare
       INNER JOIN emulstingeri es ON es.codemulstingere = e1.codemulstingere
       INNER JOIN obligpif     o  ON o.codobligpif       = es.codobligpif
       INNER JOIN general      g  ON g.codgeneral       = o.codgeneral
       INNER JOIN iesiri       i  ON  g.coddoc           = i.codies AND g.tipdoc = i.tipdoc
     WHERE E.DATABON BETWEEN TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'') AND TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')
       AND es.valoare &lt;&gt; 0
       AND e.valoare &lt;&gt; 0
       AND NOT o.semnificatie in (210,211)
     UNION ALL
     SELECT
       -2-(ROW_NUMBER() OVER()) *100 CodObligPIF, 0 Codgeneral, e.codemulare CodDoc, NULL CodDoc1, 64 TipDoc, I.CodIes CodDocS, I.TipDoc TipDocS,
       ''BON''||'' '' ||e.nrbon||''/''||to_char(e.databon, ''dd.mm.yyyy'') DOCSTINGATOR,
       e.databon DATADECONT, e.databon DATADOC, e.databon DATAINC, 0 Agent, i.Subunitatea, o.codobligpif codstinspif, e.valoare, e.valoare-e.tvatotal valftva,
       Coalesce(NULLIF(i.curs,0),1) curs, Coalesce(i.moneda,0) moneda, i.an, i.luna, 0 codbanca
     FROM emulare e
       INNER JOIN iesiri   i ON i.codies     = e.codies
       INNER JOIN general  g ON g.coddoc     = i.codies AND g.tipdoc = i.tipdoc
       INNER JOIN obligpif o ON o.codgeneral = g.codgeneral
     WHERE E.DATABON BETWEEN TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'') AND TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')
       AND e.valoare &lt;&gt; 0 and not o.semnificatie in (210,211)';

  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsertman,'') || coalesce(sSelectman,''), aListID, aListVer);

  sInsertMan := 'INSERT INTO tmp_lst_stinsi(
      codobligstingator, coddoc1, indexlocal, coddoc, tipdoc, codgeneral, codobiect, codobiect1, initializari,
      docstins, datadoc, subunitatea, curs, moneda, codobligpif,
      valoarelinie, valdoc,
      valobliglinie,
      coeftva,
      valoare, codpart, codlocatie, termen, agent, cont, an, luna, codbanca,
      tipstoc, gestact, pretvanz, cant, infocm)';

  sSelectMan := '
    SELECT
      codobligstingator, coddoc1, indexlocal, coddoc, tipdoc, codgeneral, codobiect, codobiect1, initializari,
      docstins, datadoc, subunitatea, curs, moneda, codobligpif,
      valoarelinie, valdoc,';

  IF  NOT (SELECT pkg_list_alegperioada_optiunea4.WME_RESULT FROM pkg_list_alegperioada_optiunea4(NULL,NULL)) THEN
    sSelectMan := coalesce(sSelectMan,'') || '
      CASE
        WHEN INFOCM = 1                  THEN 0
        WHEN CODOBLIGSTINGATOR &lt; 0       THEN VALOARELINIE
        WHEN valoare = 0 AND infocm &lt;&gt; 1 THEN 0
        WHEN valoarelinie = 0            THEN 0
        WHEN Sum( valoarelinie ) OVER (PARTITION BY codobligstingator, codobligpif) = 0 THEN 0
        ELSE valoarelinie * valoare/ Sum( valoarelinie ) OVER (PARTITION BY codobligstingator, codobligpif)
      END valobliglinie,
      COEFTVA,
      CASE WHEN CODOBLIGSTINGATOR &lt; 0 THEN VALDOC ELSE VALOARE END valoare, ';
  ELSE
    sSelectMan := coalesce(sSelectMan,'') || '
      CASE
        WHEN CODOBLIGSTINGATOR = 0       THEN 0
        WHEN INFOCM = 1                  THEN 0
        WHEN CODOBLIGSTINGATOR &lt; 0       THEN VALOARELINIE
        WHEN valoare = 0 AND infocm &lt;&gt; 1 THEN 0
        WHEN valoarelinie = 0            THEN 0
        WHEN Sum( valoarelinie ) OVER (PARTITION BY codobligstingator, codobligpif) = 0 THEN 0
        ELSE valoarelinie * valoare/ Sum( valoarelinie ) OVER (PARTITION BY codobligstingator, codobligpif)
      END valobliglinie,
      COEFTVA,
      CASE WHEN CODOBLIGSTINGATOR = 0 THEN 0 ELSE VALOARE END VALOARE, ';
  END IF;

  sSelectMan := coalesce(sSelectMan,'') || '
      codpart, codlocatie, termen, agent, cont, an, luna, codbanca,
      tipstoc, gestact, pretvanz, cant, infocm
    FROM (
      SELECT
        STG.CODOBLIGPIF CODOBLIGSTINGATOR, i1.codies1 coddoc1, i1.indexlocal, i.codies coddoc, i.tipdoc, o.codgeneral, i1.codobiect, o1.codobiect1, 0 initializari,
        i.prefixdoc||'' ''|| i.nrdoc||''/''||to_char(i.datadoc, ''dd.mm.yyyy'') docstins, i.datadoc, i.subunitatea, Coalesce(NULLIF(g.curs,0),1) curs, Coalesce(g.moneda,0) moneda, o.codobligpif,
        (i1.pu*i1.cant+CASE WHEN i.tipdoc = 21 THEN 0 ELSE i1.tva END)*Coalesce(i1.coefdiscmaj,1)*CASE i1.pu WHEN i1.pretorig THEN 1 WHEN 0 THEN 0 ELSE i1.pretorig/i1.pu END valoarelinie, i.valdoc, Coalesce(i.infocm,0) infocm,
        CASE
          WHEN i.tipdoc =  21 AND I1.PU * I1.CANT        &lt;&gt; 0 THEN (I1.PU * I1.CANT-I1.TVA)/(I1.PU * I1.CANT)
          WHEN i.tipdoc &lt;&gt; 21 AND I1.PU * I1.CANT+I1.TVA &lt;&gt; 0 THEN (I1.PU * I1.CANT)/(I1.PU * I1.CANT+I1.TVA)
          ELSE 1
        END COEFTVA,
        o.valoare, o.codpart, i.codlocatie, o.termen, i.agent, PKG_LIST_BASE_UTILS_icont_CodCont(o.icont,o.codpart,i.an*12+i.luna,o.semnificatie) cont, i.an, i.luna, 0 codbanca,
        CASE WHEN i1.tiplinie = ''='' THEN 1 ELSE 0 END tipstoc, i1.gestact, i1.pu - CASE WHEN i1.cant = 0 THEN 0 WHEN i.tipdoc &lt;&gt; 21 THEN 0 ELSE i1.tva/i1.cant END pretvanz, i1.cant,
        Coalesce(O.CodCentru,0) CodCentruO, Coalesce(i1.codcentru,0) CodCentruI, Max(Coalesce(O.CodCentru,0)) OVER (PARTITION BY i.codies) CodCentruM
      FROM iesiri           i
        INNER JOIN general  g  ON g.coddoc     = i.codies and g.tipdoc = i.tipdoc
        INNER JOIN obligpif o  ON g.codgeneral = o.codgeneral
        LEFT JOIN iesiri1   i1 ON i.codies     = i1.codies
        ' || coalesce(sTipJoin,'') || ' JOIN TMP_AUX_STINGATORI STG ON STG.CODSTINSPIF = O.CODOBLIGPIF OR (STG.CODDOCS = I.CODIES AND STG.TIPDOCS = I.TIPDOC AND STG.CODSTINSPIF IS NULL)
        LEFT JOIN nartobj1 o1 ON o1.codobiect = i1.codobiect AND ' || coalesce(AnLunaLucru::varchar,'') || ' BETWEEN o1.ALStart and o1.ALStop
--                  (
--                   SELECT codobiect, Max(codobiect1) codobiect1  -- KEEP (DENSE_RANK LAST ORDER BY anstart*12+lunastart) codobiect1
--                   FROM (SELECT codobiect, codobiect1, dense_rank() over(ORDER BY anstart*12+lunastart desc) NR
--                         FROM nartobj1
--                         WHERE anstart*12+lunastart &lt;= ' || coalesce(AnLunaLucru::varchar,'') || '
--                        ) aaa
--                   WHERE NR=1
--                   GROUP BY codobiect
--                  ) o1 ON o1.codobiect = i1.codobiect
      WHERE Coalesce(i.anulat, 0) = 0 AND Coalesce(i.initializari, 0) = 0
        AND I.TIPDOC IN (16,19,21,22,26)
        AND i.datadoc &lt;= TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')
        AND Coalesce(i1.codobiect,0) &lt;&gt; 0
        AND g.semnificatie NOT IN (210, 211, 240, 500) ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL)),'');

  sSelectMan := coalesce(sSelectMan,'') || '
    ) A_PG
    WHERE CodCentruO = CASE WHEN CodCentruM = 0 THEN 0 ELSE CodCentruI END';

  sInsAux := 'INSERT INTO tmp_aux_stingatori(CODOBLIGPIF, CODDOC, CODDOC1, TIPDOC, CODSTINSPIF, CODDOCS, TIPDOCS)
    SELECT CODOBLIGPIF, CODDOC, CODDOC1, TIPDOC, CODSTINSPIF, CODDOCS, TIPDOCS
    FROM tmp_lst_stingatori
    WHERE TIPDOCS IN (16,19,21,22,26)';

  PERFORM LIST_EXECUTE_IMMEDIATE('TRUNCATE TABLE tmp_aux_stingatori', aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsAux, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsertman,'') || coalesce(sSelectman,''), aListID, aListVer);

  sSelectMan := '
    SELECT
      STG.CODOBLIGPIF CODOBLIGSTINGATOR, 0 coddoc1, 0 indexlocal, i.codies coddoc, i.tipdoc, o.codgeneral, -1 codobiect, 0 codobiect1, 1 initializari,
      i.prefixdoc||'' ''||i.nrdoc||''/''||to_char(i.datadoc, ''DD.MM.YYYY'') docstins, i.datadoc, i.subunitatea, Coalesce(NULLIF(g.curs,0),1) curs, Coalesce(g.moneda,0) moneda, o.codobligpif,
      o.valoare + Coalesce(CECINI.VALOARE,0) valoarelinie, o.valoare + Coalesce(CECINI.VALOARE,0) valdoc,
      o.valoare + Coalesce(CECINI.VALOARE,0) valobliglinie,
      1 COEFTVA,
      o.valoare + Coalesce(CECINI.VALOARE,0) valoare, o.codpart, i.codlocatie, o.termen, i.agent, PKG_LIST_BASE_UTILS_icont_CodCont(o.icont,o.codpart,' || coalesce(AnLunaIni::varchar,'') || ',o.semnificatie) cont, i.an, i.luna, 0 codbanca,
      0 tipstoc, 0 gestact, 0 pretvanz, 0 cant, i.infocm
    FROM iesiri           i
      INNER JOIN general  g ON g.tipdoc     = i.tipdoc AND g.coddoc = i.codies
      INNER JOIN obligpif o ON g.codgeneral = o.codgeneral
      ' || coalesce(sTipJoin,'') || ' JOIN tmp_lst_stingatori STG ON STG.CODSTINSPIF = O.CODOBLIGPIF
      LEFT JOIN (
                 SELECT S.CODSTINSPIF, SUM(ST.VALOARE) VALOARE
                 FROM STINGERE S
                      INNER JOIN OBLIGPIF ST     ON S.CODSTINGATORPIF  = ST.CODOBLIGPIF
                      INNER JOIN GENERAL  GST    ON GST.CODGENERAL     = ST.CODGENERAL
                      INNER JOIN TREZOR1  T1     ON T1.CODTREZOR1      = GST.CODDOC
                      INNER JOIN TREZOR   T      ON T1.CODTREZOR       = T.CODTREZOR AND GST.TIPDOC = T.TIPDOC
                      INNER JOIN OBLIGPIF OSTINS ON OSTINS.CODOBLIGPIF = S.CODSTINSPIF
                      INNER JOIN GENERAL  GSTINS ON GSTINS.CODGENERAL  = OSTINS.CODGENERAL AND GSTINS.SEMNIFICATIE &lt;&gt; 500 AND GSTINS.SEMNIFICATIE &lt;&gt; 240
                      INNER JOIN IESIRI   IES    ON IES.CODIES         = GSTINS.CODDOC AND IES.TIPDOC = GSTINS.TIPDOC
                 WHERE Coalesce(IES.anulat, 0) = 0 and Coalesce(IES.initializari, 0) = 1 AND IES.datadoc &lt;= TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'')' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'IES',NULL,NULL,NULL)),'') || '
                       AND NOT IES.TIPDOC IN (14,15,16,20,23,24)
                       AND GST.semnificatie IN (400,420,750,751)
                       AND GST.TIPDOC = 31
                       AND T1.DATADOC &lt; TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'')
                       AND Coalesce(T1.INITIALIZARI,0) = 1
                 GROUP BY CODSTINSPIF
                ) CECINI ON CECINI.CODSTINSPIF = O.CODOBLIGPIF
    WHERE Coalesce(i.anulat, 0) = 0 AND Coalesce(i.initializari, 0) = 1
      AND I.TIPDOC IN (16,19,21,22,26)
      AND i.datadoc &lt;= TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'')
      AND NOT g.semnificatie IN (240, 500)' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL)),'');

  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsertman,'') || coalesce(sSelectman,''), aListID, aListVer);

  sSelectMan := '
    SELECT
      STG.CODOBLIGPIF CODOBLIGSTINGATOR, nc1.codnc1 CodDoc1, nc1.indexlocal, NC.CodNc CodDoc, g.TipDoc, o.codgeneral, -3 codobiect, 0 codobiect1, 0 initializari,
      ''NC ''  ||nc.nrdoc||''/''||to_char(nc.datadoc, ''dd.mm.yyyy'') docstins, nc.datadoc, nc.subunitatea, Coalesce(NULLIF(g.curs,0),1) curs, g.moneda, o.codobligpif,
      o.valoare valoarelinie, o.valoare valdoc,
      o.valoare valobliglinie,
      CASE WHEN Coalesce(o.valoare,0) = 0 THEN 1 ELSE (o.valoare-Coalesce(g.tva,0))/o.valoare END COEFTVA,
      o.valoare, o.codpart, 0 codlocatie, o.termen, nc1.agent, PKG_LIST_BASE_UTILS_icont_CodCont(o.icont,o.codpart,nc1.an*12+nc1.luna,o.semnificatie) cont, nc.An, nc.Luna, 0 codbanca,
      0 tipstoc, 0 gestact, 0 pretvanz, 0 cant, 0 infocm
    FROM nc
      INNER JOIN          nc1 ON nc1.codnc = nc.codnc
      INNER JOIN general  g   ON g.coddoc = nc1.codnc1 AND g.tipdoc = 35
      INNER JOIN obligpif o   ON g.codgeneral = o.codgeneral
      ' || coalesce(sTipJoin,'') || ' JOIN tmp_lst_stingatori STG ON STG.CODSTINSPIF = O.CODOBLIGPIF
    WHERE nc.datadoc &lt;= TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')
          AND g.semnificatie = 1200' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'nc',NULL,NULL,NULL)),'');

  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsertman,'') || coalesce(sSelectman,''), aListID, aListVer);

  sSelectMan := '
    SELECT
      STG.CODOBLIGPIF CODOBLIGSTINGATOR, NULL CodDoc1, 0 IndexLocal, c.CodCompens CodDoc, g.TipDoc, o.codgeneral, -4 codobiect, 0 codobiect1, 0 initializari,
      ''PV '' ||c.nrdoc||''/''||to_char(c.datadoc, ''dd.mm.yyyy'') docstins, c.datadoc, c.subunitatea, Coalesce(NULLIF(g.curs,0),1) curs, g.moneda, o.codobligpif,
      o.valoare valoarelinie, o.valoare valdoc,
      o.valoare valobliglinie,
      CASE WHEN Coalesce(o.valoare,0) = 0 THEN 1 ELSE (o.valoare-Coalesce(g.tva,0))/o.valoare END COEFTVA,
      o.valoare, o.codpart, 0 codlocatie, o.termen, c.agent, PKG_LIST_BASE_UTILS_icont_CodCont(o.icont,o.codpart,c.an*12+c.luna,o.semnificatie) cont, c.An, c.Luna, 0 codbanca,
      0 tipstoc, 0 gestact, 0 pretvanz, 0 cant, 0 infocm
    FROM compens          c
      INNER JOIN general  g ON g.coddoc     = c.codcompens AND g.tipdoc = 28
      INNER JOIN obligpif o ON g.codgeneral = o.codgeneral
      ' || coalesce(sTipJoin,'') || ' JOIN tmp_lst_stingatori STG ON STG.CODSTINSPIF = O.CODOBLIGPIF
    WHERE c.datadoc &lt;= TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')';

  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsertman,'') || coalesce(sSelectman,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE('DELETE FROM tmp_lst_stinsi WHERE (valobliglinie = 0 OR valoare = 0) and codobligstingator &lt; 0', aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE('UPDATE tmp_lst_stinsi t' || coalesce(sUpdateMan,''), aListID, aListVer);

  IF (SELECT pkg_list_alegperioada_optiunea3.WME_RESULT FROM pkg_list_alegperioada_optiunea3(NULL,NULL)) THEN
    sUpd1 := 'Coalesce(Sum(CASE WHEN Coalesce(t1.initializari,0) = 1 AND gs.tipdoc = 31 THEN OS.VALOARE ELSE s.valoare END),0)';
  ELSE
    sUpd1 := 'Coalesce(Sum(CASE WHEN gs.tipdoc = 31 AND tx.codtrezor IS NULL THEN 0 WHEN Coalesce(t1.initializari,0) = 1 AND gs.tipdoc = 31 THEN OS.VALOARE ELSE s.valoare END),0)';
    sUpd2 := '
                  LEFT JOIN general  gc  ON gc.coddoc      = gs.coddoc AND gc.semnificatie = 600 AND gc.semnificatie &lt;&gt; gs.semnificatie
                  LEFT JOIN obligpif oc  ON oc.codgeneral  = gc.codgeneral
                  LEFT JOIN stingere sc  ON sc.codstinspif = Coalesce(oc.codobligpif, os.codobligpif)
                  LEFT JOIN obligpif ox  ON ox.codobligpif = sc.codstingatorpif
                  LEFT JOIN general  gx  ON gx.codgeneral  = ox.codgeneral
                  LEFT JOIN trezor1  t1x ON t1x.codtrezor1 = gx.coddoc
                  LEFT JOIN trezor   tx  ON t1x.codtrezor  = tx.codtrezor AND t1x.datadoc &lt; TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'')';
  END IF;

  sUpdateMan := 'UPDATE tmp_lst_stinsi man
    SET rest = valdoc -
               (SELECT ' || coalesce(sUpd1,'') || '
                FROM general          g
                  INNER JOIN obligpif o  on o.codgeneral   = g.codgeneral
                  INNER JOIN stingere s  ON s.codstinspif  = o.codobligpif
                  INNER JOIN obligpif os ON os.codobligpif = s.codstingatorpif
                  INNER JOIN general  gs ON gs.codgeneral  = os.codgeneral
                  LEFT  JOIN trezor1  t1 on gs.coddoc      = t1.codtrezor1 AND gs.tipdoc &lt;&gt; 28 AND t1.datadoc &lt; TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'')
                  LEFT  JOIN compens  c  ON gs.coddoc      = c.codcompens  AND gs.tipdoc = 28  AND c.datadoc  &lt; TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'')' || coalesce(sUpd2,'') || '
                WHERE g.coddoc = man.coddoc AND g.tipdoc = man.tipdoc AND Coalesce(t1.codtrezor,c.codcompens) IS NOT NULL)';

  PERFORM LIST_EXECUTE_IMMEDIATE(supdateman, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE('UPDATE tmp_lst_stinsi SET restlinie = CASE WHEN Coalesce(valdoc,0) = 0 THEN 0 ELSE rest*valoarelinie/valdoc END', aListID, aListVer);

  sInsert := 'INSERT INTO ' || coalesce(tmpName,'') || '(
      NAV_CodDoc, NAV_CodDoc1, NAV_TipDoc,
      DOCSTINS, TOTAL_DOCUMENT, VAL_NESTINSA_DOCUMENT, VAL_STINGATOR, VAL_STINGFTVA,
      DOCSTINGATOR, PARTENER, LOCATIE,
      SOLD_LIN, SOLD_LINF, ORDINE,
      SOLD_DOC, SOLD_DOCF, ORDDOC,
      DATADECONT, DATA, DATAINC, DATA_STINS, TERMEN, MONEDA, SUBUNITATEA, SUBUNITATEA_ST, SCADENTA, DIFZILE,
      INC_VAL1, INC_VAL2, INC_VAL3, INC_VAL4, INC_VAL5, INC_VAL_0_7, INC_VAL_8_21, INC_VAL_22_40, INC_VAL_61_70, INC_VAL_61_75, INC_VAL_71_85, INC_VAL_40p, INC_VAL_75p, INC_VAL_85p, INC_VAL_0_75,
      DEPZILE, DEPZILEDEC, DEPZILEINC, AGENT, AGENT_INCASATOR, CONT,
      ARTICOL,
      CODEXTERN, CODINTERN, PRODUCATOR, CLASAARTICOL,
      DISCTER,
      DSTINSCURS, DSTINSAN, DSTINSLUNA, DSTINGCURS, DSTINGAN, DSTINGLUNA,
      GESTDEN, GESTSIMB, FURNIZORI, NRCONT, PRETACHIZ,PRETVANZ,CANT,
      DSTINSCURS_REF, DSTINGCURS_REF, DSTINSCURS_PREST, DSTINGCURS_PREST' || coalesce(gUserFields,'') || ')';

  sSelect := '
    WITH UN AS (
      SELECT
        stingatori.coddoc NAV_CodDoc, stingatori.coddoc1 NAV_CodDoc1, stingatori.tipdoc NAV_TipDoc, stinsi.DOCSTINS, stinsi.valoarelinie TOTAL_DOCUMENT,
        sign(stinsi.valoare) * Coalesce(stingatori.valoare,0)*stinsi.valobliglinie/Coalesce(NULLIF(stinsi.valoare,0),1) VAL_STINGATOR,
        sign(stinsi.valoare) * Coalesce(stingatori.valftva,0)*stinsi.valobliglinie/Coalesce(NULLIF(stinsi.valoare,0),1) VAL_STINGFTVA,
        stinsi.restlinie VAL_REST, stinsi.coeftva, stingatori.codobligpif codstingatorpif, stinsi.codobligpif codstinspif,
        stinsi.restlinie -
        SUM(Coalesce(sign(stinsi.valoare)*Coalesce(stingatori.valoare,0)*stinsi.valobliglinie/Coalesce(NULLIF(stinsi.valoare,0),1),0))
        OVER (PARTITION BY stinsi.coddoc, stinsi.tipdoc, stinsi.coddoc1 ORDER BY stinsi.termen, stinsi.codobligpif, stingatori.codobligpif ROWS BETWEEN unbounded preceding AND CURRENT ROW) SOLD_LIN,
        stinsi.rest -
        SUM(Coalesce(sign(stinsi.valoare)*Coalesce(stingatori.valoare,0)*stinsi.valobliglinie/Coalesce(NULLIF(stinsi.valoare,0),1),0))
        OVER (PARTITION BY stinsi.coddoc, stinsi.tipdoc ORDER BY stinsi.indexlocal, stinsi.coddoc1, stinsi.termen, stinsi.codobligpif, stingatori.codobligpif ROWS BETWEEN unbounded preceding AND CURRENT ROW) SOLD_DOC,
        ROW_NUMBER() OVER (PARTITION BY stinsi.coddoc, stinsi.tipdoc, stinsi.coddoc1 ORDER BY stinsi.termen, stinsi.codobligpif, stingatori.codobligpif) ORDINE,
        COUNT(1)     OVER (PARTITION BY stinsi.coddoc, stinsi.tipdoc, stinsi.coddoc1) ORDINEMAX,
        ROW_NUMBER() OVER (PARTITION BY stinsi.coddoc, stinsi.tipdoc ORDER BY stinsi.indexlocal, stinsi.coddoc1, stinsi.termen, stinsi.codobligpif, stingatori.codobligpif) ORDDOC,
        COUNT(1)     OVER (PARTITION BY stinsi.coddoc, stinsi.tipdoc) ORDDOCMAX,
        stingatori.DOCSTINGATOR, stingatori.DATADECONT, stingatori.datadoc DSTINGDATA, stingatori.DATAINC, stinsi.datadoc DSTINSDATA, stinsi.TERMEN, stinsi.termen SCADENTA, trunc(stingatori.datadoc - stinsi.datadoc) DIFZILE,
        CASE WHEN trunc(stingatori.datadoc - stinsi.termen) &gt; 0 then trunc(stingatori.datadoc - stinsi.termen) ELSE 0 END DEPZILE,
        CASE WHEN trunc(COALESCE(stingatori.datadecont,stingatori.datadoc) - stinsi.termen) &gt; 0 then trunc(COALESCE(stingatori.datadecont,stingatori.datadoc) - stinsi.termen) ELSE 0 END DEPZILEDEC,
        CASE WHEN trunc(stingatori.datainc - stinsi.termen) &gt; 0 then trunc(stingatori.datainc - stinsi.termen) ELSE 0 END DEPZILEINC,
        stinsi.codpart, Coalesce(stinsi.agent,0) agent, Coalesce(stingatori.agent,0) agent_inc, stinsi.cont, Coalesce(stinsi.codlocatie,0) codlocatie, stinsi.curs dstinscurs, stinsi.moneda,
        stinsi.subunitatea substinsi, stingatori.subunitatea substingatori,
        stinsi.coddoc, stinsi.coddoc1, stinsi.tipdoc, stinsi.codobiect, stinsi.codobiect1, stinsi.an dstinsan, stinsi.luna dstinsluna, stingatori.an dstingan, stingatori.luna dstingluna, stingatori.curs dstingcurs,
        CASE WHEN stinsi.codobiect = -2 THEN stinsi.codbanca ELSE stingatori.codbanca END codbanca,
        stinsi.TIPSTOC, stinsi.GESTACT, stinsi.PRETACHIZ, stinsi.PRETVANZ, stinsi.CANT, stinsi.GESTDEN, stinsi.GESTSIMB, stinsi.FURNIZORI
      FROM tmp_lst_stinsi stinsi ' || coalesce(sTipJoin,'') || ' JOIN tmp_lst_stingatori stingatori ON stingatori.CODOBLIGPIF = stinsi.CODOBLIGSTINGATOR' || coalesce(sWhereUN,'') || coalesce(sSelMonet,'') || '
    )
    SELECT
      CASE WHEN ts.codsubunit IS NOT NULL THEN UN.NAV_CodDoc END NAV_CodDoc, CASE WHEN ts.codsubunit IS NOT NULL THEN UN.NAV_CodDoc1 END NAV_CodDoc1, CASE WHEN ts.codsubunit IS NOT NULL THEN UN.NAV_TipDoc END NAV_TipDoc,
      UN.DOCSTINS, CASE WHEN UN.ORDINE = 1 THEN UN.TOTAL_DOCUMENT ELSE 0 END TOTAL_DOCUMENT, UN.SOLD_LIN + UN.VAL_STINGATOR VAL_NESTINSA_DOCUMENT, UN.VAL_STINGATOR, UN.VAL_STINGATOR * UN.COEFTVA VAL_STINGFTVA,
      UN.DOCSTINGATOR, NPART.DEN_PART, AG.OBS,
      UN.SOLD_LIN, CASE WHEN UN.ORDINE = UN.ORDINEMAX THEN UN.SOLD_LIN ELSE 0 END SOLD_LINF, UN.ORDINE,
      UN.SOLD_DOC, CASE WHEN UN.ORDDOC = UN.ORDDOCMAX THEN UN.SOLD_DOC ELSE 0 END SOLD_DOCF, UN.ORDDOC,
      UN.DATADECONT, UN.DSTINGDATA as DATA, UN.DATAINC, UN.DSTINSDATA DATA_STINS, UN.TERMEN, MON.DEN_MONEDA, SUBSTINSI.DEN_SUBUNIT SUBUNITATEA, SUBSTINGATORI.DEN_SUBUNIT SUBUNITATEA_ST, UN.SCADENTA, UN.DIFZILE,
      CASE WHEN UN.DIFZILE &lt;=              1 THEN UN.VAL_STINGATOR ELSE 0 END INC_VAL1,
      CASE WHEN UN.DIFZILE BETWEEN  2 AND 30 THEN UN.VAL_STINGATOR ELSE 0 END INC_VAL2,
      CASE WHEN UN.DIFZILE BETWEEN 31 AND 45 THEN UN.VAL_STINGATOR ELSE 0 END INC_VAL3,
      CASE WHEN UN.DIFZILE BETWEEN 46 AND 60 THEN UN.VAL_STINGATOR ELSE 0 END INC_VAL4,
      CASE WHEN UN.DIFZILE &gt;              60 THEN UN.VAL_STINGATOR ELSE 0 END INC_VAL5,
      CASE WHEN UN.DIFZILE BETWEEN  0 AND  7 THEN UN.VAL_STINGATOR ELSE 0 END INC_VAL_0_7,
      CASE WHEN UN.DIFZILE BETWEEN  8 AND 21 THEN UN.VAL_STINGATOR ELSE 0 END INC_VAL_8_21,
      CASE WHEN UN.DIFZILE BETWEEN 22 AND 40 THEN UN.VAL_STINGATOR ELSE 0 END INC_VAL_22_40,
      CASE WHEN UN.DIFZILE BETWEEN 61 AND 70 THEN UN.VAL_STINGATOR ELSE 0 END INC_VAL_61_70,
      CASE WHEN UN.DIFZILE BETWEEN 61 AND 75 THEN UN.VAL_STINGATOR ELSE 0 END INC_VAL_61_75,
      CASE WHEN UN.DIFZILE BETWEEN 71 AND 85 THEN UN.VAL_STINGATOR ELSE 0 END INC_VAL_71_85,
      CASE WHEN UN.DIFZILE &gt;              40 THEN UN.VAL_STINGATOR ELSE 0 END INC_VAL_40p,
      CASE WHEN UN.DIFZILE &gt;              75 THEN UN.VAL_STINGATOR ELSE 0 END INC_VAL_75p,
      CASE WHEN UN.DIFZILE &gt;              85 THEN UN.VAL_STINGATOR ELSE 0 END INC_VAL_85p,
      CASE WHEN UN.DIFZILE &lt;              75 THEN UN.VAL_STINGATOR ELSE 0 END INC_VAL_0_75,
      UN.DEPZILE, UN.DEPZILEDEC, UN.DEPZILEINC, NUMEPRENUME(agent.nume,agent.prenume) AGENT, NUMEPRENUME(agent_inc.nume,agent_inc.prenume) AGENT_INCASATOR, nc.simbol CONT,
      CASE un.codobiect WHEN -1 THEN ''INITIALIZARE'' WHEN -2 THEN ''AVANS TREZORERIE'' WHEN -3 THEN ''NOTE CONTABILE'' WHEN -4 THEN ''COMPENSARI'' ELSE o.denumire END,
      O.CODEXTERN, O.CODINTERN, PROD.DEN_PART, CA.DEN_CLASEA ,
      CASE WHEN Coalesce(UN.VAL_STINGATOR,0) &gt; 0 THEN (Select wme_result from pkg_notecredit_GETDISCTERMENCLI(null,to_char(UN.DSTINGDATA,''dd.mm.yyyy''), UN.DIFZILE::numeric, pkg_list_base_urmincart_getcodcontract(UN.CODPART, UN.DSTINSDATA), UN.CODDOC1, UN.VAL_STINGATOR )) END DISCTER,
      UN.DSTINSCURS, UN.DSTINSAN, UN.DSTINSLUNA, UN.DSTINGCURS, UN.DSTINGAN, UN.DSTINGLUNA,
      Coalesce(UN.GESTDEN,G1.DEN_GEST) GESTDEN, Coalesce(UN.GESTSIMB,G1.SIMBOL) GESTSIMB, UN.FURNIZORI, BC.NRCONT, UN.PRETACHIZ, UN.PRETVANZ, UN.CANT' || coalesce(sCurs,'') || coalesce(gUserAlias,'') || '
    FROM UN
      LEFT JOIN tmp_lst_stingatori  TMP_INC       ON TMP_INC.codobligpif = UN.codstingatorpif
      LEFT JOIN tmp_lst_stinsi      TMP_DOC       ON TMP_DOC.codobligpif = UN.codstinspif and UN.coddoc1 = TMP_DOC.coddoc1 and tmp_inc.CODOBLIGPIF = tmp_doc.CODOBLIGSTINGATOR
      LEFT JOIN nartobj             o             ON o.codobiect          = un.codobiect
      LEFT JOIN npers               agent         on UN.agent            = agent.codpers
      LEFT JOIN npers               agent_inc     on UN.agent_inc        = agent_inc.codpers
      LEFT JOIN npart               npart         ON npart.codpart        = UN.codpart
      LEFT JOIN nagenda             ag            on UN.codlocatie        = ag.codagenda
      LEFT JOIN nmonede             mon           ON mon.codmoneda        = Coalesce(UN.moneda,0)
      LEFT JOIN nsubunit            SubStingatori ON UN.substingatori    = SubStingatori.codsubunit
      LEFT JOIN nsubunit            SubStinsi     ON UN.substinsi        = SubStinsi.codsubunit
      LEFT JOIN tmp_subunitdedicate ts            ON ts.codsubunit        = UN.substingatori
      LEFT JOIN npart               prod          ON prod.codpart        = o.codproducator
      LEFT JOIN nart                a             ON a.codarticol        = o.codarticol
      LEFT JOIN nclasea             ca            ON ca.codclasea        = a.clasa
      LEFT JOIN nartobj1            n1            on n1.codobiect1        = un.codobiect1
      LEFT JOIN nbankcont           bc            ON bc.codbankcont      = un.codbanca
      LEFT JOIN ngest               g1            ON g1.codgest          = un.gestact
      LEFT JOIN ncont               nc            ON nc.codcont          = un.cont' || coalesce(gSuplJoins,'');

  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmincart_setjoinuri</obj_name>
  <obj_hashval>ef15b74714eebf2a12b62b9dd7beb492</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmincart_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 05.09.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_URMINCART.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmincasaridoc_processlist</obj_name>
  <obj_hashval>f09ab06a7770aad49334ad970cf62e30</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmincasaridoc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplCols   VARCHAR := '';
  gSuplJoins  VARCHAR := '';

  VREC        RECORD;
  sInsert     varchar;
  sSelect     varchar;
  aSitV       numeric;
  aBancaV     numeric;
  aMonedaV    numeric;
  sCursRef    varchar;
  vCursRef    numeric;
  vSitVal     BOOLEAN;
begin
  --Bogdan 02.09.2020
  gSuplCols := 'nmonede mon, nsubunit sub, ';

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPART'  , 'NP'  , 'NP.CODPART   = O.CODPART',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NAGENDA', 'SSOC', 'SSOC.CODPART = O.CODPART AND SSOC.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(SSOC.INACTIV, 0) = 0');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPERS'  , 'AGP' , 'AGP.CODPERS  = SSOC.CODAGENT',NULL);

  CALL pkg_list_struct_getsuplcols( aLISTID, aLISTVER, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config('PKG_LIST_BASE_URMINCASARIDOC.gSuplCols',gSuplCols,false);

  SELECT pkg_list_base_utils_GetInfoSitValuta.WME_RESULT, pkg_list_base_utils_GetInfoSitValuta.psitvaluta ,
      pkg_list_base_utils_GetInfoSitValuta.pbancavaluta, pkg_list_base_utils_GetInfoSitValuta.pmonedavaluta
      FROM pkg_list_base_utils_GetInfoSitValuta(NULL,aSitV, aBancaV, aMonedaV) into vSitVal,aSitV,aBancaV,aMonedaV;

  sInsert := 'INSERT INTO ' || coalesce(tmpName,'')
      || '( NAV_CodDoc, NAV_TipDoc, PREFIXDOC, DATADOC, NRDOC, TERMEN, MONEDA, MAJORARE, OBLIG, INCASARE, SOLD, OBS, ORDINE, CURS_REF '
      || coalesce(gUserFields,'') || ' )';

  IF vSitVal THEN
    sCursRef := ' (select wme_result from PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null, ' || coalesce(aMonedaV::varchar,'')
                                          || ',' || coalesce(aBancaV::varchar,'') || ', to_char(I.DATADOC,''dd.mm.yyyy'')))';
  ELSE
    sCursRef := ' 1 ';
  END IF;

  sSelect := '
        SELECT G.CodDoc, G.TipDoc , I.Prefixdoc , I.Datadoc, I.Nrdoc, O.Termen,
           M.Simbol, 0 Majorare, O.Valoare, 0 Incasare, O.Valoare, I.Obs, 0 Ordine,'
          || coalesce(sCursRef,'') || coalesce(gUserAlias,'') || '
        FROM IESIRI I
          INNER JOIN GENERAL  G   ON G.CODDOC       = I.CODIES AND G.TIPDOC = I.TIPDOC
          INNER JOIN OBLIGPIF O   ON O.CODGENERAL   = G.CODGENERAL
          LEFT  JOIN NMONEDE  M   ON M.CODMONEDA    = I.Moneda
          LEFT  JOIN NSUBUNIT SUB ON SUB.CODSUBUNIT = I.SUBUNITATEA'
          || coalesce(gSuplJoins,'') || '
        WHERE I.PARTENER     = PKG_LIST_SELURMDOCPART_CODPART()
          AND I.NRDOC        = PKG_LIST_SELURMDOCPART_NRDOC()
          AND I.DATADOC      = PKG_LIST_SELURMDOCPART_DATADOC()
          AND O.SEMNIFICATIE = 200';
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
  IF vSitVal THEN
    sCursRef := ' (select wme_result from  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null, '
                                          || coalesce(aMonedaV::varchar,'') || ','
                                          || coalesce(aBancaV::varchar,'')
                                          || ', to_char(COALESCE(C.DATADOC,T1.DATADOC,NC.DATADOC,I.DATADOC),''dd.mm.yyyy'')))';
  ELSE
    sCursRef := ' 1 ';
  END IF;

  sSelect := '
          SELECT
            CASE WHEN TS.CODSUBUNIT IS NULL THEN NULL WHEN G.TipDoc IN (29,30,31,33) THEN T.CODTREZOR ELSE G.CODDOC END NAV_CodDoc,
            CASE WHEN ts.codsubunit IS NULL THEN NULL ELSE G.TipDoc END NAV_TipDoc,
            CASE WHEN G.TipDoc = 28 THEN ''PV''    WHEN G.TipDoc IN (29,30,31,33) THEN T1.DOC     WHEN G.TipDoc = 35 THEN ''NC''     ELSE I.PREFIXDOC END PREFIXDOC,
            CASE WHEN G.TipDoc = 28 THEN C.DATADOC WHEN G.TipDoc IN (29,30,31,33) THEN T1.DATADOC WHEN G.TipDoc = 35 THEN NC.DATADOC ELSE I.DATADOC   END DATADOC,
            CASE WHEN G.TipDoc = 28 THEN C.NRDOC   WHEN G.TipDoc IN (29,30,31,33) THEN T1.NRDOC   WHEN G.TipDoc = 35 THEN NC.NRDOC   ELSE I.NRDOC     END NRDOC,
            O.TERMEN, MON.SIMBOL, O.MAJORARI, 0,
            CASE WHEN G.SEMNIFICATIE IN (420,1300) THEN - O.VALOARE ELSE O.VALOARE END VALOARE,
            CASE WHEN G.SEMNIFICATIE IN (420,1300) THEN O.VALOARE ELSE - O.VALOARE END SOLD,
            CASE WHEN G.TipDoc = 28 AND G.SEMNIFICATIE IN (1300) THEN C.OBSD
             WHEN G.TipDoc = 28 AND G.SEMNIFICATIE IN (1350)     THEN C.OBSC
             WHEN G.TipDoc IN (29,30,31,33)                      THEN T1.OBS
             WHEN G.TipDoc = 35                                  THEN NC.OBS
             ELSE I.OBS
            END OBS,
            1 ORDINE,' || coalesce(sCursRef,'') || coalesce(gUserAlias,'') || '
          FROM STINGERE S
            INNER JOIN OBLIGPIF            O   ON O.CODOBLIGPIF  = S.CODSTINGATORPIF
            INNER JOIN GENERAL             G   ON G.CODGENERAL   = O.CODGENERAL
            LEFT  JOIN IESIRI              I   ON I.CODIES       = G.CODDOC AND I.TIPDOC = G.CODDOC
            LEFT  JOIN COMPENS             C   ON C.CODCOMPENS   = G.CODDOC AND G.TIPDOC = 28
            LEFT  JOIN TREZOR1             T1  ON T1.CODTREZOR1  = G.CODDOC AND G.TIPDOC IN (29,30,31,33)
            LEFT  JOIN TREZOR              T   ON T1.CODTREZOR   = T.CODTREZOR
            LEFT  JOIN NC                      ON NC.CODNC       = G.CODDOC AND G.CODDOC = 35
            LEFT  JOIN NMONEDE             MON ON MON.CODMONEDA  = G.MONEDA
            LEFT  JOIN tmp_subunitdedicate ts  ON ts.codsubunit  = COALESCE(NC.SUBUNITATEA, T.SUBUNITATEA, C.SUBUNITATEA, I.SUBUNITATEA)
            LEFT  JOIN nsubunit            sub ON sub.codsubunit = COALESCE(NC.SUBUNITATEA, T.SUBUNITATEA, C.SUBUNITATEA, I.SUBUNITATEA)'
                        || coalesce(gSuplJoins,'') || '
          WHERE s.codstinspif = $1';
--  insert into x values ('x_codpart',PKG_LIST_SELURMDOCPART_CODPART()::varchar );
--  insert into x values ('x_nrdoc',PKG_LIST_SELURMDOCPART_NRDOC()::varchar );
--  insert into x values ('x_datadoc',to_char(PKG_LIST_SELURMDOCPART_DATADOC(),'dd.mm.yyyy'));
  FOR vRec IN (
        SELECT O.Codobligpif
        FROM IESIRI I
          INNER JOIN GENERAL  G ON  G.CODDOC     = I.CODIES AND  G.TIPDOC = I.TIPDOC
          INNER JOIN OBLIGPIF O ON  O.CODGENERAL = G.CODGENERAL
        WHERE
                 I.PARTENER = PKG_LIST_SELURMDOCPART_CODPART()
             AND  I.NRDOC    = PKG_LIST_SELURMDOCPART_NRDOC()
             AND  I.DATADOC  = PKG_LIST_SELURMDOCPART_DATADOC()
             AND  O.SEMNIFICATIE = 200
  ) LOOP
      EXECUTE coalesce(sInsert,'') || coalesce(sSelect,'') using vRec.Codobligpif;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmincasaridoc_setjoinuri</obj_name>
  <obj_hashval>4f94af03f612f1491bad9dc0c16e7fe5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmincasaridoc_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 02.09.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_URMINCASARIDOC.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmlohn_processlist</obj_name>
  <obj_hashval>7f86da73fd0f59302548ece8380bf2ce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmlohn_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsTmp     varchar;
  sInsert     varchar;
  sSelect     varchar;
  sData1      varchar := 'to_date(''' || coalesce(current_setting('PKG_LIST_ALEGPERIOADA.gDataS', TRUE), '') || ''',''dd.mm.yyyy'')';
  sData2      varchar := 'to_date(''' || coalesce(current_setting('PKG_LIST_ALEGPERIOADA.gDataF', TRUE), '') || ''',''dd.mm.yyyy'')';
  sJoinExt    varchar;
  sFiltru     varchar;
  gSuplCols   VARCHAR :=  'iesiri1 ies1, iesiri ies, npart iesp, npartcodfisc iesfisc, nagenda iesssoc, nlocalit ieslsoc, njudet iesjsoc, nzone ieszsoc, ntari iestsoc, num1 iesu, nartobj oies, livr1 l1, livr l, intrari1 np1, intrari np, ' || 'comanda1 ci1, comanda ci, comanda1 cc1, comanda cc, iesiri1 bc1, iesiri bc, cmdprodmat cpm, prodmat pm, nartobj obc, livr1 bcl1, livr bcl, intrari1 intr1, intrari intr, npart intrp, npartcodfisc intrfisc, ' || 'nagenda intrssoc, nlocalit intrlsoc, njudet intrjsoc, nzone intrzsoc, ntari intrtsoc, num1 intru, ioart1 eioa1, ncont ec, ioart1 iioa1, ncont ic';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Adina 12.04.2021 -alstart,alstop
  --Florin 19.08.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OPEXT', 'OPEXT.CODOBIECT = IES1.CODOBIECT' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OPATR', 'OPATR.CODOBIECT = IES1.CODOBIECT' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OMEXT', 'OMEXT.CODOBIECT = INTR1.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OMATR', 'OMATR.CODOBIECT = INTR1.CODOBIECT',NULL);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_URMLOHN.gSuplCols',gSuplCols,false);

  CALL PRC_AL_CHECK('ioart1',0);

  IF fnc_current_setting_boolint('PKG_LIST_ALEGPERIOADA.gOpt1') = 1 THEN
    sFiltru := '
        AND COALESCE(ic.clasa,0) = 8';
  END IF;

  sInsert := 'INSERT INTO ' || tmpName || '(
        NAV_CODDOC, NAV_TIPDOC, PRODUS, MATERIAL,
        IESPREF, IESNR, IESDATA, IESPART, IESCIF, IESSSOC_DEN, IESSSOC_LOC, IESSSOC_JUD, IESSSOC_TARA, IESSSOC_ZONA,
        IESSSOC_ADR,
        IESUM, IESCANT, IESPU,
        NPPREF, NPNR, NPDATA, NPCANT,
        CIPREF, CINR, CIDATA,
        CCPREF, CCNR, CCDATA,
        BCPREF, BCNR, BCDATA, BCCANT, RETCANT, RETREST,
        INTRPREF, INTRNR, INTRDATA, INTRPART, INTRCIF, INTRSSOC_DEN, INTRSSOC_LOC, INTRSSOC_JUD, INTRSSOC_TARA, INTRSSOC_ZONA,
        INTRSSOC_ADR,
        INTRUM, INTRCANT, INTRCANTX, INTRPU ' || gUserFields || ')';
  sInsTmp := '
      INSERT INTO tmp_list_lohn (
        codies1, codl1, codnp1, codci1, codcc1, codbc1, codbcl1, codcpm, codintr1,
        codiioa1, codeioa1, iescodcif, intrcodcif, iescodssoc, intrcodssoc,
        coefx, coefin)
      SELECT
        ies1.codies1, l1.codlivr1 codl1, np1.codintr1 codnp1, ci1.codcomanda1 codci1, cc1.codcomanda1 codcc1, bc1.codies1 codbc1, bcl1.codlivr1 codbcl1, cpm.codcmdprodmat codcpm, intr1.codintr1,
        iioa1.codioart1 codiioa1,eioa1.codioart1 codeioa1, iesfisc.cod_codfiscal iescodcif, intrfisc.cod_codfiscal intrcodcif, iesssoc.codagenda iescodssoc, intrssoc.codagenda intrcodssoc,
        0 coefx, CASE WHEN ies1.cant &lt; 0 THEN 0 ELSE 1 END coefin
      FROM iesiri ies
        inner join npart        iesp     ON iesp.codpart      = ies.partener
        left  join npartcodfisc iesfisc  on iesfisc.codpart   = ies.partener and iesfisc.principal = 1
        left  join nagenda       iesssoc  on iesssoc.codpart   = ies.partener and iesssoc.sediusocial between 4 and 7 and COALESCE(iesssoc.inactiv, 0) = 0
        inner join iesiri1       ies1      ON ies1.codies       = ies.codies
        inner join nartobj       oies      ON oies.codobiect    = ies1.codobiect
        inner join livr1         l1        ON l1.codies1        = ies1.codies1
        inner join livr         l        ON l.codlivr         = l1.codlivr AND l.codies = ies.codies AND l.tiplivr = ies.tipdoc
        inner join nirstoc       ens      ON ens.codnirstoc    = l1.codnirstoc
        inner join nirstoc1     ens1      ON ens1.codnirstoc   = l1.codnirstoc
        inner join nirstoc       eons      ON eons.codnirstoc   = ens1.codnirstocorig
        inner join intrari1     np1      ON np1.codintr1      = eons.codintr1
        inner join intrari       np        ON np.codintr        = np1.codintr
        inner join comanda1     ci1      ON ci1.codcomanda1   = np1.codcmdint1
        inner join comanda       ci        ON ci.codcomanda     = ci1.codcomanda
        left  join cmdlink       cl        ON cl.codcomanda1    = ci1.codcomanda1
        left  join comanda1     cc1      ON cc1.codcomanda1   = cl.codliniecomanda
        left  join comanda       cc        ON cc.codcomanda     = cc1.codcomanda
        inner join iesiri1       bc1      ON bc1.codcmdint1    = ci1.codcomanda1
        inner join iesiri       bc        ON bc.codies         = bc1.codies
        left  join iesprodlink  ipl      ON ipl.codies1       = bc1.codies1
        left  join cmdprodmat   cpm      ON cpm.codcmdprodmat = ipl.codcmdprodmat
        left  join prodmat       pm        ON pm.codmat         = cpm.codprodmat
        inner join nartobj       obc      ON obc.codobiect     = bc1.codobiect
        inner join livr1         bcl1      ON bcl1.codies1      = bc1.codies1
        inner join livr         bcl      ON bcl.codlivr       = bcl1.codlivr AND bcl.codies = bc.codies AND bcl.tiplivr = bc.tipdoc
        inner join nirstoc1     ins1     ON ins1.codnirstoc   = bcl1.codnirstoc
        inner join nirstoc       ins      ON ins.codnirstoc    = ins1.codnirstocorig
        inner join nir           inir     ON inir.codnir       = ins.codnir
        left  join dvi1         idvi1    on idvi1.coddvi1     = ins.coddvi1
        inner join intrari1     intr1    ON intr1.codintr1    = COALESCE(idvi1.codintr1, ins.codintr1)
        inner join intrari       intr      ON intr.codintr      = intr1.codintr AND intr.tipdoc = inir.tipnir
        left  join npart         intrp    on intrp.codpart     = intr.partener
        left  join npartcodfisc intrfisc on intrfisc.codpart  = intr.partener and intrfisc.principal = 1
        left  join nagenda       intrssoc on intrssoc.codpart  = intr.partener and intrssoc.sediusocial between 4 and 7 and COALESCE(intrssoc.inactiv, 0) = 0
        left  join ioart1       eioa1    ON eioa1.codioart    = ens.codioart AND (ies.an*12+ies.luna)   BETWEEN eioa1.ALStart and eioa1.ALStop
        left  join ioart1       iioa1    ON iioa1.codioart    = ins.codioart AND (intr.an*12+intr.luna) BETWEEN iioa1.ALStart and iioa1.ALStop
        left  join ncont         ic        ON ic.codcont        = iioa1.cont
      WHERE ies.operat = 1 AND ies.anulat = 0
        AND ies.DataDoc BETWEEN ' || coalesce(sData1,'') || ' AND ' || coalesce(sData2,'') || coalesce(sFiltru,'')
        || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('ies',NULL,NULL,NULL),'');
  sSelect := '
      SELECT
        ies.codies, ies.tipdoc, oies.denumire produs, obc.denumire mat,
        ies.prefixdoc, ies.nrdoc, ies.datadoc, iesp.den_part, iesfisc.codfiscal, iesssoc.obs, ieslsoc.den_localit, iesjsoc.den_judet, iestsoc.den_tara, ieszsoc.den_zona,
        (SELECT getadresa.wme_result FROM getadresa(NULL, iesssoc.sector, iesssoc.strada, iesssoc.nr1, iesssoc.nr2, iesssoc.bloc, iesssoc.scara, iesssoc.etaj, iesssoc.apart, iesssoc.codpostal)),
        iesu.den_um1, l1.cant/iesu.paritate, ies1.pu*iesu.paritate,
        np.prefixdoc, np.nrdoc, np.datadoc, tmp.coefin*np1.cant/iesu.paritate,
        ci.prefixdoc, ci.nrdoc, ci.datadoc,
        cc.prefixdoc, cc.nrdoc, cc.datadoc,
        bc.prefixdoc, bc.nrdoc, bc.datadoc, tmp.coefin*bcl1.cant/intru.paritate bccant,
        tmp.coefin*(Case  When bc1.cant=0 then 0 else cpm.cant*bcl1.cant/bc1.cant end)/intru.paritate retcant, tmp.coefin*(Case  When bc1.cant=0 then 0 else cpm.rest*bcl1.cant/bc1.cant end)/intru.paritate retrest,
        intr.prefixdoc, intr.nrdoc, intr.datadoc, intrp.den_part, intrfisc.codfiscal, intrssoc.obs, intrlsoc.den_localit, intrjsoc.den_judet, intrtsoc.den_tara, intrzsoc.den_zona,
        (SELECT getadresa.wme_result FROM getadresa(NULL, intrssoc.sector, intrssoc.strada, intrssoc.nr1, intrssoc.nr2, intrssoc.bloc, intrssoc.scara, intrssoc.etaj, intrssoc.apart, intrssoc.codpostal)),
        intru.den_um1, tmp.coefin*intr1.cant/intru.paritate, tmp.coefin*tmp.coefx*intr1.cant/intru.paritate, intr1.pu*intru.paritate' || gUserAlias || '
      FROM tmp_list_lohn tmp
        left join iesiri1       ies1       ON ies1.codies1           = tmp.codies1
        left join iesiri         ies       ON ies.codies             = ies1.codies
        left join npart         iesp       ON iesp.codpart           = ies.partener
        left join npartcodfisc  iesfisc   on iesfisc.cod_codfiscal  = tmp.iescodcif
        left join nagenda       iesssoc   on iesssoc.codagenda      = tmp.iescodssoc
        left join nlocalit       ieslsoc   on ieslsoc.codlocalit     = iesssoc.codlocalit
        left join njudet         iesjsoc   on iesjsoc.codjudet       = ieslsoc.codjudet
        left join nzone         ieszsoc   on ieszsoc.codzona        = ieslsoc.codzona
        left join ntari         iestsoc   on iestsoc.codtara        = ieslsoc.codtara
        left join num1           iesu       ON iesu.codum1            = ies1.umsec
        left join nartobj       oies       ON oies.codobiect         = ies1.codobiect
        left join livr1         l1         ON l1.codlivr1            = tmp.codl1
        left join livr           l         ON l.codlivr              = l1.codlivr
        left join intrari1       np1       ON np1.codintr1           = tmp.codnp1
        left join intrari       np         ON np.codintr             = np1.codintr
        left join comanda1       ci1       ON ci1.codcomanda1        = tmp.codci1
        left join comanda       ci         ON ci.codcomanda          = ci1.codcomanda
        left join comanda1       cc1       ON cc1.codcomanda1        = tmp.codcc1
        left join comanda       cc         ON cc.codcomanda          = cc1.codcomanda
        left join iesiri1       bc1       ON bc1.codies1            = tmp.codbc1
        left join iesiri         bc         ON bc.codies              = bc1.codies
        left join cmdprodmat     cpm       ON cpm.codcmdprodmat      = tmp.codcpm
        left join prodmat       pm         ON pm.codmat              = cpm.codprodmat
        left join nartobj       obc       ON obc.codobiect          = bc1.codobiect
        left join livr1         bcl1       ON bcl1.codlivr1          = tmp.codbcl1
        left join livr           bcl       ON bcl.codlivr            = bcl1.codlivr
        left join intrari1       intr1     ON intr1.codintr1         = tmp.codintr1
        left join intrari       intr       ON intr.codintr           = intr1.codintr
        left join npart         intrp     on intrp.codpart          = intr.partener
        left join npartcodfisc   intrfisc  on intrfisc.cod_codfiscal = tmp.intrcodcif
        left join nagenda       intrssoc  on intrssoc.codagenda     = tmp.intrcodssoc
        left join nlocalit       intrlsoc  on intrlsoc.codlocalit    = intrssoc.codlocalit
        left join njudet         intrjsoc  on intrjsoc.codjudet      = intrlsoc.codjudet
        left join nzone         intrzsoc  on intrzsoc.codzona       = intrlsoc.codzona
        left join ntari         intrtsoc  on intrtsoc.codtara       = intrlsoc.codtara
        left join num1           intru     ON intru.codum1           = intr1.umsec
        left join ioart1         eioa1     ON eioa1.codioart1        = tmp.codeioa1
        left join ncont         ec         ON ec.codcont             = eioa1.cont
        left join ioart1         iioa1     ON iioa1.codioart1        = tmp.codiioa1
        left join ncont         ic         ON ic.codcont             = iioa1.cont' || gSuplJoins;
  DELETE FROM tmp_list_lohn;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInstmp, aListID, aListVer);

  UPDATE tmp_list_lohn SET coefx = 1 WHERE ctid IN (SELECT min(ctid) FROM tmp_list_lohn WHERE coefin = 1 GROUP BY codintr1);

  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
  EXECUTE coalesce(sInsert,'') || coalesce(sSelect,'');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmlohn_setjoinuri</obj_name>
  <obj_hashval>a20b16294440faf3fb6e46d0af395683</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmlohn_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 19.08.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_URMLOHN.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmnccli_processlist</obj_name>
  <obj_hashval>f2d315e5cca65c70d467439178b26272</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmnccli_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplCols   VARCHAR := '';
  gSuplJoins  VARCHAR := '';

  sInsert     varchar;
  sSelect     varchar;
  dDataS      date;
  dDataF      date;
begin
  --Bogdan 08.09.2020
  dDataS    :=  (SELECT PKG_LIST_ALEGPERIOADA_getDataS.WME_RESULT FROM PKG_LIST_ALEGPERIOADA_getDataS (NULL,NULL)) ;
  dDataF    :=  (SELECT PKG_LIST_ALEGPERIOADA_getDataF.WME_RESULT FROM PKG_LIST_ALEGPERIOADA_getDataF (NULL,NULL)) ;
  gSuplCols := 'notecredit nc, notecreditfact ncf, iesiri i, iesiri1 i1, npart p, nartobj o, num1 um, ncont ncont';

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs (gSuplCols , 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = O.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs (gSuplCols , 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = O.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs (gSuplCols , 'NAGENDA'   , 'SSOC', 'SSOC.CODPART = I.PARTENER AND SSOC.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(SSOC.INACTIV, 0) = 0');
  call pkg_list_struct_addsupltabs (gSuplCols , 'NPERS'     , 'PAG' , 'PAG.CODPERS = SSOC.CODAGENT' ,NULL);
  CALL pkg_list_struct_getsuplcols( aLISTID, aLISTVER, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config ('PKG_LIST_BASE_URMNCCLI.gSuplCols',gSuplCols,false);

  sInsert := 'INSERT INTO '|| tmpName ||'
    (NAV_CodDoc, NAV_TipDoc, NCDATAI, NCDATAS, PrefixDoc,
    NrDoc, DataDoc, Part, Art, Cont, UM, Cant, Pret, PU, PD, VAL, VALTVA, PROCTVA '
  || coalesce (gUserFields ,'')
  || ') ';
  sSelect := '
        SELECT nc.codncredit,
          58,
          nc.datastart,
          nc.datastop,
          i.prefixdoc,
          i.nrdoc,
          i.datadoc,
          p.den_part,
          o.denumire,
          ncont.simbol,
          CASE WHEN i1.tiplinie IN (''T'',''G'') THEN ''%'' ELSE um.den_um1 END,
          i1.cant     / coalesce (um.paritate,1) ,
          i1.pretorig * um.paritate,
          i1.pu       * um.paritate,
          i1.pretorig * um.paritate *  (case when i1.coefdiscmaj = 0 then 1
                                             when i1.coefdiscmaj is NULL then 1
                                             else  i1.coefdiscmaj end) ,
          CASE WHEN i1.tiplinie IN (''T'',''G'') THEN i1.restfact ELSE i1.cant  * i1.pu END,
          i1.tva,
          CASE
            WHEN coalesce (i1.tva,0) = 0 THEN 0
            WHEN i.tipdoc IN (16,21) AND i1.pu  * i1.cant = coalesce (i1.tva,0) THEN 0
            WHEN i.tipdoc IN (16,21) THEN coalesce (i1.tva,0) /  (case when (i1.pu * i1.cant - coalesce (i1.tva,0)) = 0 then 1
                                                                       else (i1.pu * i1.cant - coalesce (i1.tva,0)) end)
            WHEN i1.pu * i1.cant = 0 THEN 0
            ELSE coalesce (i1.tva,0) / (case when (i1.pu * i1.cant) = 0 then 1 else (i1.pu * i1.cant) end)
          END * 100 '
            || coalesce (gUserAlias ,'')|| '
        FROM notecredit             nc
          INNER JOIN notecreditfact ncf ON ncf.codncredit = nc.codncredit
          INNER JOIN iesiri         i   ON i.codies       = ncf.coddoc AND i.tipdoc = ncf.tipdoc
          INNER JOIN iesiri1        i1  ON i1.codies      = i.codies
          INNER JOIN npart          p   ON p.codpart      = i.partener
          INNER JOIN nartobj        o   ON o.codobiect    = i1.codobiect
          INNER JOIN num1           um  ON um.codum1      = i1.umsec
          LEFT JOIN ncont               ON ncont.codcont  = Coalesce (i1.contserv,i1.contdiscount,0) '
            || coalesce (gSuplJoins ,'')|| '
        WHERE
          i.operat = 1
          AND i.anulat = 0 '
            || coalesce ( (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT (NULL,'NC',NULL,NULL,NULL)) ,'') || '
          AND i.DataDoc BETWEEN $1 AND $2';

  EXECUTE coalesce (sInsert,'') || coalesce (sSelect,'') USING dDataS, dDataF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmnccli_setjoinuri</obj_name>
  <obj_hashval>d423f0dc33963c962d464918ea48935e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmnccli_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 08.09.2020
  PERFORM pkg_list_struct_SetTableSpec (current_setting ('PKG_LIST_BASE_URMNCCLI.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmofe_setjoinuri</obj_name>
  <obj_hashval>e67047ac757d8504029b2bb2e7911dc6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmofe_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 09.09.2020
  PERFORM pkg_list_struct_SetTableSpec (current_setting ('PKG_LIST_BASE_URMOFE.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmplatiart_getcodcontract</obj_name>
  <obj_hashval>52e72d0f94de08d49e0ef71508472866</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmplatiart_getcodcontract(acodpart numeric, adatadoc date)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodContract numeric;
BEGIN
  --Adina 08 septembrie 2020
  BEGIN
    SELECT COALESCE(CodContract, 0)
    INTO aCodContract
    FROM contract c
    WHERE c.partener = aCodPart and aDataDoc BETWEEN c.datastart AND c.datastop;
  EXCEPTION WHEN others THEN
    aCodContract := 0;
  END;
  RETURN aCodContract;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmplatiart_setjoinuri</obj_name>
  <obj_hashval>c7dc068719044db55a42baf1b5eef630</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmplatiart_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 08 septembrie 2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_URMPLATIART.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmplatidoc_setjoinuri</obj_name>
  <obj_hashval>26314dcbb8311517d585fc3d0f8e3bf0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmplatidoc_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 08 septembrie 2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_URMPLATIDOC.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmrealdez_setjoinuri</obj_name>
  <obj_hashval>29a7950323ea38a7cb296c386056c53e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmrealdez_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 19.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_URMREALDEZ.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmsupv_processlist</obj_name>
  <obj_hashval>05cdd857cc86a67c75cac88a8a68177f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmsupv_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sInsertTMP       varchar := '';
  sInsertTMP1     varchar := '';
  sFiltruDATA     varchar := '';
  sFiltruCamp     varchar := '';
  sFiltruRetCamp   varchar := '';
  gSuplCols        VARCHAR := 'NPERS P, PASS_MODIF PM';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  emDataIni        varchar := current_setting('PKG_LIST_SELECTEMULARE.p_DataIni', true);
  emDataFin        varchar := current_setting('PKG_LIST_SELECTEMULARE.p_DataFin', true);
BEGIN
  --Adina 11 septembrie 2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_URMSUPV.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  sInsert := '
  INSERT INTO ' || tmpName || '(
    NAV_CodDoc,
    NAV_TipDoc,
    Persoana,
    CampModif,
    TipDoc,
    NrDoc,
    DataDoc,
    Tabela,
    OldVal,
    NewVal,
    Explic ' || gUserFields || ')
  SELECT
    I.CODIES NAV_CodDoc,
    I.TIPDOC NAV_TipDoc,
    P.NUME||'' ''||P.PRENUME Persoana,
    PM.FIELDNAME CampModif,
    I.PREFIXDOC TipDoc,
    I.NrDoc,
    I.DataDoc,
    PM.TABLENAME Tabela,
    PM.OLDVALUE OldVal,
    PM.NEWVALUE NewVal,
    PM.Explic ' || gUserAlias || '
  FROM PASS_MODIF PM
    INNER JOIN IESIRI I ON I.CODIES     = PM.CODMASTER
    INNER JOIN NPERS  P ON PM.PERSMODIF = P.CODPERS ' || gSuplJoins || '
  WHERE PM.TABLENAME = ''IESIRI'' AND
        PM.DataModif between to_date(''' || coalesce(emDataIni,'') || ''',''dd.mm.yyyy hh24:mi:ss'')
                         and to_date(''' || coalesce(emDataFin,'') || ''',''dd.mm.yyyy hh24:mi:ss'')';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  sInsert := '
  INSERT INTO ' || tmpName || '(
    NAV_CodDoc,
    NAV_TipDoc,
    Persoana,
    CampModif,
    TipDoc,
    NrDoc,
    DataDoc,
    Tabela,
    OldVal,
    NewVal,
    Explic ' || gUserFields || ')
  SELECT
    C.CODCOMANDA NAV_CodDoc,
    C.TIPDOC NAV_TipDoc,
    P.NUME||'' ''||P.PRENUME Persoana,
    PM.FIELDNAME CampModif,
    C.PREFIXDOC TipDoc,
    C.NrDoc,
    C.DataDoc,
    PM.TABLENAME Tabela,
    PM.OLDVALUE OldVal,
    PM.NEWVALUE NewVal,
    PM.Explic ' || gUserAlias || '
  FROM PASS_MODIF PM
    INNER JOIN COMANDA C ON C.CODCOMANDA = PM.CODMASTER
    INNER JOIN NPERS   P ON PM.PERSMODIF = P.CODPERS ' || gSuplJoins || '
  WHERE PM.TABLENAME = ''COMANDA'' AND
        PM.DataModif between to_date(''' || coalesce(emDataIni,'') || ''',''dd.mm.yyyy hh24:mi:ss'')
                         and to_date(''' || coalesce(emDataFin,'') || ''',''dd.mm.yyyy hh24:mi:ss'')';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  sInsert := '
  INSERT INTO ' || tmpName || '(
    NAV_CodDoc,
    NAV_TipDoc,
    Persoana,
    CampModif,
    TipDoc,
    NrDoc,
    DataDoc,
    Tabela,
    OldVal,
    NewVal,
    Explic ' || gUserFields || ')
  SELECT
    O.CODOFERTA NAV_CodDoc,
    O.TIPDOC NAV_TipDoc,
    P.NUME||'' ''||P.PRENUME Persoana,
    PM.FIELDNAME CampModif,
    ''OFERTA'' TipDoc,
    O.NrDoc,
    O.DataOferta,
    PM.TABLENAME Tabela,
    PM.OLDVALUE OldVal,
    PM.NEWVALUE NewVal,
    PM.Explic ' || gUserAlias || '
  FROM PASS_MODIF PM
    INNER JOIN OFERTA O ON O.CODOFERTA  = PM.CODMASTER
    INNER JOIN NPERS  P ON PM.PERSMODIF = P.CODPERS ' || gSuplJoins || '
  WHERE PM.TABLENAME = ''OFERTA'' AND
        PM.DataModif between to_date(''' || coalesce(emDataIni,'') || ''',''dd.mm.yyyy hh24:mi:ss'')
                         and to_date(''' || coalesce(emDataFin,'') || ''',''dd.mm.yyyy hh24:mi:ss'')';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  sInsert := '
  INSERT INTO ' || tmpName || '(
    NAV_CodDoc,
    NAV_TipDoc,
    Persoana,
    CampModif,
    TipDoc,
    NrDoc,
    DataDoc,
    Tabela,
    OldVal,
    NewVal,
    Explic,
    Fact ' || gUserFields || ')
  SELECT
    E.CODEMULARE NAV_CodDoc,
    -1 NAV_TipDoc,
    P.NUME||'' ''||P.PRENUME Persoana,
    PM.FIELDNAME CampModif,
    ''BON CASA'' TipDoc,
    E.NRBON NrDoc,
    E.DATABON DataDoc,
    PM.TABLENAME Tabela,
    PM.OLDVALUE OldVal,
    PM.NEWVALUE NewVal,
    PM.Explic,
    I.PREFIXDOC||I.NRDOC::varchar||''/''||TO_CHAR(I.DATADOC,''DD.MM.YYYY'') Fact
     ' || gUserAlias || '
  FROM PASS_MODIF PM
    INNER JOIN NPERS   P ON PM.PERSMODIF = P.CODPERS
    LEFT  JOIN EMULARE E ON E.CODEMULARE = PM.CODMASTER
    LEFT  JOIN IESIRI  I ON E.CODIES     = I.CODIES ' || gSuplJoins || '
  WHERE PM.TABLENAME = ''EMULARE'' AND
        PM.DataModif between to_date(''' || coalesce(emDataIni,'') || ''',''dd.mm.yyyy hh24:mi:ss'')
                         and to_date(''' || coalesce(emDataFin,'') || ''',''dd.mm.yyyy hh24:mi:ss'')';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  sInsert := '
  INSERT INTO ' || tmpName || '(
    NAV_CodDoc,
    NAV_TipDoc,
    Persoana,
    CampModif,
    TipDoc,
    NrDoc,
    DataDoc,
    Tabela,
    OldVal,
    NewVal,
    Explic,
    Obs ' || gUserFields || ')
  SELECT
    NP.CODPERS NAV_CodDoc,
    502 NAV_TipDoc,
    P.NUME||'' ''||P.PRENUME Persoana,
    PM.FIELDNAME CampModif,
    ''PERSOANA'' TipDoc,
    NULL NrDoc,
    NULL DataDoc,
    PM.TABLENAME Tabela,
    PM.OLDVALUE OldVal,
    PM.NEWVALUE NewVal,
    PM.Explic,
    NP.NUME||'' ''||NP.PRENUME ' || gUserAlias || '
  FROM PASS_MODIF PM
    INNER JOIN NPERS NP ON NP.CODPERS   = PM.CODMASTER
    INNER JOIN NPERS P  ON PM.PERSMODIF = P.CODPERS ' || gSuplJoins || '
  WHERE PM.TABLENAME = ''NPERS'' AND
        PM.DataModif between to_date(''' || coalesce(emDataIni,'') || ''',''dd.mm.yyyy hh24:mi:ss'')
                         and to_date(''' || coalesce(emDataFin,'') || ''',''dd.mm.yyyy hh24:mi:ss'')';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  sInsert := '
  INSERT INTO ' || tmpName || '(
    NAV_CodDoc,
    NAV_TipDoc,
    Persoana,
    CampModif,
    TipDoc,
    NrDoc,
    DataDoc,
    Tabela,
    OldVal,
    NewVal,
    Explic,
    Obs ' || gUserFields || ')
  SELECT
    PC.CODPRODCOMP NAV_CodDoc,
    504 NAV_TipDoc,
    P.NUME||'' ''||P.PRENUME Persoana,
    PM.FIELDNAME CampModif,
    ''RETETA'' TipDoc,
    PC.CODPRODCOMP NrDoc,
    NULL DataDoc,
    PM.TABLENAME Tabela,
    PM.OLDVALUE OldVal,
    PM.NEWVALUE NewVal,
    PM.Explic,
    PC.OBS ' || gUserAlias || '
  FROM PASS_MODIF PM
    INNER JOIN PRODCOMP PC ON PC.CODPRODCOMP = PM.CODMASTER
    INNER JOIN NPERS    P  ON PM.PERSMODIF   = P.CODPERS ' || gSuplJoins || '
  WHERE PM.TABLENAME = ''PRODCOMP'' AND
        PM.DataModif between to_date(''' || coalesce(emDataIni,'') || ''',''dd.mm.yyyy hh24:mi:ss'')
                         and to_date(''' || coalesce(emDataFin,'') || ''',''dd.mm.yyyy hh24:mi:ss'')';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  sInsert := '
  INSERT INTO ' || tmpName || ' (NAV_CODDOC,NAV_TIPDOC,PERSOANA,CAMPMODIF,TIPDOC,NRDOC,DATADOC,TABELA,OLDVAL,NEWVAL,EXPLIC,OBS,POSTR,FACT)
  select TMP.NAV_CODDOC,TMP.NAV_TIPDOC,TMP.PERSOANA,TMP.CAMPMODIF,TMP.TIPDOC,TMP.NRDOC,TMP.DATADOC,TMP.TABELA,TMP.OLDVAL,TMP.NEWVAL,TMP.EXPLIC,TMP.OBS,TMP.POSTR,TMP.FACT
  from TMP_LIST_URMSUPV TMP
       LEFT JOIN PASS_MODIF PM ON PM.PERSMODIF = TMP.NAV_CODDOC - TMP.NAV_CODDOC - 1
       LEFT JOIN NPERS      P  ON P.CODPERS    = TMP.NAV_CODDOC - TMP.NAV_CODDOC - 1 ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmsupv_setjoinuri</obj_name>
  <obj_hashval>b809f9746d80d565387cf3af39afe78b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmsupv_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 11 septembrie 2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_URMSUPV.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmvirinterne_setjoinuri</obj_name>
  <obj_hashval>13c892378ab021ba465b0c950fabcab4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmvirinterne_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_URMVIRINTERNE.gSuplCols', true));
PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmvirinterne_setparams</obj_name>
  <obj_hashval>ab5c02abfe9b27b4f9e9f908498f55c8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmvirinterne_setparams()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 01.09.2020
  PERFORM set_config('PKG_LIST_BASE_URMVIRINTERNE.v_LunaStart', getanlucru() * 12 + current_setting('PKG_LIST_SELECTLUNA.vLunaStart', TRUE)::NUMERIC);
  PERFORM set_config('PKG_LIST_BASE_URMVIRINTERNE.v_LunaStop' , getanlucru() * 12 + current_setting('PKG_LIST_SELECTLUNA.vLunaFin'  , TRUE)::NUMERIC);
--  INSERT INTO x (view_name, test)VALUES ('lStartu', current_setting('PKG_LIST_BASE_URMVIRINTERNE.v_LunaStart', TRUE));
--  INSERT INTO x (view_name, test)VALUES ('lFInu', current_setting('PKG_LIST_BASE_URMVIRINTERNE.v_LunaStop', TRUE));
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utilaje_setjoinuri</obj_name>
  <obj_hashval>17f7f7168583fee37ed0991dcd974605</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utilaje_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 16 septembrie 2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_UTILAJE.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_add_simbol_lipsa</obj_name>
  <obj_hashval>9dd1d3babe463fc6755bdff5d97656b7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_add_simbol_lipsa(psimbol character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_LIPSA_CORESP_PLANP(SIMBOL) VALUES(pSimbol);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_baga_serii_in_tmp</obj_name>
  <obj_hashval>40e3c1ec8561fafdf6b831d5bba5ba8b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_baga_serii_in_tmp(pcant numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Stef 12.05.2022 - curatenie PKG_LIST_BASE_UTILS CT_XXX
  DELETE FROM tmp_manevra_serii;
  PERFORM pkg_globals_SetSeparator( '| ');

  IF pCant = PKG_LIST_BASE_UTILS_CT_CODNIRSER() THEN
    INSERT INTO tmp_manevra_serii(codnirstoc, flag, serii, TG)
    SELECT s.codnirser, pCant,
      CASE WHEN  s.tipserie = 1 THEN string_agg( s.serie,',') || CASE WHEN  s.total_ns &gt; 10 THEN '...' ELSE '' END
           WHEN  s.tipserie = 2 THEN string_agg( s.serie,',')
      END  SERIE,
      CASE WHEN  s.tipserie = 1 THEN string_agg( s.TG,',')    || CASE WHEN  s.total_ns &gt; 10 THEN '...' ELSE '' END
           WHEN  s.tipserie = 2 THEN string_agg( s.TG,',')
      END  TG
    FROM (
          SELECT NSER.codnirser, row_number() over (PARTITION BY ns.codnirstoc ORDER BY s.serie) NRCRT,
              COUNT( ns.codnirstoc) over (PARTITION BY ns.codnirstoc) TOTAL_NS,
              CASE WHEN  tipserie = 1 THEN s.serie
                   WHEN  tipserie = 2 THEN s.serie || ' ( ' || nser.cantnir || ' ) '
                   ELSE ''
              END  SERIE, ns.tipserie, nser.cantnir, to_char( Coalesce( nser.TG, ns.tg),'dd.mm.yyyy') TG
          FROM nirser nser
            INNER JOIN nserii  s  ON  s.codserie    = nser.codserie
            INNER JOIN nirstoc ns ON  ns.codnirstoc = nser.codnirstoc
            INNER JOIN livr1   l1 ON  l1.codnirser  = nser.codnirser
          WHERE
            l1.codlivr1::varchar IN (SELECT VALOARE FROM tmp_manevra_liste WHERE filtru = 'CODLIVR1')
          ORDER BY nser.codnirser , ns.tipserie
      ) s
    WHERE s.nrcrt &lt;= 10
    GROUP BY s.codnirser, s.tipserie, s.total_ns;
  END IF;

  IF  pCant = PKG_LIST_BASE_UTILS_CT_MODIFPRET() THEN
    INSERT INTO tmp_manevra_serii(codnirstoc, serii, flag, codlivr1, codaux1, TG)
    SELECT S.CODTRANSF1, string_agg( s.serie,',') || CASE WHEN  s.total_ns &gt; 10 THEN '...' ELSE '' END  SERIE,
          PKG_LIST_BASE_UTILS_CT_MODIFPRET(), S.GEST, S.CODIOART, NULL TG
    FROM (
          SELECT L1.CODIES1 CODTRANSF1, N.GEST, NS.CODIOART,
            CASE MAX( NS.TIPSERIE)
              WHEN 1 THEN S.SERIE
              WHEN 2 THEN S.SERIE || ' ( ' || SUM( L1.CANT) || ' ) '
              ELSE ''
            END  SERIE, ROW_NUMBER() over(PARTITION BY L1.CODIES1 ORDER BY S.SERIE) NRCRT,
            COUNT( 1) over (PARTITION BY L1.CODIES1, N.GEST, NS.CODIOART) TOTAL_NS
          FROM LIVR1 L1
            INNER JOIN NIRSER  NSER ON  L1.CODNIRSER  = NSER.CODNIRSER
            INNER JOIN NIRSTOC NS   ON  NS.CODNIRSTOC = L1.CODNIRSTOC
            INNER JOIN NIR     N    ON  N.CODNIR      = NS.CODNIR
            INNER JOIN NSERII  S    ON  S.CODSERIE    = NSER.CODSERIE
          WHERE l1.codlivr1::varchar IN (SELECT VALOARE FROM tmp_manevra_liste WHERE filtru = 'CODLIVR1')
          GROUP BY L1.CODIES1, N.GEST, NS.CODIOART, S.SERIE
        ) S
    WHERE s.nrcrt &lt;= 10
    GROUP BY S.CODTRANSF1, S.GEST, S.CODIOART, s.total_ns;

    INSERT INTO tmp_manevra_serii(codnirstoc, serii, flag, codlivr1, codaux1, TG)
    SELECT S.CODTRANSF1, string_agg( s.serie,',') || CASE WHEN  s.total_ns &gt; 10 THEN '...' ELSE '' END  SERIE,
          PKG_LIST_BASE_UTILS_CT_MODIFPRET() + 1000, S.GEST, S.CODIOART, NULL TG
    FROM (
          SELECT L1.CODIES1 CODTRANSF1, N.GEST, NS.CODIOART,
                 CASE MAX( NS.TIPSERIE)
                  WHEN 1 THEN S.SERIE
                  WHEN 2 THEN S.SERIE || ' ( ' || SUM( L1.CANT) || ' )'
                  ELSE ''
                 END  || CASE WHEN  Coalesce( NSER.TG, NS.TG) IS NULL THEN '' ELSE  ' - ' || Coalesce( NSER.TG, NS.TG) END  SERIE,
                 ROW_NUMBER() OVER (PARTITION BY L1.CODIES1 ORDER BY S.SERIE, Coalesce(NSER.TG, NS.TG)) NRCRT,
                 COUNT( 1) over (PARTITION BY L1.CODIES1, N.GEST, NS.CODIOART) TOTAL_NS
          FROM LIVR1 L1
            INNER JOIN NIRSER  NSER ON  L1.CODNIRSER  = NSER.CODNIRSER
            INNER JOIN NIRSTOC NS   ON  NS.CODNIRSTOC = L1.CODNIRSTOC
            INNER JOIN NIR     N    ON  N.CODNIR      = NS.CODNIR
            INNER JOIN NSERII  S    ON  S.CODSERIE    = NSER.CODSERIE
          WHERE l1.codlivr1::varchar IN (SELECT VALOARE FROM tmp_manevra_liste WHERE filtru = 'CODLIVR1')
          GROUP BY L1.CODIES1, N.GEST, NS.CODIOART, S.SERIE, Coalesce( nser.TG, ns.tg)
          ) S
    WHERE s.nrcrt &lt;= 10
    GROUP BY S.CODTRANSF1, S.GEST, S.CODIOART, s.total_ns;

    INSERT INTO tmp_manevra_serii(codnirstoc, serii, flag, codlivr1, codaux1, TG)
    SELECT S.CODTRANSF1, string_agg( s.serie,',') || CASE WHEN  s.total_ns &gt; 10 THEN '...' ELSE '' END  SERIE,
          PKG_LIST_BASE_UTILS_CT_MODIFPRET() + 2000, S.GEST, S.CODIOART, NULL TG
    FROM (
          SELECT L1.CODIES1 CODTRANSF1, N.GEST, NS.CODIOART, TO_CHAR( Coalesce( NSER.TG, NS.TG),'dd.mm.yyyy') SERIE,
                 ROW_NUMBER()  OVER (PARTITION BY L1.CODIES1 ORDER BY S.SERIE, Coalesce(NSER.TG, NS.TG)) NRCRT,
                 COUNT( 1) over (PARTITION BY L1.CODIES1, N.GEST, NS.CODIOART) TOTAL_NS
          FROM LIVR1 L1
            INNER JOIN NIRSER  NSER ON  L1.CODNIRSER  = NSER.CODNIRSER
            INNER JOIN NIRSTOC NS   ON  NS.CODNIRSTOC = L1.CODNIRSTOC
            INNER JOIN NIR     N    ON  N.CODNIR      = NS.CODNIR
            INNER JOIN NSERII  S    ON  S.CODSERIE    = NSER.CODSERIE
          WHERE l1.codlivr1::varchar IN (SELECT VALOARE FROM tmp_manevra_liste WHERE filtru = 'CODLIVR1')
          GROUP BY L1.CODIES1, N.GEST, NS.CODIOART, S.SERIE, Coalesce( NSER.TG, NS.TG)
          ) S
    WHERE s.nrcrt &lt;= 10
    GROUP BY S.CODTRANSF1, S.GEST, S.CODIOART, s.total_ns;
  END IF;

  IF  pCant = PKG_LIST_BASE_UTILS_CT_TRANSF() THEN
    INSERT INTO tmp_manevra_serii(codnirstoc, serii, flag, TG)
    SELECT S.CODTRANSF1, string_agg( s.serie,',') || CASE WHEN  s.total_ns &gt; 10 THEN '...' ELSE '' END  SERIE,
          PKG_LIST_BASE_UTILS_CT_TRANSF(), NULL TG
    FROM (
          SELECT L1.CODIES1 CODTRANSF1,
                 CASE MAX( NS.TIPSERIE)
                   WHEN 1 THEN S.SERIE
                   WHEN 2 THEN S.SERIE || ' ( ' || SUM( L1.CANT) || ' ) '
                   ELSE ''
                 END  SERIE,
                 ROW_NUMBER() OVER (PARTITION BY L1.CODIES1 ORDER BY S.SERIE) NRCRT,
                 COUNT( 1) over (PARTITION BY L1.CODIES1) TOTAL_NS
          FROM LIVR1 L1
            INNER JOIN NIRSER  NSER ON  L1.CODNIRSER  = NSER.CODNIRSER
            INNER JOIN NIRSTOC NS   ON  NS.CODNIRSTOC = L1.CODNIRSTOC
            INNER JOIN NSERII  S    ON  S.CODSERIE    = NSER.CODSERIE
          WHERE l1.codlivr1::varchar IN (SELECT VALOARE FROM tmp_manevra_liste WHERE filtru = 'CODLIVR1')
          GROUP BY L1.CODIES1, S.SERIE, Coalesce( nser.tg, NS.TG)
          ) S
    WHERE s.nrcrt &lt;= 10
    GROUP BY S.CODTRANSF1, s.total_ns;

    INSERT INTO tmp_manevra_serii(codnirstoc, serii, flag, TG)
    SELECT S.CODTRANSF1, string_agg( s.serie,',') || CASE WHEN  s.total_ns &gt; 10 THEN '...' ELSE '' END  SERIE,
          PKG_LIST_BASE_UTILS_CT_TRANSF() + 1000, NULL TG
    FROM (
          SELECT L1.CODIES1 CODTRANSF1,
                 CASE MAX( NS.TIPSERIE)
                   WHEN 1 THEN S.SERIE
                   WHEN 2 THEN S.SERIE || ' ( ' || SUM( L1.CANT) || ' )'
                   ELSE ''
                 END  || CASE WHEN  Coalesce( nser.tg, NS.TG) IS NULL THEN '' ELSE  ' - ' || Coalesce( nser.tg, NS.TG) END  SERIE,
                 ROW_NUMBER() OVER (PARTITION BY L1.CODIES1 ORDER BY S.SERIE, Coalesce(nser.tg, NS.TG)) NRCRT,
                 COUNT( 1) over (PARTITION BY L1.CODIES1) TOTAL_NS
          FROM LIVR1 L1
            INNER JOIN NIRSER  NSER ON  L1.CODNIRSER  = NSER.CODNIRSER
            INNER JOIN NIRSTOC NS   ON  NS.CODNIRSTOC = L1.CODNIRSTOC
            INNER JOIN NSERII  S    ON  S.CODSERIE    = NSER.CODSERIE
          WHERE l1.codlivr1::varchar IN (SELECT VALOARE FROM tmp_manevra_liste WHERE filtru = 'CODLIVR1')
          GROUP BY L1.CODIES1, S.SERIE, Coalesce( nser.tg, NS.TG)
          ) S
    WHERE s.nrcrt &lt;= 10
    GROUP BY S.CODTRANSF1, s.total_ns;

    INSERT INTO tmp_manevra_serii(codnirstoc, serii, flag, TG)
    SELECT S.CODTRANSF1, string_agg( s.serie,',') || CASE WHEN  s.total_ns &gt; 10 THEN '...' ELSE '' END  SERIE,
          PKG_LIST_BASE_UTILS_CT_TRANSF() + 2000, NULL TG
    FROM (
          SELECT L1.CODIES1 CODTRANSF1, TO_CHAR( Coalesce( NSER.TG, NS.TG),'dd.mm.yyyy') SERIE,
                 ROW_NUMBER() OVER (PARTITION BY L1.CODIES1 ORDER BY S.SERIE, Coalesce(NSER.TG, NS.TG)) NRCRT,
                 COUNT( 1) over (PARTITION BY L1.CODIES1) TOTAL_NS
          FROM LIVR1 L1
            INNER JOIN NIRSER  NSER ON  L1.CODNIRSER  = NSER.CODNIRSER
            INNER JOIN NIRSTOC NS   ON  NS.CODNIRSTOC = L1.CODNIRSTOC
            INNER JOIN NSERII  S    ON  S.CODSERIE    = NSER.CODSERIE
          WHERE l1.codlivr1::varchar IN (SELECT VALOARE FROM tmp_manevra_liste WHERE filtru = 'CODLIVR1')
          GROUP BY L1.CODIES1, S.SERIE, Coalesce( NSER.TG, NS.TG)
          ) S
    WHERE s.nrcrt &lt;= 10
    GROUP BY S.CODTRANSF1, s.total_ns;
  END IF;

  IF  pCant = PKG_LIST_BASE_UTILS_CT_CANT() THEN
    INSERT INTO tmp_manevra_serii(codnirstoc, flag, serii, serii_ies, tg, nrcertif, dataprod, serii_aux1, serii_aux2, serii_obs)
    SELECT s.codnirstoc, pCant,
       CASE
          WHEN  s.tipserie = 1 THEN string_agg( s.serie,',')             || CASE WHEN  s.total_ns &gt; 10 THEN '...' ELSE '' END
          WHEN  s.tipserie = 2 THEN string_agg( s.serie,',')
       END  SERIE,
       CASE
          WHEN  s.tipserie = 1 THEN string_agg( s.sernocant,',')         || CASE WHEN  s.total_ns &gt; 10 THEN '...' ELSE '' END
          WHEN  s.tipserie = 2 THEN string_agg( s.sernocant,',')
       END  SERNOCANT,
       CASE
          WHEN  s.tipserie = 1 THEN string_agg( s.TG,',')                || CASE WHEN  s.total_ns &gt; 10 THEN '...' ELSE '' END
          WHEN  s.tipserie = 2 THEN string_agg( s.TG,',')
       END  TG,
       CASE
          WHEN  s.tipserie = 1 THEN string_agg( s.nrcertif,',')          ||  CASE WHEN  s.total_ns &gt; 10 THEN '...' ELSE '' END
          WHEN  s.tipserie = 2 THEN string_agg( s.nrcertif,',')
       END  NRCERTIF,
       CASE
          WHEN  s.tipserie = 1 THEN string_agg( s.dataprod::varchar,',') || CASE WHEN  s.total_ns &gt; 10 THEN '...' ELSE '' END
          WHEN  s.tipserie = 2 THEN string_agg( s.dataprod::varchar,',')
       END  DATAPROD,
       CASE
          WHEN  s.tipserie = 1 THEN string_agg( s.divizor::varchar,',')  || CASE WHEN  s.total_ns &gt; 10 THEN '...' ELSE '' END
          WHEN  s.tipserie = 2 THEN string_agg( s.divizor::varchar,',')
       END  DIVIZOR,
       CASE
          WHEN  s.tipserie = 1 THEN string_agg( s.bucati::varchar,',')   || CASE WHEN  s.total_ns &gt; 10 THEN '...' ELSE '' END
          WHEN  s.tipserie = 2 THEN string_agg( s.bucati::varchar,',')
       END  BUCATI,
       CASE
          WHEN  s.tipserie = 1 THEN string_agg( s.obs,',')               || CASE WHEN  s.total_ns &gt; 10 THEN '...' ELSE '' END
          WHEN  s.tipserie = 2 THEN string_agg( s.obs,',')
       END  OBS
    FROM (
          SELECT ns.codnirstoc, ns.tipserie,
                 ROW_NUMBER() over (PARTITION BY ns.codnirstoc ORDER BY s.serie) NRCRT,
                 COUNT( ns.codnirstoc) over (PARTITION BY ns.codnirstoc) TOTAL_NS,
                 s.serie || CASE WHEN  tipserie = 2 THEN ' ( ' || trunc(nser.cantnir) || ' ) ' ELSE '' END  SERIE,
                 s.serie SERNOCANT, to_char( Coalesce( NSER.TG, NS.TG),'dd.mm.yyyy') TG, c.nrcertif, nser.dataprod, nser.divizor, nser.bucati, nser.obs
          FROM nirstoc ns
            INNER JOIN nirser nser ON  ns.codnirstoc = nser.codnirstoc
            INNER JOIN nserii s    ON  s.codserie    = nser.codserie
            LEFT  JOIN certif c    ON  c.codcertif   = nser.codcertif
          WHERE ns.codnirstoc::varchar IN (SELECT VALOARE FROM tmp_manevra_liste WHERE filtru = 'CODNIRSTOC')
          ORDER BY ns.codnirstoc , ns.tipserie
          ) s
    WHERE s.nrcrt &lt;= 10
    GROUP BY s.codnirstoc, s.tipserie, s.total_ns;
  END IF;

  IF  pCant = PKG_LIST_BASE_UTILS_CT_STOC_M() THEN
    INSERT INTO tmp_manevra_serii(codnirstoc, serii, flag, TG)
    SELECT codnirstoc,
           CASE
             WHEN  tipserie = 1 THEN string_agg( serie,',') || CASE WHEN  Max( total_ns) &gt; 10 THEN '...' ELSE '' END
             WHEN  tipserie = 2 THEN string_agg( serie,',')
           END  SERIE,
           PKG_LIST_BASE_UTILS_CT_STOC_M(),
           CASE
             WHEN  tipserie = 1 THEN string_agg( TG,',') || CASE WHEN  Max( total_ns) &gt; 10 THEN '...' ELSE '' END
             WHEN  tipserie = 2 THEN string_agg( TG,',')
           END  TG
    FROM (
          SELECT codnirstoc,
                 CASE
                   WHEN  tipserie=1 THEN serie
                   WHEN  tipserie=2 THEN serie || ' ( ' || rest || ' ) '
                   ELSE  ''
                  END  SERIE,
                  row_number() over (PARTITION BY codnirstoc ORDER BY serie) NRCRT,
                  COUNT( codnirstoc) over (PARTITION BY codnirstoc) TOTAL_NS,
                  tipserie, rest, to_char( TG,'dd.mm.yyyy') TG
          FROM TMP_MANEVRA_NIRSER
          WHERE rest &gt; 0
          ORDER BY codnirstoc , tipserie , serie
        ) A_PG
    WHERE nrcrt &lt;= 10
    GROUP BY codnirstoc, tipserie, rest;
  END IF;

  IF  pCant = PKG_LIST_BASE_UTILS_CT_REST() THEN
    INSERT INTO tmp_manevra_serii(codnirstoc, serii, flag, TG)
    SELECT s.codnirstoc,
           CASE
              WHEN  s.tipserie = 1 THEN string_agg( s.serie,',') || CASE WHEN  s.rest &gt; 10 THEN '...' ELSE '' END
              WHEN  s.tipserie = 2 THEN string_agg( s.serie,',')
           END  SERIE, PKG_LIST_BASE_UTILS_CT_REST(),
           CASE
              WHEN  s.tipserie = 1 THEN string_agg( s.TG,',') || CASE WHEN  s.rest &gt; 10 THEN '...' ELSE '' END
              WHEN  s.tipserie = 2 THEN string_agg( s.TG,',')
           END  TG
    FROM (
          SELECT ns.codnirstoc,
                 CASE
                    WHEN  tipserie = 1 THEN s.serie
                    WHEN  tipserie = 2 THEN s.serie || ' ( ' || nser.cantnir || ' ) '
                    ELSE ''
                 END  SERIE,
                 row_number() over (PARTITION BY ns.codnirstoc ORDER BY s.serie) NRCRT,
                 COUNT( ns.codnirstoc) over (PARTITION BY ns.codnirstoc) TOTAL_NS,
                 ns.tipserie, ns.rest, to_char( Coalesce( NSER.TG, NS.TG),'dd.mm.yyyy') TG
          FROM nirstoc ns
            INNER JOIN nirser nser ON  ns.codnirstoc = nser.codnirstoc
            INNER JOIN nserii s    ON  s.codserie    = nser.codserie
          WHERE ns.codnirstoc::varchar IN (SELECT VALOARE FROM tmp_manevra_liste WHERE filtru = 'CODNIRSTOC') AND  ns.rest &gt; 0
          ORDER BY ns.codnirstoc , ns.tipserie , s.serie
        ) s
    WHERE s.nrcrt &lt;= 10
    GROUP BY s.codnirstoc, s.tipserie, s.rest;
  END IF;

  IF  pCant = PKG_LIST_BASE_UTILS_CT_LIVR() THEN
    INSERT INTO tmp_manevra_serii(codnirstoc, serii, flag, Codlivr1, TG)
    SELECT s.codnirstoc,
           CASE
              WHEN  s.tipserie = 1 THEN string_agg( s.serie,',') || CASE WHEN  s.cant &gt; 10 THEN '...' ELSE '' END
              WHEN  s.tipserie = 2 THEN string_agg( s.serie,',')
           END  SERIE,
           PKG_LIST_BASE_UTILS_CT_LIVR(), CODLIVR1,
           CASE
              WHEN  s.tipserie = 1 THEN string_agg( s.TG,',') || CASE WHEN  s.cant &gt; 10 THEN '...' ELSE '' END
              WHEN  s.tipserie = 2 THEN string_agg( s.TG,',')
           END  TG
    FROM (
          SELECT ns.codnirstoc,
                 CASE
                   WHEN  tipserie = 1 THEN s.serie
                   WHEN  tipserie = 2 THEN s.serie || ' ( ' || nser.cantnir || ' ) '
                   ELSE ''
                 END  SERIE,
                 row_number() over (PARTITION BY ns.codnirstoc ORDER BY s.serie) NRCRT,
                 COUNT( ns.codnirstoc) over (PARTITION BY ns.codnirstoc) TOTAL_NS,
                 ns.tipserie, livr1.cant, LIVR1.CODLIVR1, to_char( Coalesce( NSER.TG, NS.TG),'dd.mm.yyyy') TG
          FROM nirstoc ns
            INNER JOIN nirser nser ON  ns.codnirstoc = nser.codnirstoc
            INNER JOIN nserii s    ON  s.codserie    = nser.codserie
            INNER JOIN livr1       ON  ns.codnirstoc = livr1.codnirstoc
          WHERE ns.codnirstoc::varchar IN (SELECT VALOARE FROM tmp_manevra_liste WHERE filtru = 'CODNIRSTOC')
          ORDER BY ns.codnirstoc , ns.tipserie , s.serie
        ) s
    WHERE s.nrcrt &lt;= 10
    GROUP BY s.codnirstoc, s.tipserie, s.cant, S.CODLIVR1;
  END IF;

  IF  pCant = PKG_LIST_BASE_UTILS_CT_toate() THEN
    INSERT INTO tmp_manevra_serii(codnirstoc, serii, serii_aux1, tg, serii_obs, nrcertif)
    SELECT codnirstoc,
          fnc_array_to_vc3200(array_agg(serie||(CASE WHEN cant=1 THEN '' ELSE '('||cant||')' END) ORDER BY SERIE)) SERII,
          fnc_array_to_vc3200(array_agg(serie    ORDER BY SERIE)) SER,
          fnc_array_to_vc3200(array_agg(tg       ORDER BY SERIE)) TG,
          fnc_array_to_vc3200(array_agg(obs      ORDER BY SERIE)) OBS,
          fnc_array_to_vc3200(array_agg(nrcertif ORDER BY SERIE)) nrcertif
    FROM (
          SELECT ns.codnirstoc, Max( ns.tipserie) TIPSERIE, s.serie, Sum( nser.cantnir) CANT,
                 TO_CHAR( Coalesce( nser.tg, ns.tg), 'dd.mm.yyyy') TG, nser.obs,c.nrcertif
          FROM nirstoc ns
            INNER JOIN nirser nser ON  ns.codnirstoc = nser.codnirstoc
            INNER JOIN nserii s    ON  s.codserie    = nser.codserie
            LEFT JOIN certif  c    ON c.codcertif    = nser.codcertif
          WHERE ns.codnirstoc::varchar IN (SELECT VALOARE FROM tmp_manevra_liste WHERE filtru = 'CODNIRSTOC')
          GROUP BY ns.codnirstoc, s.serie, Coalesce( nser.tg, ns.tg), nser.obs, c.nrcertif
         ) B_PG
    GROUP BY codnirstoc;

    INSERT INTO tmp_manevra_serii(codlivr1, serii_ies, serii_aux1, tg, serii_obs, nrcertif)
    SELECT codlivr1,
           fnc_array_to_vc3200(array_agg(serie||(CASE WHEN cant=1 THEN '' ELSE '('||cant||')' END) ORDER BY SERIE)) SERII,
           fnc_array_to_vc3200(array_agg(serie    ORDER BY SERIE)) SER,
           fnc_array_to_vc3200(array_agg(tg       ORDER BY SERIE)) TG,
           fnc_array_to_vc3200(array_agg(obs      ORDER BY SERIE)) OBS,
           fnc_array_to_vc3200(array_agg(nrcertif ORDER BY SERIE)) nrcertif
    FROM (
          SELECT l1.codlivr1, Max( ns.tipserie) TIPSERIE, s.serie, Sum( l1.cant) CANT, TO_CHAR( Coalesce( nser.tg, ns.tg), 'dd.mm.yyyy') TG, nser.obs, c.nrcertif
          FROM nirstoc ns
            INNER JOIN livr1   l1   ON  l1.codnirstoc  = ns.codnirstoc
            INNER JOIN nirser  nser ON  nser.codnirser = l1.codnirser
            INNER JOIN nserii  s    ON  s.codserie     = nser.codserie
            INNER JOIN nartobj nobj ON  nobj.codobiect = ns.codobiect
            INNER JOIN nart    n    ON  n.codarticol   = nobj.codarticol
            LEFT JOIN certif   c    ON  c.codcertif    = l1.codcertif
          WHERE ns.codnirstoc::varchar IN (SELECT VALOARE FROM tmp_manevra_liste WHERE filtru = 'CODNIRSTOC')
          GROUP BY l1.codlivr1, s.serie, Coalesce( nser.tg, ns.tg), nser.obs, c.nrcertif
         ) C_PG
    GROUP BY codlivr1;
  END IF;
  PERFORM pkg_globals_SetSeparator( ',');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_calc_match_tva</obj_name>
  <obj_hashval>9e2ae80f23142e695f67f62157bb5443</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_calc_match_tva(p_tipdoc numeric, p_an numeric, p_luna numeric, p_cant numeric, p_pu numeric, p_tva numeric, p_codobiect numeric DEFAULT 0, p_proctvaart numeric DEFAULT '-1'::integer, p_rotefatc numeric DEFAULT 0, p_returnproc numeric DEFAULT 1)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAL           numeric := p_An * 12 + p_Luna;
  vProcTVA      numeric := PKG_LIST_BASE_UTILS_CALC_PROC_TVA(p_TipDoc, p_An, p_Luna, p_Cant, p_PU, p_TVA, p_CodObiect, p_ProcTvaArt, p_RotEfatc);
  rezCazTva     numeric;
  rezProcTVA    numeric;
BEGIN
  --Florin 01.02.2023 - fixat 60822
  --Florin 31.01.2024 - fixat 60798
  SELECT out_caztva, out_proctva FROM pkg_list_base_utils_MATCH_TVA_COMBI(vProcTVA, vAL, rezCazTva, rezProcTVA) INTO rezCazTva, rezProcTVA;

  IF p_ReturnProc = 1
  THEN RETURN rezProcTVA;
  ELSE RETURN rezCazTva ;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_calc_proc_tva</obj_name>
  <obj_hashval>82bff31cb4840e8ee9acb3ffa9449c59</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_calc_proc_tva(p_tipdoc numeric, p_an numeric, p_luna numeric, p_cant numeric, p_pu numeric, p_tva numeric, p_codobiect numeric DEFAULT 0, p_proctvaart numeric DEFAULT '-1'::integer, p_rotefatc numeric DEFAULT 0)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vProcTVA      numeric;
  vAL           numeric := p_An * 12 + p_Luna;
  vPUIncludeTVA numeric := CASE WHEN p_TipDoc IN (3, 16, 21) THEN 1 ELSE 0 END;
  vProcTvaArt   numeric := p_ProcTvaArt;
  vCant         numeric := Coalesce(p_Cant,0);
  vPU           numeric := Coalesce(p_PU,  0);
  vTVA          numeric := Coalesce(p_TVA, 0);
  vVal          numeric := CASE p_RotEfatc WHEN 1 THEN Round(vCant*vPU,2) ELSE vCant*vPU END;
BEGIN
  --Florin 20.11.2025 - sinc. Oracle
  vProcTvaArt := Coalesce(p_ProcTvaArt, -1);

   IF vTva = 0 AND vVal &lt;&gt; 0 THEN
    vProcTVA := 0;
  ELSIF vProcTvaArt = -1 AND Coalesce(p_CodObiect, 0) &gt; 0 THEN
    SELECT T1.PROCENT INTO vProcTvaArt
    FROM nartobj o
      LEFT JOIN nart1 a1 ON a1.codarticol = o.codarticol AND vAL BETWEEN a1.alstart AND a1.alstop
      LEFT JOIN ntva1 t1 ON t1.codtva     = a1.codtva    AND vAL BETWEEN t1.alstart AND t1.alstop
    WHERE o.CodObiect = p_CodObiect;
  END IF;

  IF    vTva = 0         THEN vProcTVA := 0;
  ELSIF vProcTvaArt = -1 THEN vProcTVA := CASE
                                            WHEN                    vPUIncludeTVA = 1 AND vVal=vTva                                           THEN 0
                                            WHEN                    vPUIncludeTVA = 1                                                         THEN 100*vTVA/(vVal-vTva)
                                            WHEN                                          vVal = 0                                            THEN 0
                                            ELSE                                                                                                   100*vTVA/vVal
                                          END;
  ELSIF Abs(vVal) &lt; 1    THEN vProcTVA := vProcTvaArt;
  ELSE                        vProcTVA := CASE
                                            WHEN vVal = 0       AND                       vTVA = 0                                            THEN vProcTvaArt
                                            WHEN p_RotEfatc = 1 AND vPUIncludeTVA = 1 AND vTVA = Round(vVal*vProcTvaArt/(100+vProcTvaArt), 2) THEN vProcTvaArt
                                            WHEN p_RotEfatc = 1 AND                       vTVA = Round(vVal*vProcTvaArt/100              , 2) THEN vProcTvaArt
                                            WHEN                    vPUIncludeTVA = 1 AND vTVA = Round(vVal*vProcTvaArt/(100+vProcTvaArt), 7) THEN vProcTvaArt
                                            WHEN                                          vTVA = Round(vVal*vProcTvaArt/100              , 7) THEN vProcTvaArt
                                            WHEN                    vPUIncludeTVA = 1 AND vTVA = vVal                                         THEN vProcTvaArt
                                            WHEN                    vPUIncludeTVA = 1                                                         THEN 100*vTVA/(vVal-vTva)
                                            WHEN                                          vVal = 0                                            THEN vProcTvaArt
                                            ELSE                                                                                                   100*vTVA/vVal
                                          END;
  END IF;
  RETURN vProcTVA;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_clear_simbol_lipsa</obj_name>
  <obj_hashval>3406b644fb15513f720dedc31f2acc4c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_clear_simbol_lipsa()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vListSimbLipsa','',false);
  DELETE FROM TMP_LIPSA_CORESP_PLANP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_cond_subunit</obj_name>
  <obj_hashval>2017c39d25e9a886ba884a9949df5523</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_cond_subunit(INOUT wme_result character varying, INOUT ptabla character varying, INOUT pcoloana character varying, INOUT pprefix character varying, INOUT psubunit numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult  varchar;
  vSubunit numeric := Coalesce(pSubunit, getsubunitate());
  vTabla   varchar := Trim(pTABLA);
  vColoana VARCHAR := Trim(pCOLOANA);
  vPrefix  varchar := Trim(pPrefix);

BEGIN
  -- STEF 21.01.2021
  WME_Result := pkg_list_base_utils_cond_subunit(ptabla, pcoloana, pprefix, psubunit) ;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_cond_subunit</obj_name>
  <obj_hashval>62dfa944b5d3b183a9414e1bba8bdd0a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_cond_subunit(ptabla character varying, pcoloana character varying DEFAULT NULL::character varying, pprefix character varying DEFAULT NULL::character varying, psubunit numeric DEFAULT NULL::numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult  VARCHAR;
  vSubunit NUMERIC := Coalesce(pSubunit, getsubunitate());
  vTabla   VARCHAR := Trim(pTABLA);
  vColoana VARCHAR := Trim(pCOLOANA);
  vPrefix  VARCHAR := Trim(pPrefix);
BEGIN
  --Florin 20.06.2025 - fixat 65964
  -- Adina 19 august 2020
  -- Bogdan 03.09.2020 - default null
  IF COALESCE(Length(vColoana),0) = 0 THEN vColoana := 'SUBUNITATEA'; END IF;
  IF vPrefix IS NULL THEN vPrefix  := ' AND';        END IF;

  IF COALESCE(Length(vTabla),0) = 0
  THEN sResult := vPrefix || ' ' || vColoana;
  ELSE sResult := vPrefix || ' ' || vTABLA || '.' || vColoana;
  END IF;

  IF    vSubunit = 0  THEN
    sResult := '';
  ELSIF vSubunit &lt;&gt; 1 THEN
    sResult := sResult || ' = ' || vSubunit::varchar || ' ';
  ELSIF Coalesce(fnc_getvalconstanta('CumulatFirmaToateSub', getANLUCRU(), getLUNALUCRU())::numeric ,2) = 2 THEN
    sResult := sResult ||' IN (SELECT codsubunit FROM tmp_subunitdedicate)';
  ELSE
    sResult := '';
  END IF;

  IF sResult = ''  AND (  Upper(vPrefix) LIKE '%WHERE%' OR Upper(vPrefix) LIKE '%OR%') THEN
    sResult := vPrefix || ' 1=1';
  END IF;

  RETURN sResult;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_cond_subunitinclactiv</obj_name>
  <obj_hashval>a79fb5ac43a45c5fc67c82385553dbcb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_cond_subunitinclactiv(ptabla character varying, pcoloana character varying DEFAULT NULL::character varying, pprefix character varying DEFAULT NULL::character varying, psubunit numeric DEFAULT NULL::numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult  VARCHAR;
  vSubunit NUMERIC := Coalesce(pSubunit, getsubunitate());
  vTabla   VARCHAR := Trim(pTABLA);
  vColoana VARCHAR := Trim(pCOLOANA);
  vPrefix  VARCHAR := Trim(pPrefix);
BEGIN
  -- Laura 17.12.2021 - sinc. Oracle (17.12.2021)
  -- Adina 19 august 2020
  -- Bogdan 03.09.2020 - default null
  -- Florin 20.05.2021 - sincron Oracle
  IF COALESCE(Length(vColoana),0) = 0 THEN vColoana := 'SUBUNITATEA'; END IF;
  IF COALESCE(Length(vPrefix), 0) = 0 THEN vPrefix  := ' AND';        END IF;

  IF COALESCE(Length(vTabla),0) = 0
  THEN sResult := vPrefix || ' (' || vColoana;
  ELSE sResult := vPrefix || ' (' || vTABLA || '.' || vColoana;
  END IF;

  IF vSubunit = 0  THEN
    sResult := '';
  ELSIF vSubunit &lt;&gt; 1 THEN
    sResult := sResult || ' = ' || vSubunit::varchar || ' OR C.ACTIV = 3';
  ELSIF Coalesce(fnc_getvalconstanta('CumulatFirmaToateSub', getANLUCRU(), getLUNALUCRU())::numeric ,2) = 2 THEN
    sResult := sResult ||' IN (SELECT codsubunit FROM tmp_subunitdedicate)';
  ELSE
    sResult := '';
  END IF;

  IF sResult = ''  AND (  Upper(vPrefix) LIKE '%WHERE%' OR Upper(vPrefix) LIKE '%OR%') THEN
    sResult := vPrefix || ' 1=1';
  ELSE IF NOT sResult = '' THEN sResult := sResult||')';
  END IF;
  END IF;

  RETURN sResult;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_cond_userid</obj_name>
  <obj_hashval>096f6c0e6dacf6e02963c180e205d994</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_cond_userid(INOUT wme_result character varying, INOUT ptabla character varying, INOUT pcoloana character varying, INOUT pprefix character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vFiltru  BOOLEAN;
  sResult  varchar := '';
  vTabla   varchar := Trim(pTABLA);
  vColoana VARCHAR := Trim(pCOLOANA);
  vPrefix  varchar := Trim(pPrefix);
BEGIN
  --Adina 10 august 2020
  vFiltru :=  Coalesce(current_setting('PKG_GLOBALS.USERID', true)::numeric, 0) &gt; 0;

  IF vFiltru THEN
    vFiltru :=  Coalesce( (SELECT fnc_getvalconstanta('LstUserCurent', getANLUCRU(), getLUNALUCRU())::numeric), 0) = 1;
  END IF;

  IF vFiltru THEN
    vFiltru :=  Coalesce( (SELECT fnc_getvalconstanta('DocUserCurent', getANLUCRU(), getLUNALUCRU())::numeric), 0) = 1;
  END IF;

  IF vFiltru THEN
    IF COALESCE(Length(vTabla),0) = 0 THEN     --pTABLA IS NULL
      sResult := vPrefix || ' ' || vCOLOANA;
    ELSE
      sResult := vPrefix || ' ' || vTABLA || '.' || vCOLOANA;
    END IF;
    sResult := sResult || ' = ' || current_setting('PKG_GLOBALS.USERID', true) || ' ';
  END IF;

  IF Upper( vPREFIX) LIKE '%WHERE%' AND sResult = ''  THEN  --IS NULL
    sResult := vPrefix || ' 1=1';
  END IF;

  WME_Result :=  sResult;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_cond_userid</obj_name>
  <obj_hashval>13ee111ed74e1c4f15bf05eebc48f19f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_cond_userid(ptabla character varying DEFAULT NULL::character varying, pcoloana character varying DEFAULT 'USERID'::character varying, pprefix character varying DEFAULT ' AND'::character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vFiltru  BOOLEAN;
  sResult  varchar := '';
  vTabla   varchar := Trim(pTABLA);
  vColoana VARCHAR := Trim(pCOLOANA);
  vPrefix  varchar := Trim(pPrefix);
BEGIN
  --Stef 01.08.2022
  vFiltru :=  Coalesce(current_setting('PKG_GLOBALS.USERID', true)::numeric, 0) &gt; 0;
  IF vFiltru THEN vFiltru :=  Coalesce( (SELECT fnc_getvalconstanta('LstUserCurent', getANLUCRU(), getLUNALUCRU())::numeric), 0) = 1; END IF;
  IF vFiltru THEN vFiltru :=  Coalesce( (SELECT fnc_getvalconstanta('DocUserCurent', getANLUCRU(), getLUNALUCRU())::numeric), 0) = 1; END IF;
  IF vFiltru THEN
    IF NULLIF(vTabla, '')  IS NULL
    THEN sResult := vPrefix||' '||vCOLOANA;
    ELSE sResult := vPrefix||' '||vTABLA||'.'||vCOLOANA;
    END IF;
    sResult := sResult || ' = ' || current_setting('PKG_GLOBALS.USERID', true) || ' ';
  END IF;

  IF Upper(vPREFIX) LIKE '%WHERE%' AND sResult = '' THEN  --IS NULL
    sResult := vPrefix||' 1=1';
  END IF;

  RETURN sResult;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_creazatabela</obj_name>
  <obj_hashval>04902eac9c223d6af2e5d017904f77d3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_creazatabela(asql character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 05.03.2025
  begin
    execute aSQL;
  exception when others then null;
  end;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_ct_cant</obj_name>
  <obj_hashval>8513d43c660cd230f5496450aff889c8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_ct_cant()
 RETURNS numeric
 LANGUAGE sql
AS $function$
  --Stef 12.05.2022
  SELECT 0::numeric;
 $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_ct_codnirser</obj_name>
  <obj_hashval>f60c37a761d5e94dea027b24c672c00f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_ct_codnirser()
 RETURNS numeric
 LANGUAGE sql
AS $function$
  --Stef 12.05.2022
  SELECT 7::numeric;
 $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_ct_livr</obj_name>
  <obj_hashval>bf4dc8a58dedc7d38acdde3ab5eb4b3d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_ct_livr()
 RETURNS numeric
 LANGUAGE sql
AS $function$
  --Stef 12.05.2022
  SELECT 2::numeric;
 $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_ct_modifpret</obj_name>
  <obj_hashval>a5e9171de6a3c4b45f5b769e44a2d6ac</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_ct_modifpret()
 RETURNS numeric
 LANGUAGE sql
AS $function$
  --Stef 12.05.2022
  SELECT 6::numeric;
 $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_ct_rest</obj_name>
  <obj_hashval>fcff628ebebb447714e2e8bf9d90535e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_ct_rest()
 RETURNS numeric
 LANGUAGE sql
AS $function$
  --Stef 12.05.2022
  SELECT 1::numeric;
 $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_ct_stoc_m</obj_name>
  <obj_hashval>de30acd78a7b1624445146bac59f7d23</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_ct_stoc_m()
 RETURNS numeric
 LANGUAGE sql
AS $function$
  --Stef 12.05.2022
  SELECT 4::numeric;
 $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_ct_toate</obj_name>
  <obj_hashval>8f277c5fca2f660e55734528a5b27377</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_ct_toate()
 RETURNS numeric
 LANGUAGE sql
AS $function$
  --Stef 12.05.2022
  SELECT 3::numeric;
 $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_ct_transf</obj_name>
  <obj_hashval>2c49db9737b3b9de3a0123bce6292a47</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_ct_transf()
 RETURNS numeric
 LANGUAGE sql
AS $function$
  --Stef 12.05.2022
  SELECT 5::numeric;
 $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_decode_icont</obj_name>
  <obj_hashval>ee6154dd4df10ecba38ac11960e4756a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_decode_icont(INOUT wme_result character varying, INOUT picont numeric, INOUT pcodpart numeric, INOUT panluna numeric, INOUT psemnif numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult varchar;
begin
  --Bogdan 03.09.2020
  BEGIN
    SELECT simbol INTO sResult FROM ncont WHERE codcont =  PKG_LIST_BASE_UTILS_icont_CodCont(pIcont, pCodPart, pAnluna, pSemnif);
  EXCEPTION WHEN OTHERS THEN
    sResult := '... Nedefinit ...';
  END;

  WME_Result :=  sResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_decode_icont</obj_name>
  <obj_hashval>da6c40d9a05ab6e067c9987fcfd42e8e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_decode_icont(picont numeric, pcodpart numeric, panluna numeric, psemnif numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult varchar;
BEGIN
  --Adina 08 septembrie 2020
  BEGIN
    SELECT simbol INTO sResult FROM ncont WHERE codcont =  PKG_LIST_BASE_UTILS_icont_CodCont(pIcont, pCodPart, pAnluna, pSemnif);
  EXCEPTION WHEN OTHERS THEN
    sResult := '... Nedefinit ...';
  END;

  RETURN sResult;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_decode_inchideri</obj_name>
  <obj_hashval>7b181330efe107d7d852d6b71ea53ef7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_decode_inchideri(INOUT wme_result character varying, INOUT ptipinchidere numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vNume varchar;
begin
  vNume := CASE pTipInchidere
             WHEN 1 THEN 'Corectie adaos marfa'
             WHEN 2 THEN 'Participatiune'
             WHEN 3 THEN 'Sincronizare conturi'
             WHEN 4 THEN 'Inchid.rulaj curent debit'
             WHEN 5 THEN 'Inchid.rulaj curent credit'
             WHEN 6 THEN 'Inchidere sold'
             ELSE        'Alte inchideri'
           END ;
  WME_Result :=  vNume;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_decode_luna</obj_name>
  <obj_hashval>85392df72ecfc78c96650fa5307952e8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_decode_luna(pluna numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult varchar;
BEGIN
 sResult :=  CASE pLuna
               WHEN  1 THEN 'Ianuarie'
               WHEN  2 THEN 'Februarie'
               WHEN  3 THEN 'Martie'
               WHEN  4 THEN 'Aprilie'
               WHEN  5 THEN 'Mai'
               WHEN  6 THEN 'Iunie'
               WHEN  7 THEN 'Iulie'
               WHEN  8 THEN 'August'
               WHEN  9 THEN 'Septembrie'
               WHEN 10 THEN 'Octombrie'
               WHEN 11 THEN 'Noiembrie'
               WHEN 12 THEN 'Decembrie'
             END ;
 RETURN sResult;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_decode_luna</obj_name>
  <obj_hashval>f5744217845ca8973a842550826b9ce7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_decode_luna(pdata date)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult varchar;
begin
  sResult := to_char( pData, 'Month', 'NLS_DATE_LANGUAGE = romanian');
  RETURN sResult;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_decode_tipdoc</obj_name>
  <obj_hashval>2c3a54eacb43450d366b6166ec3ec573</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_decode_tipdoc(INOUT wme_result character varying, INOUT vtip numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult varchar;
begin
   --Bogdan 08.01.2020
  BEGIN
     SELECT NUMEEXT into strict sResult FROM tmp_machete   WHERE vTip = CodMacheta;
  exception WHEN others THEN
      sResult := '-';
  END;

  WME_Result := sResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_decode_tipdoc_scurt</obj_name>
  <obj_hashval>6f6d356eee639f0a4ef03fa26f417fc1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_decode_tipdoc_scurt(ptipdoc numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult varchar;
BEGIN
  --Florin 05.08.2020
  --Bogdan 08.01.2021
  BEGIN
    SELECT NUMEPRESC into strict sResult FROM tmp_machete WHERE pTipDoc = CodMacheta;
  EXCEPTION WHEN others THEN
    sResult := '-';
  END;
  RETURN sResult;
END ;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_decode_tipplata</obj_name>
  <obj_hashval>9f32319717e7e671d49b3a5a3e8756ad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_decode_tipplata(INOUT wme_result character varying, INOUT ptipplata numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sTipPlata varchar;
begin
  SELECT CASE
           WHEN  pTipPlata=2 THEN 'Numerar'
           WHEN  pTipPlata=3 THEN 'Ordin Plata'
           WHEN  pTipPlata=4 THEN 'Cec'
           WHEN  pTipPlata=5 THEN 'Bilet la Ordin'
           WHEN  pTipPlata=6 THEN 'Compensare'
           WHEN  pTipPlata=7 THEN 'Majorari'
           ELSE                   '...nedefinit...'
         END
  INTO sTipPlata;

  WME_Result :=  sTipPlata;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_decode_zi</obj_name>
  <obj_hashval>79eb3369645752110094bd19f5c32fbf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_decode_zi(INOUT wme_result character varying, INOUT pdata date)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult varchar;
  engDay  varchar;
begin
  engDay := Trim( TO_CHAR( pData, 'DAY', 'NLS_DATE_LANGUAGE=english'));
  sResult := CASE engDay
               WHEN 'MONDAY'    THEN 'Luni'
               WHEN 'TUESDAY'   THEN 'Marti'
               WHEN 'WEDNESDAY' THEN 'Miercuri'
               WHEN 'THURSDAY'  THEN 'Joi'
               WHEN 'FRIDAY'    THEN 'Vineri'
               WHEN 'SATURDAY'  THEN 'Sambata'
               WHEN 'SUNDAY'    THEN 'Duminica'
             END ;
  WME_Result :=  sResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_decode_zi</obj_name>
  <obj_hashval>e444720256cc53f9ff4b33e4f8486395</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_decode_zi(pdata date)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult varchar;
  engDay varchar;
BEGIN
  --Adina 28 septembrie 2020
  engDay := Trim( TO_CHAR( pData, 'DAY'));  --, 'NLS_DATE_LANGUAGE=english'

  sResult := CASE engDay
               WHEN 'MONDAY'    THEN 'Luni'
               WHEN 'TUESDAY'   THEN 'Marti'
               WHEN 'WEDNESDAY' THEN 'Miercuri'
               WHEN 'THURSDAY'  THEN 'Joi'
               WHEN 'FRIDAY'    THEN 'Vineri'
               WHEN 'SATURDAY'  THEN 'Sambata'
               WHEN 'SUNDAY'    THEN 'Duminica'
             END ;

  RETURN sResult;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_duma1</obj_name>
  <obj_hashval>56e894eb15cb480e04ff13416a241f01</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_duma1(INOUT wme_result character varying, INOUT pcodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_LIST_BASE_UTILS_SET_UMA( pCodObiect);
  WME_Result :=  current_setting('PKG_LIST_BASE_UTILS.vDUMA1', true);
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_duma2</obj_name>
  <obj_hashval>e4c3e2fcc74914338beea477d46b1a55</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_duma2(INOUT wme_result character varying, INOUT pcodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_LIST_BASE_UTILS_SET_UMA( pCodObiect);
  WME_Result :=  current_setting('PKG_LIST_BASE_UTILS.vDUMA2', true);
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_duma3</obj_name>
  <obj_hashval>5def56db5831e464488c1984cc38baa8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_duma3(INOUT wme_result character varying, INOUT pcodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_LIST_BASE_UTILS_SET_UMA( pCodObiect);
  WME_Result :=  current_setting('PKG_LIST_BASE_UTILS.vDUMA3', true);
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_ganfin</obj_name>
  <obj_hashval>235dc73d2b9daade05aa6faf46aaaacb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_ganfin(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.gAnFin', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_ganini</obj_name>
  <obj_hashval>9a4b949ea6769cb871916d83fdcde67b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_ganini(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.gAnIni', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_get_cod_monedafactinvaluta</obj_name>
  <obj_hashval>755f24b47ef736de52e5e2f9e643a77c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_get_cod_monedafactinvaluta(INOUT wme_result numeric, INOUT pan numeric, INOUT pluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAnLuna     numeric := pAn * 12 + pLuna;
  vAnLunaMFIV numeric;
begin
  --Bogdan 07.09.2020
  vAnLunaMFIV := Coalesce((case when current_setting('PKG_LIST_BASE_UTILS.vAnLunaMFIV', true) = '' then null
                                else current_setting('PKG_LIST_BASE_UTILS.vAnLunaMFIV', true)::numeric end), -1);

  IF  vAnLuna &lt;&gt; vAnLunaMFIV THEN
    PERFORM pkg_list_base_utils_SET_VAR_MonedaFactInValuta( vAnLuna);
  END IF;

  WME_Result := (case when current_setting('PKG_LIST_BASE_UTILS.vCodMFIV', true) = '' then null
                      else current_setting('PKG_LIST_BASE_UTILS.vCodMFIV', true)::numeric end);

  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_get_codconts</obj_name>
  <obj_hashval>cdb0df65c6a04a14c7281fadde885f12</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_get_codconts(v_codcont numeric, v_an numeric, v_luna numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_cod numeric;
begin
  --Florin 13.01.2022 - sinc. Oracle (29.12.2021)
  --BogdanL 28.07.2020
  BEGIN
   SELECT Coalesce(c1.contsecundar,0) INTO v_cod
   FROM ncont1 c1
        WHERE c1.codcont = v_codcont AND v_an*12+v_luna BETWEEN c1.ALSTART AND c1.ALSTOP;
  EXCEPTION WHEN OTHERS THEN
    v_cod := 0;
  END;
  return  v_cod;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_get_cont_ioart</obj_name>
  <obj_hashval>ae2da260145fc89fdaa4c00156ad42f3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_get_cont_ioart(INOUT wme_result character varying, INOUT v_icont numeric, INOUT v_codioart numeric, INOUT v_an numeric, INOUT v_luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  simbol  varchar;
  den_col varchar;
  sSchema varchar;
  vAL     VARCHAR := To_Char(V_AN*12+V_LUNA, 'fm99990');
begin
  --Florin 13.01.2022 - sinc. Orcale (29.12.2021)
  --Adina 29.03.2021 - get_schema
  sSchema := Lower(current_setting('PKG_GLOBALS.FIRMANAME', true));
  IF NULLIF(sSchema, '') IS NULL THEN
    sSchema := public.get_schema();
  END IF;

  IF  Coalesce( v_icont, -1) &gt; -1 THEN
    SELECT COLUMN_NAME INTO DEN_COL FROM information_schema.COLUMNS WHERE ORDINAL_POSITION = V_ICONT + 1 AND  TABLE_NAME = 'ioart1' AND table_schema = sSchema;
    EXECUTE 'SELECT SIMBOL  FROM NCONT WHERE CODCONT IN (' || 'SELECT ' || DEN_COL || ' FROM ' || 'IOART1 I1 WHERE I1.CODIOART = ' || v_codioart || ' AND '||vAL||' BETWEEN I1.ALSTART AND I1.ALSTOP) ';
    WME_Result :=  SIMBOL;
  RETURN;
  ELSE
    WME_Result :=  'nedef.';
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_get_cont_iopart</obj_name>
  <obj_hashval>eb5dd0f362394bd3e89a63ab75a52fc8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_get_cont_iopart(INOUT wme_result character varying, INOUT idx_col numeric, INOUT codpart numeric, INOUT semnif numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  DEN_COL varchar;
  SIMBOL  varchar;
  sSchema varchar;
BEGIN
  sSchema := Lower(current_setting('PKG_GLOBALS.FIRMANAME', true));
  IF NULLIF(sSchema, '') IS NULL THEN
    sSchema := public.get_schema();
  END IF;

  PERFORM PKG_LIST_BASE_UTILS_make_config_luna_iopart();
  IF  Coalesce( IDX_COL, -1) &lt;&gt; -1 THEN
    BEGIN
      IF SEMNIF IN (900, 901) THEN
        SELECT ncont.simbol INTO simbol FROM ncont WHERE codcont = idx_col;
      ELSE
        SELECT COLUMN_NAME
        INTO DEN_COL
        FROM information_schema.columns
        WHERE
           ORDINAL_POSITION = IDX_COL + 1 AND  TABLE_NAME = 'iopart1' AND table_schema = sSchema;

        BEGIN
          EXECUTE 'SELECT SIMBOL FROM NCONT WHERE CODCONT IN ' || '( SELECT ' || DEN_COL || ' FROM tmp_iopart_luna WHERE CODPART= ' || codpart || ') ' INTO SIMBOL;
        END;
      END IF;
    EXCEPTION WHEN OTHERS THEN
      simbol := 'nedefinit';
    END;

    WME_Result :=  SIMBOL;
    RETURN;
  ELSE
    WME_Result :=  'nedef.';
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_get_cont_iopers</obj_name>
  <obj_hashval>1e9595c2f4e1d8c5a92e27ac08174744</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_get_cont_iopers(INOUT wme_result character varying, INOUT idx_col numeric, INOUT codpart numeric, INOUT semnif numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  DEN_COL varchar;
  SIMBOL  varchar;
  sSchema varchar;
BEGIN
  sSchema := Lower(current_setting('PKG_GLOBALS.FIRMANAME', true));
  IF NULLIF(sSchema, '') IS NULL THEN
    sSchema := public.get_schema();
  END IF;

  IF  Coalesce( IDX_COL, -1) &lt;&gt; -1 THEN
    BEGIN
      IF SEMNIF IN (900, 901) THEN
        SELECT ncont.simbol INTO simbol FROM ncont WHERE codcont = idx_col;
      ELSE
        SELECT COLUMN_NAME
        INTO DEN_COL
        FROM information_schema.columns
        WHERE
           ORDINAL_POSITION = IDX_COL + 1 AND  TABLE_NAME = 'iopers1' AND table_schema = sSchema;

        BEGIN
          EXECUTE 'SELECT SIMBOL FROM NCONT WHERE CODCONT IN ' || '( SELECT ' || DEN_COL || ' FROM tmp_iopers_luna WHERE CODPERS= ' || codpart || ') ' INTO SIMBOL;
        END;
      END IF;
    EXCEPTION WHEN OTHERS THEN
      simbol := 'nedefinit';
    END;

    WME_Result :=  SIMBOL;
    RETURN;
  ELSE
    WME_Result :=  'nedef.';
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_get_cota_tva_art</obj_name>
  <obj_hashval>7aa728c79a5b1ffc27027ded668893af</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_get_cota_tva_art(INOUT wme_result numeric, INOUT v_codobiect numeric, INOUT v_an numeric, INOUT v_luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_cota numeric;
  vAL    numeric := v_an*12+v_luna;
begin
  --Florin 13.01.2022 - sinc. Oracle (29.12.2021)
  BEGIN
    SELECT ntva1.procent
    INTO v_cota
    FROM nartobj nobj
         INNER JOIN nart1 n1 ON nobj.codarticol = n1.codarticol AND vAL BETWEEN N1.ALSTART AND N1.ALSTOP
         LEFT JOIN ntva      ON  n1.codtva       = ntva.codtva
         LEFT JOIN ntva1 ON ntva.codtva = ntva1.codtva AND vAL BETWEEN ntva1.ALSTART AND ntva1.ALSTOP
    WHERE
       nobj.codobiect = v_codobiect;
  EXCEPTION WHEN OTHERS THEN
    v_cota := 0;
  END;
  WME_Result :=  v_cota;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_get_den_bancacurspuv</obj_name>
  <obj_hashval>14fe03551d769a3c1344388ab8d1d1c6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_get_den_bancacurspuv(INOUT wme_result character varying, INOUT pan numeric, INOUT pluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAnLuna NUMERIC := pAn * 12 + pLuna;
  val     varchar;
  valC    NUMERIC := 0;
BEGIN
  --Florin 18.06.2021 - fixat 50587
  --Florin 27.08.2020
  val := fnc_GetValConstanta('BancaCursPUV', pAn, pLuna);
  IF val &lt;&gt; '' AND val IS NOT NULL THEN valC := val::NUMERIC; END IF;
  IF vAnLuna &lt;&gt; Coalesce(CASE WHEN current_setting('PKG_LIST_BASE_UTILS.vAnLunaBCPUV', TRUE) = '' THEN NULL
            ELSE current_setting('PKG_LIST_BASE_UTILS.vAnLunaBCPUV', true)::NUMERIC END, -1)
  THEN
    PERFORM set_config('PKG_LIST_BASE_UTILS.vAnLunaBCPUV', vAnLuna::varchar, FALSE);
    PERFORM set_config('PKG_LIST_BASE_UTILS.vDenBCPUV', COALESCE((SELECT pkg_list_base_utils_get_den_banca.WME_RESULT FROM
      pkg_list_base_utils_get_den_banca(NULL, COALESCE(valC, 0))), ''), FALSE);
  END IF;
  WME_Result := COALESCE(current_setting('PKG_LIST_BASE_UTILS.vDenBCPUV', TRUE), '');
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_get_den_taxa</obj_name>
  <obj_hashval>2b7e27cfab62365efacf6fdb836869cf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_get_den_taxa(INOUT wme_result character varying, INOUT pcodtaxa numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vDenTaxa varchar;
begin
  BEGIN
    SELECT Den_Taxa INTO vDenTaxa FROM NTAXE WHERE CODTAXA = pCodTaxa;
  EXCEPTION WHEN OTHERS THEN
    WME_Result :=  NULL;
    RETURN;
  END;
  WME_Result :=  vDenTaxa;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_get_dencont_iopart</obj_name>
  <obj_hashval>a69aa75f3450668d34c3dbd375f2a78f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_get_dencont_iopart(INOUT wme_result character varying, INOUT idx_col numeric, INOUT codpart numeric, INOUT semnif numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  DEN_COL varchar;
  SIMBOL  varchar;
  sSchema varchar;
BEGIN
  sSchema := Lower(current_setting('PKG_GLOBALS.FIRMANAME', true));
  IF NULLIF(sSchema, '') IS NULL THEN
    sSchema := public.get_schema();
  END IF;

  PERFORM PKG_LIST_BASE_UTILS_make_config_luna_iopart();
  IF  Coalesce( IDX_COL, -1) &lt;&gt; -1 THEN
    BEGIN
      IF SEMNIF IN (900, 901) THEN
        SELECT ncont.den_cont INTO simbol FROM ncont WHERE codcont = idx_col;
      ELSE
        SELECT COLUMN_NAME INTO DEN_COL FROM information_schema.COLUMNS WHERE ORDINAL_POSITION = IDX_COL + 1 AND  TABLE_NAME = 'iopart1' AND table_schema = sSchema;

        BEGIN
          EXECUTE 'SELECT DEN_CONT FROM NCONT WHERE CODCONT IN ' || '( SELECT ' || DEN_COL || ' FROM tmp_iopart_luna WHERE CODPART= ' || codpart || ') ' INTO SIMBOL;
        END;
      END IF;
    EXCEPTION WHEN OTHERS THEN
      simbol := 'nedefinit';
    END;

    WME_Result :=  SIMBOL;
    RETURN;
  ELSE
    WME_Result :=  'nedefinit';
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_get_name_sec</obj_name>
  <obj_hashval>4bde36c13f5c0a39658588e4cddebe67</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_get_name_sec(INOUT wme_result character varying, INOUT v_codcont numeric, INOUT v_an numeric, INOUT v_luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_name varchar;
begin
  --Florin 13.01.2022 - sinc. Oracle (29.12.2021)
  --Bogdan 31.07.2020
  BEGIN
    SELECT cs.name INTO v_name
    FROM ncont1 c1 LEFT JOIN nconts cs ON c1.contsecundar = cs.codconts
    WHERE c1.codcont = v_codcont AND v_an*12+v_luna BETWEEN c1.ALSTART AND c1.ALSTOP;
  EXCEPTION WHEN OTHERS THEN
    v_name := '';
  END;
  WME_Result :=  v_name;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_get_name_ter</obj_name>
  <obj_hashval>aaa411e93898a61f4040a314b6cc9fd4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_get_name_ter(INOUT wme_result character varying, INOUT v_codcont numeric, INOUT v_an numeric, INOUT v_luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
v_name varchar;
begin
  --Florin 13.01.2022 - sinc. Oracle (29.12.2021)
  --Bogdan 31.07.2020
  BEGIN
    SELECT ct.name INTO v_name
    FROM ncont1 c1 LEFT JOIN ncontt ct ON c1.conttertiar = ct.codcontt
    WHERE c1.codcont = v_codcont AND v_an*12+v_luna BETWEEN c1.ALSTART AND c1.ALSTOP;
  EXCEPTION WHEN OTHERS THEN
    v_name := '';
  END;
  WME_Result :=  v_name;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_get_simb_monedafactinvaluta</obj_name>
  <obj_hashval>f1c6dc4afd0a6c6e6f463bc4dd7068f4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_get_simb_monedafactinvaluta(INOUT wme_result character varying, INOUT pan numeric, INOUT pluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAnLuna numeric := pAn * 12 + pLuna;
BEGIN
  --Florin 27.08.2020
  IF vAnLuna &lt;&gt; Coalesce(CASE WHEN current_setting('PKG_LIST_BASE_UTILS.vAnLunaMFIV', true) = '' then null
                              ELSE current_setting('PKG_LIST_BASE_UTILS.vAnLunaMFIV', true)::NUMERIC END, -1)
  THEN
    PERFORM pkg_list_base_utils_SET_VAR_MonedaFactInValuta(vAnLuna);
  END IF;
  WME_Result :=  current_setting('PKG_LIST_BASE_UTILS.vSimbMFIV', true);
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_get_simbol_sec</obj_name>
  <obj_hashval>8cbfb2f542a223e185cc5113f9b3d397</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_get_simbol_sec(INOUT wme_result character varying, INOUT v_codcont numeric, INOUT v_an numeric, INOUT v_luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_simb varchar;
begin
  --Florin 13.01.2022 - sinc. Oracle (29.12.2021)
  --Bogdan 31.07.2020
  BEGIN
    SELECT cs.simbol INTO v_simb
    FROM ncont1 c1 LEFT JOIN nconts cs ON c1.contsecundar = cs.codconts
    WHERE c1.codcont = v_codcont AND v_an*12+v_luna BETWEEN c1.ALSTART AND c1.ALSTOP;
  EXCEPTION WHEN OTHERS THEN
    v_simb := '';
  END;
  WME_Result :=  v_simb;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_get_simbol_ter</obj_name>
  <obj_hashval>2295524ca3cd5b4f244417cec4e5de5e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_get_simbol_ter(INOUT wme_result character varying, INOUT v_codcont numeric, INOUT v_an numeric, INOUT v_luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_simb varchar;
begin
  --Florin 13.01.2022 - sinc. Oracle (29.12.2021)
  --Bogdan 31.07.2020
  BEGIN
    SELECT ct.simbol INTO v_simb
    FROM ncont1 c1 LEFT JOIN ncontt ct ON c1.conttertiar = ct.codcontt
    WHERE c1.codcont = v_codcont AND v_an*12+v_luna BETWEEN c1.ALSTART AND c1.ALSTOP;
  EXCEPTION WHEN OTHERS THEN
    v_simb := '';
  END;
  WME_Result :=  v_simb;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_get_stocexterncamp</obj_name>
  <obj_hashval>4e41d1c7981341b5fcc1d48f832f814b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_get_stocexterncamp(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sStocExternCamp varchar;
begin
  sStocExternCamp := CASE fnc_GetValConstanta('StocExternCamp', getANLUCRU(), getlunalucru())
                       WHEN 1 THEN 'CODINTERN'
                       WHEN 3 THEN 'DENUMIRE'
                       WHEN 4 THEN 'CODOBIECT'
                       ELSE 'CODEXTERN'
                     END ;
  WME_Result :=  sStocExternCamp;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_get_stocexterncamp</obj_name>
  <obj_hashval>649c32b7bef9d99b156552e02199bed9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_get_stocexterncamp()
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sStocExternCamp varchar;
BEGIN
  --Adina 27 august 2020
  sStocExternCamp :=
    CASE fnc_getvalconstanta('StocExternCamp',getAnLucru(),getLunaLucru())::numeric
        WHEN 1 THEN 'CODINTERN'
        WHEN 3 THEN 'DENUMIRE'
        WHEN 4 THEN 'CODOBIECT'
        ELSE        'CODEXTERN'
    END;
  RETURN sStocExternCamp;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_get_termen_concedii</obj_name>
  <obj_hashval>d1fe86bac9ed49c2221a9ba1d8dc2c49</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_get_termen_concedii(adataini date, xdatafin date, acodcomanda1 numeric, auserid numeric)
 RETURNS date
 LANGUAGE plpgsql
AS $function$
DECLARE
  nr NUMERIC(10);
  odata date;
  aDataFin date;
  v_tmp record;
BEGIN
  --Florin 24.01.2024
  if xDataFin is null then
    select termen into aDataFin from comanda1 where codcomanda1 = aCodComanda1;
  else
    aDataFin := xDataFin;
  end if;

  nr := 0;
  for v_tmp in (
    select dela, panala
    from nperscvscol cv
         inner join npers p on p.codpers = cv.codpers
    where (cv.dela between aDataIni and aDataFin or cv.panala between aDataIni and aDataFin or
          aDataIni between cv.dela and cv.panala or aDataFin between cv.dela and cv.panala) and
          p.logonname = aUserID

  ) loop
    odata := v_tmp.dela;
    while odata &lt;= v_tmp.panala loop
      if odata between aDataIni and aDataFin then
        nr := nr + 1;
      end if;
      odata := odata + 1;
    end loop;
  end loop;
  return aDataFin + nr;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_get_tiparticol</obj_name>
  <obj_hashval>88338ea17d08b4394f92ed83286eb13c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_get_tiparticol(INOUT wme_result numeric, INOUT v_codobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_tip numeric;
begin
  SELECT tiparticol INTO v_tip
  FROM nartobj
       LEFT JOIN nart ON  nartobj.codarticol = nart.codarticol
  WHERE nartobj.codobiect = v_codobiect;

  WME_Result :=  v_tip;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getcodnirstoc_orig</obj_name>
  <obj_hashval>59a2ee259d4ca1ff6e93c0ff9ce8647e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getcodnirstoc_orig(INOUT wme_result numeric, INOUT vcodnirstoc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM tmp_manevra2;
  WME_Result :=  (SELECT PKG_LIST_BASE_UTILS_GETCODNIRSTOCPARINTE.WME_RESULT FROM PKG_LIST_BASE_UTILS_GETCODNIRSTOCPARINTE(NULL, vCodNIRSTOC));
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getcodnirstocparinte</obj_name>
  <obj_hashval>5d815620bd96b9a9d1a16c309040585b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getcodnirstocparinte(INOUT wme_result numeric, INOUT vcodnirstoc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
  DECLARE
    sCodNirStoc numeric;
    aCount      numeric;
  begin
    SELECT count ( *) INTO aCount FROM tmp_manevra2 WHERE codunic = vcodnirstoc;

    IF aCount &gt; 0 THEN
      WME_Result := 0;
      RETURN;
    END IF;

    INSERT INTO tmp_manevra2 (codunic) VALUES (vcodnirstoc);

    begin
      WITH RECURSIVE a (codnirstoc, codnirstocparinte) AS
      ( SELECT codnirstoc, codnirstocparinte FROM nirstoc WHERE codnirstoc = vCodNirStoc
        UNION ALL
        SELECT n.codnirstoc, n.codnirstocparinte FROM nirstoc n INNER JOIN a ON a.codnirstocparinte = n.codnirstoc
      )
      SELECT min (a.codnirstocparinte) into STRICT WME_Result FROM a;
    exception
    when others then
      WME_Result := vCodNirStoc;
    end;

    if WME_Result is null then WME_Result := vCODNIRSTOC; end if;
    RETURN;
  end;
  $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getcoefdiscmonetar</obj_name>
  <obj_hashval>f9cabbf47b7c23b883572bec567bce2f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getcoefdiscmonetar(INOUT wme_result numeric, INOUT pcodies numeric, INOUT ptiplinie character varying, INOUT pcodobiect numeric, INOUT pcontserv numeric, INOUT pcodioart numeric, INOUT ptipcoef numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  pkg_list_base_utils_getcoefdiscmonetar(pcodies, ptiplinie, pcodobiect, pcontserv, pcodioart, ptipcoef);
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getcursmediu</obj_name>
  <obj_hashval>0e4cdb8a82f77e933de7263dfa30de70</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getcursmediu(INOUT wme_result numeric, INOUT acodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCurs double precision;
begin
  BEGIN
    SELECT avg( curs) INTO aCurs
    FROM (
          SELECT ii.curs
          FROM nirstoc ns
               INNER JOIN intrari1 ii1 ON  ii1.codintr1 = ns.codintr1
               INNER JOIN intrari  ii  ON  ii.codintr   = ii1.codintr
               INNER JOIN nir          ON  ns.codnir    = nir.codnir and  ii.codintr = nir.codintr and  nir.tipnir = ii.tipdoc
          WHERE ii.tipdoc IN (1, 2, 3, 4, 7) and  ns.codobiect = acodobiect and  ns.rest &gt; 0
          union ALL
          SELECT ii.curs
          FROM nirstoc ns
               INNER JOIN dvi1     dvi1 ON  dvi1.coddvi1  = ns.coddvi1
               INNER JOIN dvi           ON  dvi.coddvi    = dvi1.coddvi
               INNER JOIN intrari1 ii1  ON  dvi1.codintr1 = ii1.codintr1
               INNER JOIN intrari  ii   ON  ii1.codintr   = ii.codintr and  dvi.codintr = ii.codintr
               INNER JOIN nir           ON  ns.codnir     = nir.codnir and  ii.codintr = nir.codintr and  nir.TIPNIR = ii.tipdoc
          WHERE ii.tipdoc = 5 and  ns.codobiect = acodobiect and  ns.rest &gt; 0
         ) A_PG;
  EXCEPTION WHEN others THEN
    aCurs := 0;
  END;
  WME_Result :=  aCurs;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getcursreferinta</obj_name>
  <obj_hashval>d062cbaad577adc7a2cda16b4eeccdec</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getcursreferinta(INOUT wme_result numeric, INOUT acodmoneda numeric, INOUT acodbanca numeric, INOUT adata character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Stef 02.02.2021
  WME_Result :=  pkg_list_base_utils_getcursreferinta(acodmoneda, acodbanca, adata);
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getcursreferinta</obj_name>
  <obj_hashval>f62ebb7e4053ea7b5473ce532c4c9c12</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getcursreferinta(acodmoneda numeric, acodbanca numeric, adata character varying)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aCURS double precision := 0;
BEGIN
  --Stef 02.02.2021
  aCurs := 0;
  FOR v_rec IN (
    SELECT Coalesce(VALOARE, 1) Curs
    FROM NMONEDE  N INNER JOIN NMONEDE1 N1 ON N.CODMONEDA = N1.CODMONEDA
    WHERE N1.CODBANCA = aCODBANCA
      AND N.CODMONEDA = aCODMONEDA
      AND N1.DATA &lt;= TO_DATE(aDATA, 'dd.mm.yyyy')
    ORDER BY N1.DATA DESC
  ) LOOP
    aCurs := v_rec.curs;
    EXIT;
  END LOOP;
  aCurs := Coalesce(NULLIF(aCurs,0), 1);
  RETURN aCURS;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getdendoc</obj_name>
  <obj_hashval>b6c2b5a0a828b2256176921e79345f89</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getdendoc(INOUT wme_result character varying, INOUT acoddoc numeric, INOUT atipdoc numeric, INOUT acoddoc1 numeric DEFAULT NULL::numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vResult varchar := '';
begin
  IF    Coalesce(aCodDoc,0) = 37 THEN vResult := 'Sal';
  ELSIF Coalesce(aCodDoc,0) = 52 THEN vResult := 'CheltuieliInAvans';
  ELSIF Coalesce(aCodDoc,0) &lt;&gt; 0 AND Coalesce(aCodDoc1,aCodDoc,0) &lt;&gt; 0 THEN
    perform pkg_list_base_utils_SetDateDoc(aCodDoc, aCodDoc1, aTipDoc);
    vResult := current_setting('PKG_LIST_BASE_UTILS.vSDD_DenDoc',True);
  END IF;
  WME_Result :=  vResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getdoccomcli</obj_name>
  <obj_hashval>eaac20624b0efc9629696b37a81866aa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getdoccomcli(INOUT wme_result character varying, INOUT acodliniecomanda numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
aDoc varchar := '';
BEGIN
  --Florin 01.02.2021 - rescris connect by prior
  BEGIN
  SELECT NrDoc::varchar || '/' || to_char(DataDoc, 'DD.MM.YYYY')
  INTO aDoc
    FROM (WITH RECURSIVE a (rootcodcomanda1, codcomanda1, NrDoc, DataDoc, TIPDOC, CODliniecomanda) AS(
              SELECT l.codcomanda1 rootcodcomanda1, l.codcomanda1, c.NrDoc,c.DataDoc, c.tipdoc, l.CODliniecomanda
              FROM  cmdlink l
                     INNER JOIN comanda1 c1 ON l.codliniecomanda = c1.codcomanda1
                     INNER JOIN comanda c   ON c1.codcomanda = c.codcomanda
                     LEFT  JOIN npart p     ON c.partener = p.codpart
              WHERE l.codcomanda1 = acodliniecomanda
              UNION ALL
              SELECT A.rootcodcomanda1, a.CODliniecomanda codcomanda1, oc.NrDoc, oc.DataDoc, oc.tipdoc, ol.CODliniecomanda
              FROM cmdlink ol
                     INNER JOIN comanda1 oc1 ON ol.codliniecomanda = oc1.codcomanda1
                     INNER JOIN comanda oc   ON oc1.codcomanda     = oc.codcomanda
                     LEFT  JOIN npart op     ON oc.partener        = op.codpart
                     INNER JOIN A            ON ol.codcomanda1     = a.CODliniecomanda
              )
              SELECT * FROM A WHERE tipdoc = 18
            ) A_PG;
    EXCEPTION WHEN others THEN
      aDoc := null;
  END;
  WME_Result :=  aDoc;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getfirstns</obj_name>
  <obj_hashval>7c239b2e7e67507ce3b93bd4d358928d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getfirstns(INOUT wme_result numeric, INOUT acodnirstoc numeric, INOUT aanluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAnLuna  numeric;
  vNextCod numeric;
  vCodOrig NUMERIC;
BEGIN
  --Florin 10.08.2023 - sinc. Oracle
  --Florin 09.06.2021 - fixat 50463
  BEGIN
      select codluna into vNextCod from tmp_nirstoc1_man where codnirstoc = aCodNirStoc;
  EXCEPTION WHEN others THEN
    vNextCod := 0;
  END;

  IF  vNextCod = 0 THEN
 begin
      select codnirstocorig into vCodOrig from nirstoc1 where codnirstoc = aCodNirStoc;
    exception when others then vNextCod := aCodNirStoc;
    end;
    if vCodOrig &gt; 0 then
      insert into tmp_nirstoc1_man(codnirstoc,
                                   codnirstocorig,
                                   an,
                                   luna,
                                   codluna)
      select ns1.codnirstoc, vNextCod, coalesce(i.an, t.an, intr.an), coalesce(i.luna, t.luna, intr.luna), min(ns1.codnirstoc)
      from nirstoc1 ns1
           inner join nirstoc ns on ns.codnirstoc = ns1.codnirstoc
           inner join nir on nir.codnir = ns.codnir
           left join iesiri i on i.codies = nir.codies
           left join transf t on t.codtransf = nir.codtransf
           left join intrari intr on intr.codintr = nir.codintr
      where ns1.codnirstocorig = vCodOrig
      group by ns1.codnirstoc, coalesce(i.an, t.an, intr.an), coalesce(i.luna, t.luna, intr.luna);
    end if;
    begin
      select codluna into vNextCod from tmp_nirstoc1_man where codnirstoc = aCodNirStoc;
    exception when others then vNextCod := aCodNirStoc;
    end;
  end if;
  wme_result := aCodNirStoc;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getganfin</obj_name>
  <obj_hashval>25921466494061f7499b5824a2e77cdf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getganfin(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.gAnFin', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getganini</obj_name>
  <obj_hashval>74f4f7efb0e3e3cf8edb2a47f5e19b8f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getganini(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.gAnIni', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getgestcom</obj_name>
  <obj_hashval>e36d3bba63cee0bb3b3c7e71cd1e8245</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getgestcom(acodliniecomanda numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  aPart varchar := '';
BEGIN
  --Adina 29 septembrie 2020 - in Oracle este Connect by prior ...
  BEGIN
    SELECT den_gest
    INTO aPart
    FROM   (WITH RECURSIVE a (rootcodcomanda1, codcomanda1, den_gest,tipdoc, CODliniecomanda) AS(
            SELECT l.codcomanda1 rootcodcomanda1, l.codcomanda1, g.den_gest,c.tipdoc, l.CODliniecomanda
            FROM  cmdlink l
                   INNER JOIN comanda1 c1 ON l.codliniecomanda = c1.codcomanda1
                   INNER JOIN comanda c   ON c1.codcomanda = c.codcomanda
                   LEFT  JOIN ngest g     ON c.codgest = g.codgest
            WHERE l.codcomanda1 = acodliniecomanda
            UNION ALL
            SELECT A.rootcodcomanda1, a.CODliniecomanda codcomanda1, og.den_gest, oc.tipdoc, ol.CODliniecomanda
            FROM cmdlink ol
                   INNER JOIN comanda1 oc1 ON ol.codliniecomanda = oc1.codcomanda1
                   INNER JOIN comanda oc   ON oc1.codcomanda = oc.codcomanda
                   LEFT  JOIN ngest og     ON oc.codgest = og.codgest
                  INNER JOIN A            ON ol.codcomanda1 = a.CODliniecomanda
            )
            SELECT * FROM A WHERE tipdoc = 43
          ) A_PG;
  EXCEPTION WHEN others THEN
    aPart := null;
  END;

  RETURN aPart;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getglunafin</obj_name>
  <obj_hashval>af85d12feb85efbc439074d2410c8379</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getglunafin(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.gLunaFin', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getglunaini</obj_name>
  <obj_hashval>35f60449d1af089881d30959c9f8ae22</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getglunaini(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.gLunaIni', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getinfositvaluta</obj_name>
  <obj_hashval>3a115ef0db76887c6c04a8c9b4096c2a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getinfositvaluta(INOUT wme_result boolean, INOUT psitvaluta numeric, INOUT pbancavaluta numeric, INOUT pmonedavaluta numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  bResult BOOLEAN := FALSE;
begin
  --Bogdan 19.08.2020
  pSitValuta    := fnc_GetValConstanta('SitValuta' , getanlucru(), getlunalucru());
  pBancaValuta  := fnc_GetValConstanta('BancaSitV' , getanlucru(), getlunalucru());
  pMonedaValuta := fnc_GetValConstanta('MonedaSitV', getanlucru(), getlunalucru());

 bResult := (   pSitValuta = 1)  AND (   Coalesce( pBancaValuta, 0) &gt; 0)  AND (   Coalesce( pMonedaValuta, 0) &gt; 0) ;

  WME_Result :=  bResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getlunadinsaptamana</obj_name>
  <obj_hashval>7390de5d6c92ddf11c492d21212e0ad8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getlunadinsaptamana(INOUT wme_result numeric, INOUT aset numeric, INOUT aan numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aAnI  numeric;
  aLuna numeric;
begin
  aAnI  := extract( month FROM (SELECT iso_week_to_date.WME_RESULT FROM iso_week_to_date(NULL, aAn, aSet)));
  aLuna := extract( month FROM (SELECT iso_week_to_date.WME_RESULT FROM iso_week_to_date(NULL, aAn, aSet)));
  IF  aLuna = 12 and  aSet = 1 THEN
    aLuna := 1;
  END IF;
  WME_Result :=  aLuna;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getobsdoc</obj_name>
  <obj_hashval>a85c881970aa45371b732713dfa1a8e4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getobsdoc(acoddoc numeric, atipdoc numeric, acoddoc1 numeric DEFAULT NULL::numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vResult varchar := '';
begin
  --BogdanL 28.07.2020
  IF  Coalesce( aCodDoc, 0) = 37 THEN  vResult := '';
  ELSIF   Coalesce( aCodDoc, 0) = 52 THEN  vResult := '';
  ELSIF Coalesce(aCodDoc,0) &lt;&gt; 0 AND Coalesce(aCodDoc1,aCodDoc,0) &lt;&gt; 0 THEN
      perform pkg_list_base_utils_setdatedoc(aCodDoc, aCodDoc1, aTipDoc);
      vResult := current_setting('PKG_LIST_BASE_UTILS.vSDD_ObsDoc', True);
  END IF;
return vResult;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getoldal_iopart1</obj_name>
  <obj_hashval>585b72c5920345c43a568714ffdd5b1d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getoldal_iopart1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.oldAL_IOPART1', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getoldcod_iopers1</obj_name>
  <obj_hashval>5c91d21c617cb292fe57360d25daef27</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getoldcod_iopers1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.oldCod_IOPERS1', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getoldcodc_iopart1</obj_name>
  <obj_hashval>fcf504aacc4c32fbcfc55651c03eeff4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getoldcodc_iopart1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.oldCodC_IOPART1', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getoldcodc_iopers1</obj_name>
  <obj_hashval>e68a5f84f1ba92fc55c8596ffc433e50</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getoldcodc_iopers1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.oldCodC_IOPERS1', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getoldcodp_iopart1</obj_name>
  <obj_hashval>9f3eab02ac34d72d546312205de7a02d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getoldcodp_iopart1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.oldCodP_IOPART1', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getoldcodp_iopers1</obj_name>
  <obj_hashval>3e436085756eebda80e62704f2655fb3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getoldcodp_iopers1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.oldCodP_IOPERS1', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getoldden_iopart1</obj_name>
  <obj_hashval>525bb7249bcb5cacc64dc3e9f3c061a8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getoldden_iopart1(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_LIST_BASE_UTILS.oldDen_IOPART1', true);
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getoldden_iopers1</obj_name>
  <obj_hashval>a0201289bd3d63c9f179826ed708be8d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getoldden_iopers1(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_LIST_BASE_UTILS.oldDen_IOPERS1', true);
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getoldidx_iopart1</obj_name>
  <obj_hashval>ed5b1c06f979263807962c16f5974699</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getoldidx_iopart1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.oldIdx_IOPART1', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getoldidx_iopers1</obj_name>
  <obj_hashval>14e8dc1ba6f4d4dd24562cfb5eecf8c5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getoldidx_iopers1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.oldIdx_IOPERS1', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getparintenivelclsa</obj_name>
  <obj_hashval>4c74fb0f156817abb380506474d02e40</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getparintenivelclsa(anivel numeric, acodclasea numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vNivel NUMERIC(20);
  vCodParinte NUMERIC(20);
  vRez varchar(100);
  vSimbol varchar(100);
BEGIN
  --Florin 20.03.2023 - sinc. Oracle ()
  --Florin 16.05.2022 - sinc. Oracle
  vrez := '';
  begin
    select codparinte, nivel, simbol into vCodParinte, vNivel, vSimbol from nclasea where codclasea = acodclasea;
  exception when others then vNivel := 0; vCodParinte := 0;
  end;
  if aNivel = vNivel then vRez := vSimbol;
  else if vCodParinte &gt; 0 then vRez := GetParinteNivelClsA(aNivel, vCodParinte); END IF;
  end if;
  return vRez;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getparintenivelclsa</obj_name>
  <obj_hashval>9fa0ce5d3dd252a5716fb6bb2d65543e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getparintenivelclsa(INOUT wme_result character varying, anivel numeric, acodclasea numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vNivel NUMERIC(20);
  vCodParinte NUMERIC(20);
  vRez varchar(100);
  vSimbol varchar(100);
BEGIN
  --Florin 20.03.2023 - sinc. Oracle ()
  --Florin 16.05.2022 - sinc. Oracle
  vrez := '';
  begin
    select codparinte, nivel, simbol into vCodParinte, vNivel, vSimbol from nclasea where codclasea = acodclasea;
  exception when others then vNivel := 0; vCodParinte := 0;
  end;
  if aNivel = vNivel then vRez := vSimbol;
  else IF vCodParinte &gt; 0 then vRez := (SELECT pkg_list_base_utils_getparintenivelclsa.WME_RESULT FROM pkg_list_base_utils_getparintenivelclsa(null,anivel, vcodparinte)); END IF;
  end if;
  wme_result := vRez;
  return;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getparintenivelclsp</obj_name>
  <obj_hashval>fa54edb67f251d0ec5cc9108d3d9a8e4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getparintenivelclsp(INOUT wme_result character varying, anivel numeric, acodclasep numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vNivel NUMERIC(20);
  vCodParinte NUMERIC(20);
  vRez varchar(100);
  vSimbol varchar(100);
BEGIN
  --Florin 20.03.2023 - sinc. Oracle (17.03.2023)
  --Florin 16.05.2022 - sinc. Oracle
  vrez := '';
  begin
    select codparinte, nivel, simbol into vCodParinte, vNivel, vSimbol from nclasep where codclasep = acodclasep;
  exception when others then vNivel := 0; vCodParinte := 0;
  end;
  if aNivel = vNivel then vRez := vSimbol;
  else IF vCodParinte &gt; 0 THEN vRez := (SELECT pkg_list_base_utils_getparintenivelclsp.WME_RESULT FROM pkg_list_base_utils_getparintenivelclsp(null,anivel, vcodparinte)); END IF;
  end if;
  wme_result := vRez;
  return;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getpartcomcli</obj_name>
  <obj_hashval>b000090857073bf7db58a042972ce255</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getpartcomcli(acodliniecomanda numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  aPart varchar;
BEGIN
  --Adina 29 septembrie 2020 - in Oracle este Connect by prior ...
  BEGIN
    SELECT den_part
    INTO aPart
    FROM   (WITH RECURSIVE a (rootcodcomanda1, codcomanda1, den_part,tipdoc, CODliniecomanda) AS(
            SELECT l.codcomanda1 rootcodcomanda1, l.codcomanda1, p.den_part,c.tipdoc, l.CODliniecomanda
            FROM  cmdlink l
                   INNER JOIN comanda1 c1 ON l.codliniecomanda = c1.codcomanda1
                   INNER JOIN comanda c   ON c1.codcomanda     = c.codcomanda
                   LEFT  JOIN npart p     ON c.partener        = p.codpart
            WHERE l.codcomanda1 = acodliniecomanda
            UNION ALL
            SELECT A.rootcodcomanda1, a.CODliniecomanda codcomanda1, op.den_part, oc.tipdoc, ol.CODliniecomanda
            FROM cmdlink ol
                   INNER JOIN comanda1 oc1 ON ol.codliniecomanda = oc1.codcomanda1
                   INNER JOIN comanda oc   ON oc1.codcomanda     = oc.codcomanda
                   LEFT  JOIN npart op     ON oc.partener        = op.codpart
                  INNER JOIN A            ON ol.codcomanda1     = a.CODliniecomanda
            )
            SELECT * FROM A WHERE tipdoc = 18
          ) A_PG;
  EXCEPTION WHEN others THEN
    aPart := null;
  END;
  RETURN aPart;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getpartcomcli</obj_name>
  <obj_hashval>62ae3c8c10edfb637bede9e68825cbf8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getpartcomcli(INOUT wme_result character varying, INOUT acodliniecomanda numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
aPart varchar;
BEGIN
  --Florin 01.02.2021 - rescris connect by prior
  BEGIN
  SELECT den_part
  INTO aPart
    FROM  (WITH RECURSIVE a (rootcodcomanda1, codcomanda1, den_part,tipdoc, CODliniecomanda) AS(
              SELECT l.codcomanda1 rootcodcomanda1, l.codcomanda1, p.den_part,c.tipdoc, l.CODliniecomanda
              FROM  cmdlink l
                     INNER JOIN comanda1 c1 ON l.codliniecomanda = c1.codcomanda1
                     INNER JOIN comanda c   ON c1.codcomanda     = c.codcomanda
                     LEFT  JOIN npart p     ON c.partener        = p.codpart
              WHERE l.codcomanda1 = acodliniecomanda
              UNION ALL
              SELECT A.rootcodcomanda1, a.CODliniecomanda codcomanda1, op.den_part, oc.tipdoc, ol.CODliniecomanda
              FROM cmdlink ol
                     INNER JOIN comanda1 oc1 ON ol.codliniecomanda = oc1.codcomanda1
                     INNER JOIN comanda oc   ON oc1.codcomanda     = oc.codcomanda
                     LEFT  JOIN npart op     ON oc.partener        = op.codpart
                    INNER JOIN A            ON ol.codcomanda1      = a.CODliniecomanda
              )
              SELECT * FROM A WHERE tipdoc = 18
            ) A_PG;
    EXCEPTION WHEN others THEN
      aPart := null;
  END;
  WME_Result :=  aPart;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getpmpobiect</obj_name>
  <obj_hashval>d8c4c2cb7da3228ccb07f79b7047d760</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getpmpobiect(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT asubunitate numeric, INOUT aan numeric, INOUT aluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  iResult       double precision;
  iValConstanta character varying;
begin
  IF  aAn = 0 THEN
    iValConstanta := fnc_GetValConstanta('TipPMP', getANLUCRU(), getLUNALUCRU());
  ELSE
    iValConstanta := fnc_GetValConstanta('TipPMP', aAn, aLuna);
  END IF;

  IF  iValConstanta::numeric = 1 THEN
    IF  aAn &lt;&gt; 0 THEN
      SELECT sum( valintr) / sum( cantIntr) INTO IResult
      FROM (SELECT CASE WHEN  p.cantintr = 0 THEN 0 ELSE p.valintr  END  VALINTR,
                   CASE WHEN  p.cantintr = 0 THEN 1 ELSE p.CantIntr END  CANTINTR
            FROM pmpluna p
            WHERE p.codobiect = aCodObiect and  p.an = aAn and  p.luna = aLuna
           ) A_PG;
    ELSE
      SELECT sum( valintr) / sum( cantIntr) INTO IResult
      FROM (SELECT CASE WHEN  p.cantintr = 0 THEN 0 ELSE p.valintr  END  VALINTR,
                   CASE WHEN  p.cantintr = 0 THEN 1 ELSE p.CantIntr END  CANTINTR
            FROM pmpluna p
            WHERE p.codobiect = aCodObiect and  p.an = TO_NUMBER(current_setting('PKG_GLOBALS.ANLUCRU', true),'999999999999999999') and  p.luna = TO_NUMBER(current_setting('PKG_GLOBALS.LUNALUCRU', true),'999999999999999999')
           ) B_PG;
    END IF;
  ELSE
    IF  aAn &lt;&gt; 0 THEN
      SELECT CASE WHEN  p.cantintr = 0 THEN 0 ELSE p.valintr / p.cantintr END INTO iResult
      FROM pmpluna p
      WHERE p.codobiect = aCodObiect and  p.an = aAn and  p.luna = aLuna and  p.codsubunit = aSubunitate;
    ELSE
      SELECT CASE WHEN  p.cantintr = 0 THEN 0 ELSE p.valintr / p.cantintr END INTO iResult
      FROM pmpluna p
      WHERE p.codobiect = aCodObiect and  p.an = TO_NUMBER(current_setting('PKG_GLOBALS.ANLUCRU', true),'999999999999999999') and  p.luna = TO_NUMBER(current_setting('PKG_GLOBALS.LUNALUCRU', true),'999999999999999999') and  p.codsubunit = aSubunitate;
    END IF;
  END IF;

  WME_Result :=  iResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getpmpobiectvaluta</obj_name>
  <obj_hashval>0cab77033118f1ea248a50e5340595c3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getpmpobiectvaluta(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT asubunitate numeric, INOUT aan numeric, INOUT aluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  iResult       double precision;
  iValConstanta character varying;
begin
  IF  aAn = 0 THEN
    iValConstanta := fnc_GetValConstantaLucru('TipPMP');
  ELSE
    iValConstanta := fnc_GetValConstanta('TipPMP', aAn, aLuna);
  END IF;

  IF  iValConstanta = 1 THEN
    IF  aAn &lt;&gt; 0 THEN
      SELECT sum( valvaluta) / sum( cantIntr) INTO IResult
      FROM (SELECT CASE WHEN  p.cantintr = 0 THEN 0 ELSE p.valValuta END  VALVALUTA,
                   CASE WHEN  p.cantintr = 0 THEN 1 ELSE p.CantIntr  END  CANTINTR
            FROM pmpluna p
            WHERE p.codobiect = aCodObiect and  p.an = aAn and  p.luna = aLuna
           ) A_PG;
    ELSE
      SELECT sum( valValuta) / sum( cantIntr) INTO IResult
      FROM (SELECT CASE WHEN  p.cantintr = 0 THEN 0 ELSE p.valValuta END  VALVALUTA,
                   CASE WHEN  p.cantintr = 0 THEN 1 ELSE p.CantIntr  END  CANTINTR
            FROM pmpluna p
            WHERE p.codobiect = aCodObiect and  p.an = TO_NUMBER(current_setting('PKG_GLOBALS.ANLUCRU', true),'999999999999999999') and  p.luna = TO_NUMBER(current_setting('PKG_GLOBALS.LUNALUCRU', true),'999999999999999999')
           ) B_PG;
    END IF;
  ELSE
    IF  aAn &lt;&gt; 0 THEN
      SELECT CASE WHEN  p.cantintr = 0 THEN 0 ELSE p.valValuta / p.cantintr END INTO iResult
      FROM pmpluna p
      WHERE p.codobiect = aCodObiect and  p.an = aAn and  p.luna = aLuna and  p.codsubunit = aSubunitate;
    ELSE
      SELECT CASE WHEN  p.cantintr = 0 THEN 0 ELSE p.valValuta / p.cantintr END INTO iResult
      FROM pmpluna p
      WHERE p.codobiect = aCodObiect and  p.an = TO_NUMBER(current_setting('PKG_GLOBALS.ANLUCRU', true),'999999999999999999') and  p.luna = TO_NUMBER(current_setting('PKG_GLOBALS.LUNALUCRU', true),'999999999999999999') and  p.codsubunit = aSubunitate;
    END IF;
  END IF;

  WME_Result :=  iResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getpretmaxachiz</obj_name>
  <obj_hashval>37636e30889ff359a3a3cec1038f8a6d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getpretmaxachiz(INOUT wme_result numeric, INOUT vcodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  vVal     numeric;
  vIdx     numeric;
  vNrIntr numeric;
BEGIN
  vIdx := 1;
  vVal := 0.0;

  vNrIntr := fnc_GetValConstanta('NrPretIntrMed', getANLUCRU(), getLUNALUCRU());

  IF  vNrIntr = 0 THEN
    WME_Result :=  0.0;
    RETURN;
  END IF;

  FOR v_rec IN
  (
    SELECT COALESCE(NS.PRET, 0) - COALESCE(NS.ADAOS, 0) PRET, ns.cantnir
    FROM NIR N, NIRSTOC NS, NGEST G
    WHERE NS.CODOBIECT = vCODOBIECT AND  NS.CODNIR = N.CODNIR AND
          TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 15) AND
          OPERAT = 1 AND  ANULAT = 0 AND  G.CODGEST = N.GEST AND
          COALESCE(G.CODSUBUNIT, 1) = CASE WHEN  getSUBUNITATE()=1 THEN COALESCE(G.CODSUBUNIT, 1) ELSE  getSUBUNITATE() END
    ORDER BY N.DATANIR desc
  )
  LOOP
    IF  vIdx &gt; vNrIntr THEN
      EXIT ;
    END IF;

    IF  v_rec.pret &gt; vVal THEN
      vVal := v_rec.pret;
    END IF;

    vIdx := vIdx + 1;
  END LOOP;

  WME_Result :=  vVal;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getpretmedachiz</obj_name>
  <obj_hashval>e71b1d5e5f83609462bc0ed8e7281b2b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getpretmedachiz(INOUT wme_result numeric, INOUT vcodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  vCant   numeric;
  vVal     numeric;
  vIdx     numeric;
  vNrIntr numeric;
BEGIN
  vIdx    := 1;
  vCant   := 0.0;
  vVal    := 0.0;
  vNrIntr := fnc_GetValConstanta('NrPretIntrMed', getANLUCRU(), getLUNALUCRU());

  IF  vNrIntr = 0 THEN
    WME_Result :=  0.0;
    RETURN;
  END IF;

  FOR v_rec IN
  (
    SELECT COALESCE(NS.PRET, 0) - COALESCE(NS.ADAOS, 0) PRET, ns.cantnir
    FROM NIR N, NIRSTOC NS, NGEST G
    WHERE NS.CODOBIECT = vCODOBIECT AND  NS.CODNIR = N.CODNIR AND
          TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 15) AND  OPERAT = 1 AND
          ANULAT = 0 AND  G.CODGEST = N.GEST AND
          COALESCE(G.CODSUBUNIT, 1) = CASE WHEN  getSUBUNITATE()=1 THEN COALESCE(G.CODSUBUNIT, 1) ELSE getSUBUNITATE() END
    ORDER BY N.DATANIR desc
  )
  LOOP
    IF  vIdx &gt; vNrIntr THEN
      EXIT ;
    END IF;

    vCant := vCant + v_rec.cantnir;
    vVal := vVal + v_rec.cantnir * v_rec.pret;
    vIdx := vIdx + 1;
  END LOOP;

  IF  vCant &lt;&gt; 0 THEN
    WME_Result :=  vVal / vCant;
    RETURN;
  ELSE
    WME_Result :=  0;
    RETURN;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getpretmediu</obj_name>
  <obj_hashval>39ca67783903f0d1c3295b1c48dabd5d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getpretmediu(INOUT wme_result numeric, INOUT acodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  PMed double precision;
begin
  BEGIN
    SELECT sum( cant * pret) / sum( cant) INTO PMed
    FROM (SELECT ns.cantnir CANT, ns.pret
          FROM nirstoc ns
            INNER JOIN intrari1 ii1 ON  ii1.codintr1 = ns.codintr1
            INNER JOIN intrari  ii  ON  ii.codintr   = ii1.codintr
            INNER JOIN nir          ON  ns.codnir    = nir.codnir and  ii.codintr = nir.codintr and  nir.TIPNIR = ii.tipdoc
          WHERE ii.tipdoc IN (1, 2, 3, 4, 7) and  ns.codobiect = acodobiect and  ns.rest &gt; 0
          union ALL
          SELECT ns.cantnir CANT, ns.pret
          FROM nirstoc ns
            INNER JOIN dvi1     dvi1 ON  dvi1.coddvi1  = ns.coddvi1
            INNER JOIN dvi           ON  dvi.coddvi    = dvi1.coddvi
            INNER JOIN intrari1 ii1  ON  dvi1.codintr1 = ii1.codintr1
            INNER JOIN intrari  ii   ON  ii1.codintr   = ii.codintr and  dvi.codintr = ii.codintr
            INNER JOIN nir           ON  ns.codnir     = nir.codnir and  ii.codintr  = nir.codintr and  nir.TIPNIR = ii.tipdoc
          WHERE ii.tipdoc = 5 and  ns.codobiect = acodobiect and  ns.rest &gt; 0
         ) A_PG;
  EXCEPTION WHEN others THEN
    PMed := 0;
  END;

  WME_Result :=  PMed;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getpretminachiz</obj_name>
  <obj_hashval>a8fcf17c3fe3e76db169c2bb5da6567e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getpretminachiz(INOUT wme_result numeric, INOUT vcodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  vVal     numeric;
  vIdx     numeric;
  vNrIntr numeric;
BEGIN
  vIdx    := 1;
  vVal    := -1;
  vNrIntr := fnc_GetValConstanta('NrPretIntrMed', getANLUCRU(), getLUNALUCRU());

  IF  vNrIntr = 0 THEN
    WME_Result :=  0.0;
    RETURN;
  END IF;

  FOR v_rec IN
  (
    SELECT COALESCE(NS.PRET, 0) - COALESCE(NS.ADAOS, 0) PRET, ns.cantnir
    FROM NIR N, NIRSTOC NS, NGEST G
    WHERE NS.CODOBIECT = vCODOBIECT AND  NS.CODNIR = N.CODNIR AND
          TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 15) AND  OPERAT = 1 AND
          ANULAT = 0 AND  G.CODGEST = N.GEST AND  COALESCE(G.CODSUBUNIT, 1) = CASE
     WHEN  current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric=1 THEN COALESCE(G.CODSUBUNIT, 1) ELSE  current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric END
    ORDER BY N.DATANIR desc
  )
  LOOP
    IF  vIdx &gt; vNrIntr THEN
      EXIT ;
    END IF;

    IF  vVal = -1 THEN
      vVal := v_rec.pret;
    ELSE
      IF  v_rec.pret &lt; vVal THEN
        vVal := v_rec.pret;
      END IF;
    END IF;

    vIdx := vIdx + 1;
  END LOOP;

  WME_Result :=  vVal;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getsecventa</obj_name>
  <obj_hashval>84666d9d9602d2aa6b3a703ecb9cb2c1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getsecventa(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NextV numeric;
begin
  SELECT NEXTVAL('SEQ_LIST_COUNTER') INTO nextv;
  WME_Result :=  nextv;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getseriiintrare</obj_name>
  <obj_hashval>17c9b610ab987793b9b8a313019380db</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getseriiintrare()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  NrSeriiRand numeric;
  idx1         numeric;
  idx2         numeric;
  cnt         numeric;
  aCodNirStoc numeric := 0;
  s           varchar := ' ';
BEGIN
  --Adina 19.10.2020 (??)
  DELETE FROM tmp_manevra_serii;

  NrSeriiRand := 10;

  PERFORM PKG_GLOBALS_SetSeparator(';');

  idx1 := 0;
  idx2 := NrSeriiRand;

  FOR V_REC IN
  (
    SELECT  DISTINCT NS.CODNIRSTOC
    FROM   nirstoc ns
          INNER JOIN nirser nser ON  nser.codnirstoc = ns.codnirstoc
          INNER JOIN nserii n    ON  n.codserie      = nser.codserie
    WHERE ns.codnir IN (SELECT valoare FROM tmp_manevra_liste WHERE filtru = 'CODNIR')
  )
  LOOP
    SELECT COUNT(*)
    INTO cnt
    FROM   nirstoc ns
          INNER JOIN nirser nser ON  nser.codnirstoc = ns.codnirstoc
          INNER JOIN nserii n    ON  n.codserie      = nser.codserie
    WHERE ns.codnirstoc = v_rec.codnirstoc;

    IF  cnt &gt; 10 THEN
      cnt := 10;
      s := '...';
    ELSE
      s := '';
    END IF;

    IF  aCodNirstoc &lt;&gt; v_rec.codnirstoc THEN
      idx1 := 0;
      idx2 := NrSeriiRand;
    END IF;

    BEGIN
    INSERT INTO tmp_manevra_serii(codnirstoc, serii, FLAG)
    SELECT CODnirstoc, coalesce(SERIE,'') || coalesce(s,''), idx1
    FROM (SELECT codnirstoc, string_agg(serie,',') SERIE
          FROM (SELECT t1.*, row_number() over() RN
                FROM (SELECT ns.codnirstoc, n.serie SERIE
                      FROM   nirstoc ns
                            INNER JOIN nirser nser ON  nser.codnirstoc = ns.codnirstoc
                            INNER JOIN nserii n    ON  n.codserie      = nser.codserie
                      WHERE ns.codnir::varchar IN (SELECT valoare FROM tmp_manevra_liste WHERE filtru = 'CODNIR') AND  ns.codnirstoc = v_rec.codnirstoc
                      ORDER BY codnirstoc , n.serie
                     ) t1
               ) A_PG
          WHERE rn BETWEEN idx1 AND idx2
          GROUP BY codnirstoc
         ) B_PG;
    EXCEPTION
      WHEN data_exception THEN
        --PERFORM Raise_Application_Error(-20001, ' Prea multe serii pe rand !  Modificati constanta ' || coalesce(chr(13),'') || ' Listare numar de serii pe un rand ' || coalesce(chr(13),''));
        RAISE;
      WHEN OTHERS THEN NULL;
    END;

    aCodnirStoc := v_rec.codnirstoc;
  END LOOP;

  PERFORM PKG_GLOBALS_SetSeparator(',');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getsoldclient</obj_name>
  <obj_hashval>983fc855764ef0a9f3806587d5ce1fbb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getsoldclient(INOUT wme_result numeric, INOUT pcodpart numeric, INOUT pcodlocatie numeric DEFAULT 0)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vSql  varchar;
  vSold numeric;
BEGIN
  PERFORM PKG_NOMPART_SET_PART_CURENT(pCodPart);
  PERFORM PKG_MONEDE_SET_MONEDA_CURENTA(-1);

  vSql := '
  WITH OBLIG AS (
    SELECT
      V.CodLocatie, V.Subunitatea,
      V.REST * DECODE(V.CURS,NULL,1,0,1,V.CURS)  RESTREAL, V.VALOARE * Coalesce(NULLIF(coalesce(V.CURS,0),0),1)  VALREAL
    FROM ( ' || V_INTRARI_ROSU_FURN() || ' ) V
    UNION ALL
    SELECT
      V.CodLocatie, V.Subunitatea,
      V.REST * DECODE(V.CURS,NULL,1,0,1,V.CURS)  RESTREAL, V.VALOARE * Coalesce(NULLIF(coalesce(V.CURS,0),0),1)  VALREAL
      FROM ( ' || V_AVANS_FURN_TREZOR() || ' ) V
    UNION ALL
    SELECT
      V.CodLocatie, V.Subunitatea,
      V.REST * DECODE(V.CURS,NULL,1,0,1,V.CURS)  RESTREAL, V.VALOARE * Coalesce(NULLIF(coalesce(V.CURS,0),0),1)  VALREAL
    FROM ( ' || V_AVANS_FURN_FACTURABILE() || ' ) V
    UNION ALL
    SELECT
      V.CodLocatie, V.Subunitatea,
      V.REST * DECODE(V.CURS,NULL,1,0,1,V.CURS)  RESTREAL, V.VALOARE * Coalesce(NULLIF(coalesce(V.CURS,0),0),1)  VALREAL
    FROM ( ' || V_OBLIG_CLIENT() || ' ) V
  )
  SELECT Sum (RESTREAL)
  FROM OBLIG
  WHERE 1 = 1 ' || coalesce(CASE WHEN  Coalesce(pCodLocatie, 0) &lt;&gt; 0 THEN ' AND CodLocatie = ' || coalesce(pCodLocatie::varchar ,'') END ::varchar ,'');

  EXECUTE vSql INTO vSold;
  vSold := Coalesce(vSold, 0);

  WME_Result :=  vSold;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getsoldfurnizor</obj_name>
  <obj_hashval>f380b80359abed2f0c831bc950698ad6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getsoldfurnizor(INOUT wme_result numeric, INOUT pcodpart numeric, INOUT pcodlocatie numeric DEFAULT 0)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vSql  varchar;
  vSold numeric;
BEGIN
  PERFORM PKG_NOMPART_SET_PART_CURENT(pCodPart);
  PERFORM PKG_MONEDE_SET_MONEDA_CURENTA(-1);

  vSql := '
  WITH OBLIG AS (
    SELECT
      V.CodLocatie, V.Subunitatea,
      V.REST * DECODE(V.CURS,NULL,1,0,1,V.CURS) RESTREAL, -V.VALOARE * Coalesce(NULLIF(coalesce(V.CURS,0),0),1) VALREAL
    FROM ( ' || V_OBLIG_FURN() || ' ) V
    UNION ALL
    SELECT
      V.CodLocatie, V.Subunitatea,
      V.REST * DECODE(V.CURS,NULL,1,0,1,V.CURS) RESTREAL, -V.VALOARE * Coalesce(NULLIF(coalesce(V.CURS,0),0),1) VALREAL
    FROM ( ' || V_IESIRI_ROSU_CLIENT() || ' ) V
    UNION ALL
    SELECT
      V.CodLocatie, V.Subunitatea,
      V.REST * DECODE(V.CURS,NULL,1,0,1,V.CURS) RESTREAL, -V.VALOARE * Coalesce(NULLIF(coalesce(V.CURS,0),0),1) VALREAL
    FROM ( ' || V_AVANS_CLIENT_TREZOR() || ' ) V
    UNION ALL
    SELECT
      V.CodLocatie, V.Subunitatea,
      V.REST * DECODE(V.CURS,NULL,1,0,1,V.CURS) RESTREAL, -V.VALOARE * Coalesce(NULLIF(coalesce(V.CURS,0),0),1) VALREAL
    FROM ( ' || V_AVANS_CLIENT_FACTURABILE() || ' ) V
  )
  SELECT Sum (RESTREAL)
  FROM OBLIG
  WHERE 1 = 1 ' || coalesce(CASE WHEN  Coalesce(pCodLocatie, 0) &lt;&gt; 0 THEN ' AND CodLocatie = ' || coalesce(pCodLocatie::varchar ,'') END ::varchar ,'');

  EXECUTE vSql INTO vSold;
  vSold := Coalesce(vSold, 0);

  WME_Result :=  vSold;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getstinsies</obj_name>
  <obj_hashval>354fa7d58b4af9939d65306e4a562c0c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getstinsies(INOUT wme_result numeric, INOUT pcodies numeric, INOUT pcodcomanda numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  CREC   RECORD;
  vStins numeric;
BEGIN
  --Florin 08.02.2023 - RAC
  vStins := 0;
  FOR cREC IN
  (
    SELECT Coalesce( I.TipFactura, 0) TIPFACTURA, Coalesce( I.ValDoc, 0) VALDOC, O.CodObligPif, I.TipDoc
    FROM IESIRI I
      INNER JOIN GENERAL  G ON  G.CODDOC     = I.CODIES AND  G.TIPDOC = I.TIPDOC
      INNER JOIN OBLIGPIF O ON  O.CODGENERAL = G.CODGENERAL
    WHERE I.CODIES = pCodIes
  )
  LOOP
    IF  cRec.TipFactura = 7 THEN
      vStins := cRec.ValDoc;
    ELSE
      vStins := vStins + PKG_LIST_BASE_UTILS_getStinsObligMoneda( cREC.CodObligPif);
    END IF;
  END LOOP;

  IF  Coalesce( pCodComanda, 0) &gt; 0 AND  vStins &lt;&gt; 0 THEN
    vStins := vStins * (SELECT PKG_LIST_BASE_UTILS_PondereComanda.WME_RESULT FROM PKG_LIST_BASE_UTILS_PondereComanda(NULL, pCodIes, pCodComanda));
  END IF;

  FOR cREC IN
  (
    SELECT C1.CodComanda, Sum( I1.Cant * I1.PU) VALDOC
    FROM IESIRI1 I1
      INNER JOIN IESLINK  L  ON  L.CODIES1      = I1.CODIES1
      INNER JOIN IESIRI   I  ON  I.CODIES       = I1.CODIES
      INNER JOIN COMANDA1 C1 ON  C1.CODCOMANDA1 = L.CODLINIECOMANDA
    WHERE I.TIPDOC = 16 and  I1.CODIES = pCodIes AND  C1.CodComanda = pCodComanda
    GROUP BY C1.CodComanda
  )
  LOOP
    vStins := cRec.ValDoc;
  END LOOP;

  WME_Result :=  vStins;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getstinsies</obj_name>
  <obj_hashval>a778c50f217c7c6c8bf4ca1e6952ff47</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getstinsies(pcodies numeric, pcodcomanda numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  CREC   RECORD;
  vStins numeric;
BEGIN
  --Adina 28 septembrie 2020
  vStins := 0;
  FOR cREC IN (  SELECT Coalesce( I.TipFactura, 0) TIPFACTURA, Coalesce( I.ValDoc, 0) VALDOC, O.CodObligPif, I.TipDoc
                FROM   IESIRI I
                      INNER JOIN GENERAL G  ON  G.CODDOC     = I.CODIES AND  G.TIPDOC = I.TIPDOC
                      INNER JOIN OBLIGPIF O ON  O.CODGENERAL = G.CODGENERAL
                WHERE I.CODIES = pCodIes
              )
  LOOP
    IF  cRec.TipFactura = 7 THEN
      vStins := cRec.ValDoc;
    ELSE
      vStins := vStins + PKG_LIST_BASE_UTILS_getStinsObligMoneda( cREC.CodObligPif);
    END IF;
  END LOOP;

  IF  Coalesce( pCodComanda, 0) &gt; 0 AND  vStins &lt;&gt; 0 THEN
    vStins := vStins * PKG_LIST_BASE_UTILS_PondereComanda(pCodIes, pCodComanda);
  END IF;

  FOR cREC IN (  SELECT C1.CodComanda, Sum( I1.Cant * I1.PU) VALDOC
                FROM   IESIRI1 I1
                      INNER JOIN IESLINK L   ON  L.CODIES1 = I1.CODIES1
                      INNER JOIN IESIRI I    ON  I.CODIES  = I1.CODIES
                      INNER JOIN COMANDA1 C1 ON  C1.CODCOMANDA1 = L.CODLINIECOMANDA
                WHERE I.TIPDOC = 16 and  I1.CODIES = pCodIes AND  C1.CodComanda = pCodComanda
                GROUP BY C1.CodComanda
              )
  LOOP
    vStins := cRec.ValDoc;
  END LOOP;

  RETURN vStins;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getstinsoblig</obj_name>
  <obj_hashval>815da7e0360f72961f0c5bd0de9afe7a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getstinsoblig(INOUT wme_result numeric, INOUT pcodobligpif numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  LREC     RECORD;
  vTrezor  numeric;
  vCEC     numeric;
  vCompens numeric;
  vLitig   numeric;
begin
  SELECT Coalesce( SUM( O_STINGATOR.VALOARE * CASE
                                                WHEN G_STINGATOR.CURS IS NULL  THEN 1
                                                WHEN G_STINGATOR.CURS = 0      THEN 1
                                                ELSE G_STINGATOR.CURS
                                              END ), 0)
  INTO vTrezor
  FROM STINGERE S
    INNER JOIN OBLIGPIF O_STINGATOR ON  O_STINGATOR.CODOBLIGPIF = S.CODSTINGATORPIF
    INNER JOIN GENERAL  G_STINGATOR ON  G_STINGATOR.CODGENERAL  = O_STINGATOR.CODGENERAL AND G_STINGATOR.TIPDOC IN (29, 30, 33)
    INNER JOIN TREZOR1  T1          ON  T1.CODTREZOR1           = G_STINGATOR.CODDOC
  WHERE
     S.CODSTINSPIF = pCodObligPif AND  Coalesce( T1.ANULAT, 0) = 0;

  SELECT Coalesce( SUM( O_STINGATOR.VALOARE * CASE
                                                WHEN G_STINGATOR.CURS IS NULL  THEN 1
                                                WHEN G_STINGATOR.CURS = 0      THEN 1
                                                ELSE G_STINGATOR.CURS
                                              END ), 0)
  INTO vCEC
  FROM STINGERE S
    INNER JOIN OBLIGPIF O_STINGATOR ON  O_STINGATOR.CODOBLIGPIF = S.CODSTINGATORPIF
    INNER JOIN GENERAL  G_STINGATOR ON  G_STINGATOR.CODGENERAL  = O_STINGATOR.CODGENERAL AND  G_STINGATOR.TIPDOC = 31
    INNER JOIN TREZOR1  T1          ON  T1.CODTREZOR1           = G_STINGATOR.CODDOC
    INNER JOIN GENERAL  G_CEC       ON  G_CEC.TIPDOC            = 31 AND  G_CEC.CODDOC = G_STINGATOR.CODDOC AND G_CEC.SEMNIFICATIE IN (500, 600)
    INNER JOIN OBLIGPIF O_CEC       ON  O_CEC.CODGENERAL        = G_CEC.CODGENERAL
    INNER JOIN STINGERE S_CEC       ON  S_CEC.CODSTINSPIF       = O_CEC.CODOBLIGPIF
    INNER JOIN OBLIGPIF O_CURENT    ON  O_CURENT.CODOBLIGPIF    = S_CEC.CODSTINGATORPIF
    INNER JOIN GENERAL  G_CURENT    ON  G_CURENT.CODGENERAL     = O_CURENT.CODGENERAL AND  G_CURENT.TIPDOC = 30
    INNER JOIN TREZOR1  T1_CURENT   ON  T1_CURENT.CODTREZOR1    = G_CURENT.CODDOC
  WHERE
     S.CODSTINSPIF = pCodObligPif AND  Coalesce( T1.ANULAT, 0) = 0;

  SELECT Coalesce( SUM( O_STINGATOR.VALOARE * CASE
                                                WHEN G_STINGATOR.CURS IS NULL  THEN 1
                                                WHEN G_STINGATOR.CURS = 0      THEN 1
                                                ELSE G_STINGATOR.CURS
                                              END ), 0)
  INTO vCompens
  FROM STINGERE S
    INNER JOIN OBLIGPIF O_STINGATOR ON  O_STINGATOR.CODOBLIGPIF = S.CODSTINGATORPIF
    INNER JOIN GENERAL  G_STINGATOR ON  G_STINGATOR.CODGENERAL  = O_STINGATOR.CODGENERAL AND  G_STINGATOR.TIPDOC = 28
    INNER JOIN COMPENS  C           ON  C.CODCOMPENS            = G_STINGATOR.CODDOC
  WHERE
     S.CODSTINSPIF = pCodObligPif;

  vLitig := 0;
  FOR lREC IN
  (
    SELECT OL.CodObligPif, OL.VALOARE
    FROM OBLIGPIF OL
      INNER JOIN GENERAL GL ON  GL.CODGENERAL = OL.CODGENERAL
      INNER JOIN COMPENS CL ON  CL.CODCOMPENS = GL.CODDOC
    WHERE
       OL.CODOBLIGASOCIAT = pCodObligPif AND  OL.SEMNIFICATIE = 1303
  )
  LOOP
    vLitig := vLitig + lREC.VALOARE;
    vLitig := vLitig - (SELECT PKG_LIST_BASE_UTILS_getStinsOblig.WME_RESULT FROM PKG_LIST_BASE_UTILS_getStinsOblig(NULL, lREC.CodObligPif));
  END LOOP;

  WME_Result :=  vTrezor + vCEC + vCompens - vLitig;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getstinsobligmoneda</obj_name>
  <obj_hashval>5ad42fa0a61cee77619dac8acce2845a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getstinsobligmoneda(INOUT wme_result numeric, INOUT pcodobligpif numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vTrezor  numeric;
  vCEC     numeric;
  vCompens numeric;
  vLitig   numeric;
BEGIN
  --Florin 28.03.2023 - sinc. Oracle
  SELECT Coalesce(SUM(case when O_STINGATOR.semnificatie in (320,420) then -1 else 1 end * O_STINGATOR.VALOARE),0)
  INTO vTrezor
  FROM STINGERE S
    INNER JOIN OBLIGPIF O_STINGATOR ON  O_STINGATOR.CODOBLIGPIF = S.CODSTINGATORPIF
    INNER JOIN GENERAL  G_STINGATOR ON  G_STINGATOR.CODGENERAL  = O_STINGATOR.CODGENERAL AND G_STINGATOR.TIPDOC IN (29, 30, 33)
    INNER JOIN TREZOR1  T1          ON  T1.CODTREZOR1           = G_STINGATOR.CODDOC
  WHERE
     S.CODSTINSPIF = pCodObligPif AND  Coalesce( T1.ANULAT, 0) = 0;

  SELECT Coalesce( SUM( O_STINGATOR.VALOARE), 0)
  INTO vCEC
  FROM STINGERE S
    INNER JOIN OBLIGPIF O_STINGATOR ON  O_STINGATOR.CODOBLIGPIF = S.CODSTINGATORPIF
    INNER JOIN GENERAL  G_STINGATOR ON  G_STINGATOR.CODGENERAL  = O_STINGATOR.CODGENERAL AND  G_STINGATOR.TIPDOC = 31
    INNER JOIN TREZOR1  T1          ON  T1.CODTREZOR1           = G_STINGATOR.CODDOC
    INNER JOIN GENERAL  G_CEC       ON  G_CEC.TIPDOC            = 31 AND  G_CEC.CODDOC = G_STINGATOR.CODDOC AND G_CEC.SEMNIFICATIE IN (500, 600)
    INNER JOIN OBLIGPIF O_CEC       ON  O_CEC.CODGENERAL        = G_CEC.CODGENERAL
    INNER JOIN STINGERE S_CEC       ON  S_CEC.CODSTINSPIF       = O_CEC.CODOBLIGPIF
    INNER JOIN OBLIGPIF O_CURENT    ON  O_CURENT.CODOBLIGPIF    = S_CEC.CODSTINGATORPIF
    INNER JOIN GENERAL  G_CURENT    ON  G_CURENT.CODGENERAL     = O_CURENT.CODGENERAL AND  G_CURENT.TIPDOC = 30
    INNER JOIN TREZOR1  T1_CURENT   ON  T1_CURENT.CODTREZOR1    = G_CURENT.CODDOC
  WHERE
     S.CODSTINSPIF = pCodObligPif AND  Coalesce( T1.ANULAT, 0) = 0;

  SELECT Coalesce( SUM( O_STINGATOR.VALOARE), 0)
  INTO vCompens
  FROM STINGERE S
    INNER JOIN OBLIGPIF O_STINGATOR ON  O_STINGATOR.CODOBLIGPIF = S.CODSTINGATORPIF
    INNER JOIN GENERAL  G_STINGATOR ON  G_STINGATOR.CODGENERAL  = O_STINGATOR.CODGENERAL AND  G_STINGATOR.TIPDOC = 28
    INNER JOIN COMPENS  C           ON  C.CODCOMPENS            = G_STINGATOR.CODDOC
  WHERE
     S.CODSTINSPIF = pCodObligPif;

  WME_Result :=  vTrezor + vCEC + vCompens;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getstinsobligmoneda</obj_name>
  <obj_hashval>19a31c6e9b6ed05cb49ccebb99744008</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getstinsobligmoneda(pcodobligpif numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vTrezor   numeric;
  vCEC       numeric;
  vCompens   numeric;
  vLitig     numeric;
BEGIN
  --Florin 28.03.2023 - sinc. Oracle
  --Adina 28 septembrie 2020
    SELECT Coalesce(SUM(case when O_STINGATOR.semnificatie in (320,420) then -1 else 1 end * O_STINGATOR.VALOARE),0)
  INTO vTrezor
  FROM   STINGERE S
        INNER JOIN OBLIGPIF O_STINGATOR ON  O_STINGATOR.CODOBLIGPIF = S.CODSTINGATORPIF
        INNER JOIN GENERAL G_STINGATOR   ON  G_STINGATOR.CODGENERAL  = O_STINGATOR.CODGENERAL AND G_STINGATOR.TIPDOC IN (29, 30, 33)
        INNER JOIN TREZOR1 T1           ON  T1.CODTREZOR1           = G_STINGATOR.CODDOC
  WHERE S.CODSTINSPIF = pCodObligPif AND  Coalesce( T1.ANULAT, 0) = 0;

  SELECT Coalesce( SUM( O_STINGATOR.VALOARE), 0)
  INTO vCEC
  FROM   STINGERE S
        INNER JOIN OBLIGPIF O_STINGATOR ON  O_STINGATOR.CODOBLIGPIF = S.CODSTINGATORPIF
        INNER JOIN GENERAL G_STINGATOR   ON  G_STINGATOR.CODGENERAL  = O_STINGATOR.CODGENERAL AND  G_STINGATOR.TIPDOC = 31
        INNER JOIN TREZOR1 T1           ON  T1.CODTREZOR1           = G_STINGATOR.CODDOC
        INNER JOIN GENERAL G_CEC         ON  G_CEC.TIPDOC            = 31 AND  G_CEC.CODDOC = G_STINGATOR.CODDOC AND G_CEC.SEMNIFICATIE IN (500, 600)
        INNER JOIN OBLIGPIF O_CEC       ON  O_CEC.CODGENERAL        = G_CEC.CODGENERAL
        INNER JOIN STINGERE S_CEC       ON  S_CEC.CODSTINSPIF       = O_CEC.CODOBLIGPIF
        INNER JOIN OBLIGPIF O_CURENT     ON  O_CURENT.CODOBLIGPIF    = S_CEC.CODSTINGATORPIF
        INNER JOIN GENERAL G_CURENT     ON  G_CURENT.CODGENERAL     = O_CURENT.CODGENERAL AND  G_CURENT.TIPDOC = 30
        INNER JOIN TREZOR1 T1_CURENT     ON  T1_CURENT.CODTREZOR1    = G_CURENT.CODDOC
  WHERE S.CODSTINSPIF = pCodObligPif AND  Coalesce( T1.ANULAT, 0) = 0;

  SELECT Coalesce( SUM( O_STINGATOR.VALOARE), 0)
  INTO vCompens
  FROM   STINGERE S
        INNER JOIN OBLIGPIF O_STINGATOR ON  O_STINGATOR.CODOBLIGPIF = S.CODSTINGATORPIF
        INNER JOIN GENERAL  G_STINGATOR ON  G_STINGATOR.CODGENERAL  = O_STINGATOR.CODGENERAL AND  G_STINGATOR.TIPDOC = 28
        INNER JOIN COMPENS  C           ON  C.CODCOMPENS            = G_STINGATOR.CODDOC
  WHERE S.CODSTINSPIF = pCodObligPif;

  RETURN (vTrezor + vCEC + vCompens);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_gettabladoc</obj_name>
  <obj_hashval>fc6e911349e012d4008c58b1860493f4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_gettabladoc(INOUT wme_result character varying, INOUT atipdoc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vSDD_TablaDoc varchar := '';
BEGIN
  --Florin --Florin 02.10.2020
  IF Coalesce(aTipDoc,0) &lt;&gt; 0 THEN
    CASE
      WHEN aTipDoc IN (1,2,3,4,5,6,7,9)               THEN vSDD_TablaDoc := 'INTRARI';
      WHEN aTipDoc IN (8,18,43,44,53,60,65,66,92,94)  THEN vSDD_TablaDoc := 'COMANDA';
      WHEN aTipDoc IN (14,15,16,19,20,21,22,23,24,26) THEN vSDD_TablaDoc := 'IESIRI';
      WHEN aTipDoc = 28                               THEN vSDD_TablaDoc := 'COMPENS';
      WHEN aTipDoc = 35                               THEN vSDD_TablaDoc := 'NC';
      WHEN aTipDoc IN (10,25,27,34,58,59)             THEN vSDD_TablaDoc := 'NOTECREDIT';
      WHEN aTipDoc IN (12, 13)                        THEN vSDD_TablaDoc := 'TRANSF';
      WHEN aTipDoc IN (29,30,31,33)                   THEN vSDD_TablaDoc := 'TREZOR';
      WHEN aTipDoc IN (45,46,47)                      THEN vSDD_TablaDoc := 'REG';
      WHEN aTipDoc = 71                               THEN vSDD_TablaDoc := 'PRODNET';
      WHEN aTipDoc = 63                               THEN vSDD_TablaDoc := 'RAPORTP';
      WHEN aTipDoc = 64                               THEN vSDD_TablaDoc := 'EMULARE';
      WHEN aTipDoc = 36                               THEN vSDD_TablaDoc := 'MIFIX';
      WHEN aTipDoc = 97                               THEN vSDD_TablaDoc := 'RECLAMATII';
    END CASE;
  END IF;
  PERFORM set_config('PKG_LIST_BASE_UTILS.vSDD_TablaDoc', vSDD_TablaDoc, FALSE);
  WME_Result := vSDD_TablaDoc;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_gettiptva0</obj_name>
  <obj_hashval>782461c6f337f446f780444489640b66</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_gettiptva0(INOUT wme_result numeric, INOUT pcodobiect numeric, INOUT pan numeric, INOUT pluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  wme_result := pkg_list_base_utils_gettiptva0 (pcodobiect ,  pan ,  pluna );
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_gettiptva0</obj_name>
  <obj_hashval>9ca4c3855140ddc2fd39944c2895e038</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_gettiptva0(pcodobiect numeric, pan numeric, pluna numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  iResult    numeric := 0;
  aTvaObj    numeric;
  sCodObiect varchar;
  vArtNeimp  numeric;
  --0 = cu deducere ; 1 = fara deducere ; 2 = neimpozabil
  vTT0_CodObiect     NUMERIC := Coalesce(fnc_current_setting_numeric('PKG_LIST_BASE_UTILS.vTT0_CodObiect'), 0);
  vTT0_AL            NUMERIC := Coalesce(fnc_current_setting_numeric('PKG_LIST_BASE_UTILS.vTT0_AL'), 0);
  vTT0_Res           NUMERIC := Coalesce(fnc_current_setting_numeric('PKG_LIST_BASE_UTILS.vTT0_Res'), 0);
  vTT0_TVA0FaraDed   NUMERIC := Coalesce(fnc_current_setting_numeric('PKG_LIST_BASE_UTILS.vTT0_TVA0FaraDed'), 0);
  vTT0_CntJVARTNEIMP NUMERIC := Coalesce(fnc_current_setting_numeric('PKG_LIST_BASE_UTILS.vTT0_CntJVARTNEIMP'), 0);
BEGIN
  IF vTT0_CodObiect = pCodObiect AND vTT0_AL = pAn*12+pLuna THEN
    iResult := vTT0_Res;
  ELSE
    iResult := 0;
    sCodObiect := pCodObiect;

    IF vTT0_AL &lt;&gt; pAn*12+pLuna THEN
      SELECT Count(1)
      INTO   vTT0_CntJVARTNEIMP
      FROM CONST1 C1
        INNER JOIN CONSTLUNA CL ON CL.codconst1 = C1.codConst1
        INNER JOIN CONSTVAL CV ON cv.codconstluna = cl.codconstluna
      WHERE UPPER(C1.simbol) = 'JVARTNEIMP' AND pAn*12+pLuna BETWEEN CL.ALSTART AND CL.ALSTOP;

      vTT0_TVA0FaraDed := fnc_getvalconstanta('TVA0FaraDed',pAn,pLuna)::numeric;
    END IF;

    IF vTT0_CntJVARTNEIMP &gt; 0 THEN
      SELECT Count(1)
      INTO   vArtNeimp
      FROM CONST1 C1
        INNER JOIN CONSTLUNA CL ON CL.codconst1 = C1.codConst1
        INNER JOIN CONSTVAL CV ON cv.codconstluna = cl.codconstluna
      WHERE UPPER(C1.simbol) = 'JVARTNEIMP' AND pAn*12+pLuna BETWEEN CL.ALSTART AND CL.ALSTOP
        AND CV.VALOARE = sCodObiect;

      IF vArtNeimp &gt; 0 THEN
        iResult := 2;
      END IF;
    END IF;

    IF iResult = 0 THEN
      BEGIN
        SELECT t.codtva INTO aTVAObj
        FROM (
          SELECT codarticol
          FROM nartobj nobj
          WHERE nobj.codobiect = pCodObiect  LIMIT 1
        ) obj
          INNER JOIN nart1 n1 ON n1.codarticol = obj.codarticol AND pAn*12+pLuna BETWEEN n1.ALSTART AND n1.ALSTOP
          INNER JOIN ntva t ON t.codtva = n1.codtva;

        IF aTvaObj = vTT0_TVA0FaraDed
        THEN iResult := 1;
        END IF;
      EXCEPTION
        WHEN OTHERS THEN NULL;
      END;

    END IF;
  END IF;
  vTT0_Res       := iResult;
  vTT0_CodObiect := pCodObiect;
  vTT0_AL        := pAn*12+pLuna;

  RETURN iResult;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getuserdoc</obj_name>
  <obj_hashval>83fbc93b55d7843b867c8f322342d0c7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getuserdoc(INOUT wme_result numeric, INOUT acoddoc numeric, INOUT atipdoc numeric, INOUT acoddoc1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vResult varchar := null;

begin
    --BogdanL 27.07.2020
    IF  Coalesce( aCodDoc, 0) = 37 THEN
      vResult := null;
    elsif Coalesce( aCodDoc, 0) = 52 THEN
      vResult := null;
    ELSIF Coalesce(aCodDoc,0) &lt;&gt; 0 AND Coalesce(aCodDoc1,aCodDoc,0) &lt;&gt; 0 THEN
        perform pkg_list_base_utils_setdatedoc(aCodDoc, aCodDoc1, aTipDoc);
        vResult := pkg_list_base_utils_getvsdd_userdoc();
    END IF;
  WME_Result :=  vResult;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvaldoc</obj_name>
  <obj_hashval>9817c0ca308db3568b115348d1fd124a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvaldoc(acoddoc numeric, atipdoc numeric, acoddoc1 numeric DEFAULT NULL::numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
declare
  vResult numeric;
BEGIN
  PERFORM pkg_list_base_utils_SetDateDoc(aCodDoc, aCodDoc1, aTipDoc);
  vResult := current_setting('PKG_LIST_BASE_UTILS.vSDD_ValDoc', true)::numeric;
  RETURN vResult;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvalfractie</obj_name>
  <obj_hashval>de4003c154dcbf1ccc4dbb41c6642618</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvalfractie(INOUT wme_result numeric, INOUT afractie character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aSQL    varchar;
  aDouble numeric;
begin
  aSQL := 'SELECT ' || afractie;
  BEGIN
    EXECUTE aSQL INTO aDouble;
  EXCEPTION WHEN OTHERS THEN
    aDouble := 1;
  END;
  WME_Result :=  round( (aDouble)::numeric, 7);
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvanlunabcpuv</obj_name>
  <obj_hashval>31d77b5fff5008e890a6598cf1cda67a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvanlunabcpuv(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vAnLunaBCPUV', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvanlunamfiv</obj_name>
  <obj_hashval>875e7d776f0896d0075597edde6f3b8b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvanlunamfiv(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vAnLunaMFIV', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvanlunamin</obj_name>
  <obj_hashval>99889aae9951c42b439aeed3671d02eb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvanlunamin(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vAnLunaMin', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvanlunatva</obj_name>
  <obj_hashval>e855fd690be058a1845bf097dc98120f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvanlunatva(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vAnLunaTVA', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvcdman</obj_name>
  <obj_hashval>a90c70d9b5affff66ecb82c65b81fd3e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvcdman(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vCDMAn', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvcdmcintermedcm</obj_name>
  <obj_hashval>91f355ee03df56a176308b108fcf6b1a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvcdmcintermedcm(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vCDMCIntermedCM', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvcdmcodies</obj_name>
  <obj_hashval>30ccbaaa8550840cac2fba0c157d2292</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvcdmcodies(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vCDMCodIes', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvcdmconincfact</obj_name>
  <obj_hashval>44a75e33df5f0ecd65c17394fb0c170b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvcdmconincfact(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vCDMConIncFact', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvcdmluna</obj_name>
  <obj_hashval>4bc4a6223172ea95bdd313870fee7b3a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvcdmluna(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vCDMLuna', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvcdmtvadisc</obj_name>
  <obj_hashval>c3abd0284327f7c92aa3ca88078456c6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvcdmtvadisc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vCDMTvaDisc', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvcdmtvadoc</obj_name>
  <obj_hashval>faa7f98aa3db9c948d3ce6df3d911c31</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvcdmtvadoc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vCDMTvaDoc', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvcdmtvalin</obj_name>
  <obj_hashval>1ecafd103d62056f901b59779ee2389d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvcdmtvalin(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vCDMTvaLin', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvcdmvaldisc</obj_name>
  <obj_hashval>5f83478e78abf91edb044081c6f7a814</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvcdmvaldisc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vCDMValDisc', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvcdmvaldoc</obj_name>
  <obj_hashval>378522eb8b64e8b7b57ea58a5d4bc665</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvcdmvaldoc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vCDMValDoc', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvcdmvallin</obj_name>
  <obj_hashval>b0e642de39ff4e2ac751c2b1bf63eafa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvcdmvallin(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vCDMValLin', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvcodmfiv</obj_name>
  <obj_hashval>0c48510992870c5af59b3adb63047f51</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvcodmfiv(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_LIST_BASE_UTILS.vCodMFIV', true);
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvcodobjuma</obj_name>
  <obj_hashval>a7bfb7d5d1510b43209298e64388f23c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvcodobjuma(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vCodObjUMA', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvdenbcpuv</obj_name>
  <obj_hashval>f9080995cd1f342cb018361f156b9211</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvdenbcpuv(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_LIST_BASE_UTILS.vDenBCPUV', true);
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvduma1</obj_name>
  <obj_hashval>9de8392c3741b643bd5232487d067782</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvduma1(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_LIST_BASE_UTILS.vDUMA1', true);
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvduma2</obj_name>
  <obj_hashval>76c85314615f2537d159bca8ea0055c4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvduma2(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_LIST_BASE_UTILS.vDUMA2', true);
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvduma3</obj_name>
  <obj_hashval>8e3c7ba3ab2ead6ad579f57b9c8ec40e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvduma3(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_LIST_BASE_UTILS.vDUMA3', true);
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvlistsimblipsa</obj_name>
  <obj_hashval>a0fa8b7a11aa52399f2ae8a49d286e44</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvlistsimblipsa(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_LIST_BASE_UTILS.vListSimbLipsa', true);
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvpj1tip</obj_name>
  <obj_hashval>2ab0a163cba4f8bdcf662c16bb6e7ebe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvpj1tip(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPj1TIP', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvpj1tva</obj_name>
  <obj_hashval>6c588a251de4f41cfeaf066e50240e89</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvpj1tva(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPj1TVA', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvpj2tip</obj_name>
  <obj_hashval>7979c3f320b042d7521c2b6e86ce83fa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvpj2tip(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPj2TIP', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvpj2tva</obj_name>
  <obj_hashval>a7b7a4e271031dfa768cdca8d2cf7e31</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvpj2tva(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPj2TVA', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvpj3tip</obj_name>
  <obj_hashval>c8e1b0dd755cd333c5c35fd211376155</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvpj3tip(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPj3TIP', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvpj3tva</obj_name>
  <obj_hashval>211e71ca7bf6a87ebbf03f2767955e44</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvpj3tva(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPj3TVA', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvpj4tip</obj_name>
  <obj_hashval>bdf47a85924a1a148076ca82dea88c35</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvpj4tip(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPj4TIP', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvpj4tva</obj_name>
  <obj_hashval>1ee1567c1c10b148890891e151a62eea</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvpj4tva(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPj4TVA', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvpj5tip</obj_name>
  <obj_hashval>878fe3d1bfa2ef580ae17b45a594f905</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvpj5tip(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPj5TIP', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvpj5tva</obj_name>
  <obj_hashval>ceab38e3038f67eaa3070277208ff4a6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvpj5tva(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPj5TVA', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvpuma1</obj_name>
  <obj_hashval>e3f5e9322e1fbf33b7f0d9146a712659</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvpuma1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPUMA1', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvpuma2</obj_name>
  <obj_hashval>37814e1b6c02520ae4490ada3a0efd9a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvpuma2(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPUMA2', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvpuma3</obj_name>
  <obj_hashval>0c753bded4e271e1b9ec370a636ee734</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvpuma3(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPUMA3', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvpumac</obj_name>
  <obj_hashval>6a0f71a21a014e833fc7529e1a459557</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvpumac(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPUMAC', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvpumap</obj_name>
  <obj_hashval>c5e5a8f36e6d664db8480250367ba34f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvpumap(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPUMAP', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvsdd_coddoc</obj_name>
  <obj_hashval>7f4839c0784001c8f6374595cd8c3b32</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvsdd_coddoc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vSDD_CodDoc', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvsdd_dendoc</obj_name>
  <obj_hashval>0e27162c8147c7c80f4e28152a044128</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvsdd_dendoc(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_LIST_BASE_UTILS.vSDD_DenDoc', true);
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvsdd_obsdoc</obj_name>
  <obj_hashval>3b1570fdfc0fa8aae6582d76c418ebd1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvsdd_obsdoc(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_LIST_BASE_UTILS.vSDD_ObsDoc', true);
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvsdd_partdoc</obj_name>
  <obj_hashval>04f49998795b93fb1d418e6d3599bda1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvsdd_partdoc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vSDD_PartDoc', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvsdd_tabladoc</obj_name>
  <obj_hashval>c8e17d2ff1cc6257704f8e23c02b5c36</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvsdd_tabladoc(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_LIST_BASE_UTILS.vSDD_TablaDoc', true);
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvsdd_tipdoc</obj_name>
  <obj_hashval>dd1bbf2ecc45b29cbfa716f973b347f0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvsdd_tipdoc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vSDD_TipDoc', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvsdd_userdoc</obj_name>
  <obj_hashval>87d774042f044d86a480e1152899adb1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvsdd_userdoc()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
declare
  vRet numeric;
begin
  --BogdanL 27.07.2020
  BEGIN
    vRet := case when current_setting('PKG_LIST_BASE_UTILS.vSDD_UserDoc', true) = '' then null
           else current_setting('PKG_LIST_BASE_UTILS.vSDD_UserDoc', true)::numeric end;
    RETURN vRet;
  EXCEPTION WHEN undefined_object THEN
    vRet := NULL;
    return vRet ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvsimbmfiv</obj_name>
  <obj_hashval>b82b1bcf0719dc6268c020acb810f2f0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvsimbmfiv(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_LIST_BASE_UTILS.vSimbMFIV', true);
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvtt0_codobiect</obj_name>
  <obj_hashval>747a32b3be352b64e999b6be48684642</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvtt0_codobiect(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vTT0_CodObiect', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvtt0_res</obj_name>
  <obj_hashval>e8077781b8a1d64605bf9c87e6ed9dcb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvtt0_res(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vTT0_Res', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvtt0_tva0faraded</obj_name>
  <obj_hashval>990d8ce7c97fb2222ba6e0fe600e9215</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvtt0_tva0faraded(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_LIST_BASE_UTILS.vTT0_TVA0FaraDed', true);
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_glunafin</obj_name>
  <obj_hashval>00d6c043883d1ac77b803e8b8fdfbf00</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_glunafin(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.gLunaFin', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_glunaini</obj_name>
  <obj_hashval>5357d22d843d0ffe8080deae0e6dbbef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_glunaini(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.gLunaIni', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_isgreentax</obj_name>
  <obj_hashval>9c0d43fe1d9fef39420e37532d0f5e1b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_isgreentax(INOUT wme_result numeric, INOUT pcodobiect numeric, INOUT ptiplinie character varying, INOUT pan numeric, INOUT pluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  iResult numeric := 0;
  vCount  numeric := 0;
  vAL     numeric := pAn * 12 + pLuna;
begin
  --Florin 14.01.2022 - sinc. Oracle (29.12.2021)
  iResult := 0;
  IF  pTipLinie = 'S' THEN
    SELECT count( 1) INTO vCount FROM ntaxe1 t1
        WHERE t1.codservfact = pCodObiect AND vAL BETWEEN t1.ALSTART AND t1.ALSTOP;
    iResult := CASE vCount  WHEN 0 THEN 0 ELSE 1 END ;
  END IF;
  WME_Result :=  iResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_list_simbol_lipsa</obj_name>
  <obj_hashval>be08fb08aa9e0411eff90993b6fdbbb1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_list_simbol_lipsa(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vListSimbLipsa VARCHAR := current_setting('PKG_LIST_BASE_UTILS.vListSimbLipsa',true);
  vCount         NUMERIC;
BEGIN
  IF vListSimbLipsa IS NULL THEN
    SELECT Count(1) INTO vCount FROM TMP_LIPSA_CORESP_PLANP;

    IF    vCount =  0
    THEN vListSimbLipsa := '';
    ELSE
      SELECT fnc_array_to_vc3200(array_agg(DISTINCT simbol)) INTO vListSimbLipsa
      FROM (
        SELECT simbol, Row_Number() OVER (ORDER BY simbol) idx
        FROM TMP_LIPSA_CORESP_PLANP
      ) subs
      WHERE idx &lt;= 5;
      IF vCount &gt; 5 THEN
        vListSimbLipsa := vListSimbLipsa||'...';
      END IF;
    END IF;
  END IF;
  perform set_config('PKG_LIST_BASE_UTILS.vListSimbLipsa',vListSimbLipsa,false);
  WME_Result := vListSimbLipsa;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_make_config_luna_ioart</obj_name>
  <obj_hashval>e24f4ccc36a8a14a0f84558afaa8f09b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_make_config_luna_ioart()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aUSER_ID    numeric := -1;
  aIOART_FLG  numeric := 0;
  AnLunaLucru numeric;
BEGIN
  --Adina 28 iulie 2020 - aranjat si modificat
  BEGIN
    SELECT Coalesce( USERID, -1), Coalesce( IOART_FLG, 0) INTO aUSER_ID, aIOART_FLG
    FROM LUNA_RECORDS_FLAGS
    WHERE
      USERID = current_setting('PKG_GLOBALS.USERID', true)::numeric;
  EXCEPTION WHEN OTHERS THEN
    BEGIN
      aUSER_ID   := -1;
      aIOART_FLG := 0;
    END;
  END;

  IF  aUSER_ID = -1 THEN
    INSERT INTO LUNA_RECORDS_FLAGS(USERID, NART_FLG, NARTOBJ_FLG, IOART_FLG, NTVA_FLG, NTAXE_FLG)
    VALUES(current_setting('PKG_GLOBALS.USERID', true)::numeric, 0, 0, 0, 0, 0);
  END IF;

  SELECT (GETANLUCRU() * 12 + GETLUNALUCRU())   INTO AnLunaLucru;

  IF  aIOART_FLG = 0 THEN
    DELETE FROM tmp_ioart_luna;

    INSERT INTO tmp_ioart_luna(codioart1, codioart, cont, diferente, cheltuieli, venituri, plusinventar, minusinventar, chelttvacolectat, PROVIZION, CHELTPROVIZION, controtunjiri, diverse, accizelatransfer, descarcareg, contabgest, baza, difpret, aretvaneex, tvaneex, mg, anstart, lunastart, den_ioart)
      SELECT codioart1, io.codioart, cont, diferente, cheltuieli, venituri, plusinventar, minusinventar, chelttvacolectat, PROVIZION, CHELTPROVIZION, controtunjiri, diverse, accizelatransfer, descarcareg, contabgest, baza, difpret, aretvaneex, tvaneex, mg, anstart, lunastart, den_ioart
      FROM ioart io
      INNER JOIN ioart1 io1 ON  io.codioart = io1.codioart
      WHERE
        IO1.ANSTART * 12 + IO1.LUNASTART =
        (
       SELECT MAX( IO2.ANSTART * 12 + IO2.LUNASTART)
       FROM IOART1 IO2
       WHERE
         IO2.CODIOART = IO1.CODIOART AND  IO2.ANSTART * 12 + IO2.LUNASTART &lt;= AnLunaLucru
      );

    UPDATE LUNA_RECORDS_FLAGS
    SET
      IOART_FLG = 1
    WHERE
      USERID = TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999');
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_make_config_luna_iopart</obj_name>
  <obj_hashval>f8a67c91d112e931a5f026943ea9d921</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_make_config_luna_iopart()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  AnLunaLucru numeric;
  aIOPART_FLG numeric := 0;
  aUSER_ID    numeric := -1;
begin
  --Florin 14.01.2022 - sinc. Oracle (29.12.2021)
  BEGIN
    SELECT Coalesce( USERID, -1), Coalesce( aIOPART_FLG, 0)
    INTO aUSER_ID, aIOPART_FLG
    FROM LUNA_RECORDS_FLAGS
    WHERE
       USERID = TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999');
  EXCEPTION WHEN OTHERS THEN
    BEGIN
      aUSER_ID := -1;
      aIOPART_FLG := 0;
    END;
  END;

  IF  aUSER_ID = -1 THEN
    INSERT INTO LUNA_RECORDS_FLAGS(USERID, NTVA_FLG, IOPART_FLG, IOPers_FLG)
    VALUES(TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999'), 0, 0, 0);
  END IF;

  SELECT GETANLUCRU() * 12 + GETLUNALUCRU() INTO AnLunaLucru;

  IF  aIOPART_FLG = 0 THEN
    DELETE FROM tmp_iopart_luna;

    INSERT INTO tmp_iopart_luna(CODPART, CODPART1, DEN_PART, CODIOPART, CREDITCLIENT, VOLUMTRANZC, CREDITFURN, VOLUMTRANZF, CODIOPART1, DEN_IOPART, CONTFURNIZOR, CONTCLIENT, CONTFURNAVANS, CONTCLIENTAVANS, CONTFURNAVIZ, CONTCLIENTAVIZ, CONTFURNMF, CONTCREDITD, CONTDEBITD, CONTLITIGII, CONTFURNAVS, CONTFURNAVIC, CONTFURNAVIN, CONTTERTI, TVANEEXF, TVANEEXC, TVANEEXP, TVANEEXI, TIP)
    SELECT n.codpart, n1.codpart1, n.den_part, Coalesce( n1.codiopart, 0) CODIOPART, n1.creditclient, n1.volumtranzc, n1.creditfurn, n1.volumtranzf, io1.codiopart1, io.den_iopart, io1.contfurnizor, io1.contclient, io1.contfurnavans, io1.contclientavans, io1.contfurnaviz, io1.contclientaviz, io1.contfurnmf, io1.contcreditd, io1.contdebitd, io1.contlitigii, io1.contfurnavs, io1.contfurnavic, io1.contfurnavin, io1.contterti, io1.tvaneexf, io1.tvaneexc, io1.TVANEEXP, io1.TVANEEXI, io1.tip
    FROM npart n
      LEFT JOIN npart1 n1 ON n.codpart = n1.codpart AND GetANLUNALUCRU() BETWEEN n1.ALStart AND n1.ALStop
      LEFT JOIN iopart io ON Coalesce(n1.codiopart,0) = Coalesce(io.codiopart,0)
      LEFT JOIN iopart1 io1 ON io.codiopart = io1.codiopart AND GetANLUNALUCRU() BETWEEN io1.ALStart AND io1.ALStop;

    UPDATE LUNA_RECORDS_FLAGS
    SET
    IOPART_FLG = 1
    WHERE
     USERID = TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999');
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_make_pmp_luna_liste</obj_name>
  <obj_hashval>b9fb698affb706db53ea36446d4b06b0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_make_pmp_luna_liste()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC         RECORD;
  aCANTINTR     double precision;
  aCANT         double precision;
  aVALINTR      double precision;
  aValValuta    double precision;
  CANTINTRPREC  double precision := 0;
  VALINTRPREC   double precision := 0;
  NR            numeric := 0;
  VALVALUTAPREC double precision := 0;
  anPrecTemp    numeric;
  lunaPrecTemp  numeric;
begin
  --Adina iulie 2020
  DELETE FROM PMPLUNA
  WHERE AN   = current_setting('PKG_GLOBALS.ANTEMP'  , true)::numeric AND
        LUNA = current_setting('PKG_GLOBALS.LUNATEMP', true)::numeric AND
        (SELECT PKG_LIST_BASE_UTILS_EsteObiectValid.WME_RESULT FROM PKG_LIST_BASE_UTILS_EsteObiectValid(NULL, codobiect)) = 1;

  INSERT INTO PMPLUNA(CODPMPLUNA, CODOBIECT, CODSUBUNIT, CANTINTR, VALINTR, REST, AN, LUNA, VALVALUTA)
  SELECT NEXTVAL('SEQ_PMPLUNA_CODPMPLUNA'), CODOBIECT, CODSUBUNIT, CANTINTR, VALINTR, REST, current_setting('PKG_GLOBALS.ANTEMP', true)::numeric, current_setting('PKG_GLOBALS.LUNATEMP', true)::numeric, VALVALUTA
  FROM PMPLUNA p
  WHERE
     ( AN * 12 + Luna)  = (current_setting('PKG_GLOBALS.ANTEMP', true)::numeric * 12 + current_setting('PKG_GLOBALS.LUNATEMP', true)::numeric)  - 1 AND
     ( NOT  EXISTS (SELECT codobiect FROM v_list_pmp_luna v WHERE p.codobiect = v.CODOBIECT)
       or
       NOT  EXISTS (SELECT codsubunit FROM v_list_pmp_luna v WHERE p.codsubunit = v.CODSUBUNIT)
     )  AND
     (SELECT PKG_LIST_BASE_UTILS_EsteObiectValid.WME_RESULT FROM PKG_LIST_BASE_UTILS_EsteObiectValid(NULL, codobiect)) = 1;

  FOR V_REC IN (SELECT * FROM V_LIST_PMP_LUNA) LOOP
    BEGIN
      SELECT Coalesce( CANTINTR, 0), Coalesce( VALINTR, 0), Coalesce( VALVALUTA, 0)
        INTO CANTINTRPREC, VALINTRPREC, VALVALUTAPREC
      FROM PMPLUNA
      WHERE
           AN * 12 + LUNA = (  current_setting('PKG_GLOBALS.ANTEMP', true)::numeric * 12 + current_setting('PKG_GLOBALS.LUNATEMP', true)::numeric)  - 1 AND
           CODOBIECT = V_REC.CODOBIECT AND  CODSUBUNIT = V_REC.CODSUBUNIT;
    EXCEPTION WHEN OTHERS THEN
      CANTINTRPREC  := 0;
      VALINTRPREC   := 0;
      VALVALUTAPREC := 0;
    END;

    aCANT     := V_REC.CANTINTR + CANTINTRPREC;
    aCANTINTR := V_REC.RESTLUNA + CANTINTRPREC;

    IF  aCANT &lt;&gt; 0 THEN
      aVALINTR   := (  (  V_REC.VALINTR + VALINTRPREC)  / aCANT)  * aCantIntr;
      aVALValuta := (  (  V_REC.VALVALUTA + VALVALUTAPREC)  / aCANT)  * aCantIntr;
    ELSE
      aVALINTR   := 0;
      aValValuta := 0;
    END IF;

    INSERT INTO PMPLUNA(CODPMPLUNA, CODOBIECT, CODSUBUNIT, CANTINTR, VALINTR, REST, AN, LUNA, VALVALUTA)
    VALUES(NEXTVAL('SEQ_PMPLUNA_CODPMPLUNA'), V_REC.CODOBIECT, V_REC.CODSUBUNIT, aCANTINTR, aVALINTR, V_REC.RESTLUNA, current_setting('PKG_GLOBALS.ANTEMP', true)::numeric, current_setting('PKG_GLOBALS.LUNATEMP', true)::numeric, aValValuta);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_match_tva_combi</obj_name>
  <obj_hashval>c0eb558fdc6bfdf5beb1ec9e4b47bd9d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_match_tva_combi(INOUT p_pjtva numeric, INOUT p_anluna numeric, INOUT out_caztva numeric, INOUT out_proctva numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vRec       RECORD;
  NR         NUMERIC;
  x_AnLuna   NUMERIC;
  x_PJTVA    NUMERIC := Abs(p_PJTVA);

  vAnLunaTVA NUMERIC := Coalesce(fnc_current_setting_numeric('PKG_LIST_BASE_UTILS.vAnLunaTVA'), 0);
  vAnLunaMin NUMERIC := Coalesce(fnc_current_setting_numeric('PKG_LIST_BASE_UTILS.vAnLunaMin'), 0);

  vPj1TVA    NUMERIC := Coalesce(fnc_current_setting_numeric('PKG_LIST_BASE_UTILS.vPj1TVA'), 0);
  vPj2TVA    NUMERIC := Coalesce(fnc_current_setting_numeric('PKG_LIST_BASE_UTILS.vPj2TVA'), 0);
  vPj3TVA    NUMERIC := Coalesce(fnc_current_setting_numeric('PKG_LIST_BASE_UTILS.vPj3TVA'), 0);
  vPj4TVA    NUMERIC := Coalesce(fnc_current_setting_numeric('PKG_LIST_BASE_UTILS.vPj4TVA'), 0);
  vPj5TVA    NUMERIC := Coalesce(fnc_current_setting_numeric('PKG_LIST_BASE_UTILS.vPj5TVA'), 0);
  vPj6TVA    NUMERIC := Coalesce(fnc_current_setting_numeric('PKG_LIST_BASE_UTILS.vPj6TVA'), 0);
  vPj7TVA    NUMERIC := Coalesce(fnc_current_setting_numeric('PKG_LIST_BASE_UTILS.vPj7TVA'), 0);
  vPj8TVA    NUMERIC := Coalesce(fnc_current_setting_numeric('PKG_LIST_BASE_UTILS.vPj8TVA'), 0);

  vPj1TIP    NUMERIC := Coalesce(fnc_current_setting_numeric('PKG_LIST_BASE_UTILS.vPj1TIP'), 0);
  vPj2TIP    NUMERIC := Coalesce(fnc_current_setting_numeric('PKG_LIST_BASE_UTILS.vPj2TIP'), 0);
  vPj3TIP    NUMERIC := Coalesce(fnc_current_setting_numeric('PKG_LIST_BASE_UTILS.vPj3TIP'), 0);
  vPj4TIP    NUMERIC := Coalesce(fnc_current_setting_numeric('PKG_LIST_BASE_UTILS.vPj4TIP'), 0);
  vPj5TIP    NUMERIC := Coalesce(fnc_current_setting_numeric('PKG_LIST_BASE_UTILS.vPj5TIP'), 0);
  vPj6TIP    NUMERIC := Coalesce(fnc_current_setting_numeric('PKG_LIST_BASE_UTILS.vPj6TIP'), 0);
  vPj7TIP    NUMERIC := Coalesce(fnc_current_setting_numeric('PKG_LIST_BASE_UTILS.vPj7TIP'), 0);
  vPj8TIP    NUMERIC := Coalesce(fnc_current_setting_numeric('PKG_LIST_BASE_UTILS.vPj8TIP'), 0);
BEGIN
  --Stef   22.08.2025 - sinc. Oracle
  IF vAnLunaMin = 0 THEN
    SELECT AnInitial*12+LunaInitiala INTO vAnLunaMin FROM FirmaLuni;
    PERFORM set_config('PKG_LIST_BASE_UTILS.vAnLunaMin', vAnLunaMin::varchar, false);
  END IF;
  x_AnLuna := Greatest(p_AnLuna, vAnLunaMin);

  IF x_AnLuna &lt;&gt; Coalesce(vAnLunaTVA,0) THEN
    vAnLunaTVA := x_AnLuna;
    NR         := 0;
    vPj1TVA    := 0;
    vPj2TVA    := 0;
    vPj3TVA    := 0;
    vPj4TVA    := 0;
    vPj5TVA    := 0;
    vPj6TVA    := 0;
    vPj7TVA    := 0;
    vPj8TVA    := 0;
    vPj1TIP    := 0;
    vPj2TIP    := 0;
    vPj3TIP    := 0;
    vPj4TIP    := 0;
    vPj5TIP    := 0;
    vPj6TIP    := 0;
    vPj7TIP    := 0;
    vPj8TIP    := 0;

    FOR vRec IN (
      SELECT PJ, TIP
      FROM (
        SELECT
          COALESCE(NULLIF(VALOARE, ''), '0')::numeric PJ,
          CASE Upper(c1.SIMBOL)
            WHEN 'PROCTVAMED'    THEN 1
            WHEN 'PROCTVAMIN'    THEN 2
            WHEN 'PROCTVAMAX'    THEN 3
            WHEN 'PROCTVAREG'    THEN 4
            WHEN 'PROCTVAREG2'   THEN 5
            WHEN 'PROCTVAREG3'   THEN 6
            WHEN 'PROCTVAREG4'   THEN 7
            WHEN 'PROCTVAREG5'   THEN 8
            ELSE 0
          END Tip
        FROM const1 c1
          INNER JOIN constluna cl ON cl.codconst1 = c1.codconst1
          INNER JOIN constval cv ON cv.codconstluna = cl.codconstluna
        WHERE UPPER(c1.SIMBOL) IN ('PROCTVAMIN','PROCTVAMED','PROCTVAMAX','PROCTVAREG','PROCTVAREG2','PROCTVAREG3','PROCTVAREG4','PROCTVAREG5')
          AND vAnLunaTVA BETWEEN CL.ALSTART AND CL.ALSTOP
          AND NOT (vAnLunaTVA &lt; 2025*12+8 AND UPPER(c1.SIMBOL) IN ('PROCTVAREG3','PROCTVAREG4','PROCTVAREG5')   )
      ) sPG
      ORDER BY PJ DESC
    )
    LOOP
      NR := NR + 1;
      CASE
        WHEN NR = 1 THEN vPj1TVA := vRec.Pj; vPj1TIP := vRec.Tip;
        WHEN NR = 2 THEN vPj2TVA := vRec.Pj; vPj2TIP := vRec.Tip;
        WHEN NR = 3 THEN vPj3TVA := vRec.Pj; vPj3TIP := vRec.Tip;
        WHEN NR = 4 THEN vPj4TVA := vRec.Pj; vPj4TIP := vRec.Tip;
        WHEN NR = 5 THEN vPj5TVA := vRec.Pj; vPj5TIP := vRec.Tip;
        WHEN NR = 6 THEN vPj6TVA := vRec.Pj; vPj6TIP := vRec.Tip;
        WHEN NR = 7 THEN vPj7TVA := vRec.Pj; vPj7TIP := vRec.Tip;
        WHEN NR = 8 THEN vPj8TVA := vRec.Pj; vPj8TIP := vRec.Tip;
      END CASE;
    END LOOP;

    PERFORM set_config('PKG_LIST_BASE_UTILS.vAnLunaTVA', vAnLunaTVA::varchar, FALSE);
    PERFORM set_config('PKG_LIST_BASE_UTILS.vPj1TVA',    vPj1TVA::varchar, FALSE);
    PERFORM set_config('PKG_LIST_BASE_UTILS.vPj1TIP',    vPj1TIP::varchar, FALSE);
    PERFORM set_config('PKG_LIST_BASE_UTILS.vPj2TVA',    vPj2TVA::varchar, FALSE);
    PERFORM set_config('PKG_LIST_BASE_UTILS.vPj2TIP',    vPj2TIP::varchar, FALSE);
    PERFORM set_config('PKG_LIST_BASE_UTILS.vPj3TVA',    vPj3TVA::varchar, FALSE);
    PERFORM set_config('PKG_LIST_BASE_UTILS.vPj3TIP',    vPj3TIP::varchar, FALSE);
    PERFORM set_config('PKG_LIST_BASE_UTILS.vPj4TVA',    vPj4TVA::varchar, FALSE);
    PERFORM set_config('PKG_LIST_BASE_UTILS.vPj4TIP',    vPj4TIP::varchar, FALSE);
    PERFORM set_config('PKG_LIST_BASE_UTILS.vPj5TVA',    vPj5TVA::varchar, FALSE);
    PERFORM set_config('PKG_LIST_BASE_UTILS.vPj5TIP',    vPj5TIP::varchar, FALSE);
    PERFORM set_config('PKG_LIST_BASE_UTILS.vPj6TVA',    vPj6TVA::varchar, FALSE);
    PERFORM set_config('PKG_LIST_BASE_UTILS.vPj6TIP',    vPj6TIP::varchar, FALSE);
    PERFORM set_config('PKG_LIST_BASE_UTILS.vPj7TVA',    vPj7TVA::varchar, FALSE);
    PERFORM set_config('PKG_LIST_BASE_UTILS.vPj7TIP',    vPj7TIP::varchar, FALSE);
    PERFORM set_config('PKG_LIST_BASE_UTILS.vPj8TVA',    vPj8TVA::varchar, FALSE);
    PERFORM set_config('PKG_LIST_BASE_UTILS.vPj8TIP',    vPj8TIP::varchar, FALSE);
  END IF;

  IF    Coalesce(x_PJTVA,0) = 0       THEN out_CAZTVA := 0;       out_PROCTVA := 0;
  ELSIF x_PJTVA &lt; vPj8TVA             THEN out_CAZTVA := vPj8TIP; out_PROCTVA := vPj8TVA;
  ELSIF x_PJTVA &lt; (vPj8TVA+vPj7TVA)/2 THEN out_CAZTVA := vPj8TIP; out_PROCTVA := vPj8TVA;
  ELSIF x_PJTVA &lt; (vPj7TVA+vPj6TVA)/2 THEN out_CAZTVA := vPj7TIP; out_PROCTVA := vPj7TVA;
  ELSIF x_PJTVA &lt; (vPj6TVA+vPj5TVA)/2 THEN out_CAZTVA := vPj6TIP; out_PROCTVA := vPj6TVA;
  ELSIF x_PJTVA &lt; (vPj5TVA+vPj4TVA)/2 THEN out_CAZTVA := vPj5TIP; out_PROCTVA := vPj5TVA;
  ELSIF x_PJTVA &lt; (vPj4TVA+vPj3TVA)/2 THEN out_CAZTVA := vPj4TIP; out_PROCTVA := vPj4TVA;
  ELSIF x_PJTVA &lt; (vPj3TVA+vPj2TVA)/2 THEN out_CAZTVA := vPj3TIP; out_PROCTVA := vPj3TVA;
  ELSIF x_PJTVA &lt; (vPj2TVA+vPj1TVA)/2 THEN out_CAZTVA := vPj2TIP; out_PROCTVA := vPj2TVA;
  ELSE                                     out_CAZTVA := vPj1TIP; out_PROCTVA := vPj1TVA;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_match_tva_proc</obj_name>
  <obj_hashval>8b45130ea48fe73f6d51f6304ba6a356</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_match_tva_proc(INOUT wme_result numeric, INOUT p_pjtva numeric, INOUT p_anluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  --Bogdan 23.12.2020
  WME_Result :=  pkg_list_base_utils_match_tva_proc(p_pjtva, p_anluna)
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_nivele_analiza</obj_name>
  <obj_hashval>b94b16396f7101328c844770213bdf15</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_nivele_analiza(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vMaxCL NUMERIC;
BEGIN
  --Florin 09.11.2023 - fixat 59989
  --Florin 07.11.2023 - sinc. Oracle
  --Florin 06.12.2022 - sinc. Oracle
  --BogdanL 27.07.2020
  DELETE FROM TMP_TREE_ANALIZANOD;

  INSERT INTO TMP_TREE_ANALIZANOD(CODANALIZANOD, NIVEL, DEN_DESCRIPTOR, SIMBOL, VALOARE, TIP, CODASOCIAT, POZITIE)
  SELECT x.cod, Row_Number() OVER (PARTITION BY x.COD ORDER BY x.ord) nivel, d.den_descriptor, d.simbol, d1.valoare, D.TIP, D1.CODASOCIAT, A.POZITIE
  FROM (
        with recursive recANALIZANOD as
          ( select codanalizanod, codanalizanod  as cod, nodparinte,  1 as level
            from ANALIZANOD
            where Coalesce(nodparinte,0) &lt;&gt; 0
              and pozitie &lt;&gt; 0
            union all
              select  a.codanalizanod, r.cod,  a.nodparinte, r.level+1
                 from ANALIZANOD a
                  join  recANALIZANOD r on r.nodparinte = a.codanalizanod
                 where
                   a.pozitie &lt;&gt; 0
          )
          SELECT  cod, codanalizanod, -level as ord
              FROM recANALIZANOD
      ) x
  INNER JOIN ANALIZANOD   a  ON  a.codanalizanod   = x.codanalizanod
  INNER JOIN ANALIZA1     a1 ON  a1.codanaliza1    = a.codanaliza1
  INNER JOIN DESCRIPTORI1 D1 ON  d1.coddescriptor1 = a.coddescriptor1
  INNER JOIN DESCRIPTORI  D  ON  d.coddescriptor   = d1.coddescriptor;

  UPDATE TMP_TREE_ANALIZANOD TMP
  SET
    IDX = (SELECT fnc_array_to_vc3200(array_agg(TO_CHAR(POZITIE) ORDER BY NIVEL)) FROM TMP_TREE_ANALIZANOD T WHERE T.CODANALIZANOD = TMP.CODANALIZANOD);

  BEGIN
    SELECT Coalesce( Max( nivel), 0) INTO vMaxCl FROM TMP_TREE_ANALIZANOD;
  EXCEPTION WHEN OTHERS THEN
    vMaxCl := 0;
  END;

  WME_Result :=  vMaxCl;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_nivele_nclasea</obj_name>
  <obj_hashval>591493e5f4487ac1a7b58eb22a3fcc70</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_nivele_nclasea(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vMaxCL NUMERIC;
begin
  -- Bogdan 27.01.2022 corectie connect by root
  --Adina 04 august 2020
  vMaxCl := 0;
  BEGIN
    SELECT max( nivel) INTO vMaxCl FROM nclasea;
  EXCEPTION WHEN OTHERS THEN
    vMaxCl := 0;
  END;

  DELETE FROM TMP_PROFIT_NCLASEA;

  IF  vMaxCL &gt; 0 THEN
    INSERT INTO TMP_PROFIT_NCLASEA(CODCLASEA, DEN_CLASEA, SIMBOL, NIVEL)
    WITH RECURSIVE a (codclasea, codparinte,nivel, cod) AS
    (
     SELECT codclasea, codparinte, nivel,codclasea rootcodnirstoc
     FROM nclasea
     WHERE COALESCE(codparinte, 0) &lt;&gt; 0
     UNION ALL
     SELECT n.codclasea, n.codparinte, n.nivel, a.cod
     FROM nclasea n INNER JOIN a ON n.codclasea = a.codparinte
    )
    SELECT x.cod, c.den_clasea, c.simbol, Row_Number() OVER (PARTITION BY x.COD ORDER BY x.nivel) NIVEL
    FROM a x
      INNER JOIN nclasea c ON  c.codclasea = x.codclasea
    union ALL
    SELECT c.codclasea COD, c.den_clasea, c.simbol, c.nivel
    FROM nclasea c
    WHERE
     Coalesce( codparinte, 0) = 0;
--    SELECT x.cod, c.den_clasea, c.simbol, Row_Number() NIVEL
--    FROM (
--          SELECT  COD, codclasea, nivel FROM nclasea
--  --START WITH  Coalesce( codparinte, 0) &lt;&gt; 0
-- --CONNECT BY prior codparinte = codclasea
--    ) x
--      INNER JOIN nclasea c ON  c.codclasea = x.codclasea
--    union ALL
--    SELECT c.codclasea COD, c.den_clasea, c.simbol, c.nivel
--    FROM nclasea c
--    WHERE
--     Coalesce( codparinte, 0) = 0;
  END IF;

  WME_Result :=  vMaxCl;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_oldal_iopart1</obj_name>
  <obj_hashval>6ce946f8e0453a68348a165656af294f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_oldal_iopart1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.oldAL_IOPART1', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_oldal_iopers1</obj_name>
  <obj_hashval>5db9a3037cfdeb2cabc81f34ac8ee8a2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_oldal_iopers1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.oldAL_IOPERS1', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_oldcod_iopart1</obj_name>
  <obj_hashval>9f236c8f0734c315d7a5fed9e2332665</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_oldcod_iopart1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.oldCod_IOPART1', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_oldcod_iopers1</obj_name>
  <obj_hashval>1b515cba54b2d0db9c00d702f3e58c26</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_oldcod_iopers1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.oldCod_IOPERS1', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_oldcodc_iopart1</obj_name>
  <obj_hashval>d4d1f81c89d71dd8d40d1bc94097a61f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_oldcodc_iopart1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.oldCodC_IOPART1', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_oldcodc_iopers1</obj_name>
  <obj_hashval>eeae3f8b880199ff980f28be9bae62c4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_oldcodc_iopers1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.oldCodC_IOPERS1', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_oldcodp_iopart1</obj_name>
  <obj_hashval>87764928fc7a9c82ed5ffd70ae261850</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_oldcodp_iopart1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.oldCodP_IOPART1', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_oldcodp_iopers1</obj_name>
  <obj_hashval>f2e32ec3d80a4c2c8e23092631b4bf5d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_oldcodp_iopers1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.oldCodP_IOPERS1', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_oldden_iopart1</obj_name>
  <obj_hashval>c444c6fd3d6b171f089cd142baa1b433</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_oldden_iopart1(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_LIST_BASE_UTILS.oldDen_IOPART1', true);
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_oldden_iopers1</obj_name>
  <obj_hashval>9a7f25022d1c733e70d6958c4924fca9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_oldden_iopers1(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_LIST_BASE_UTILS.oldDen_IOPERS1', true);
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_oldidx_iopart1</obj_name>
  <obj_hashval>0302bee982636e4754edf308bb2ce484</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_oldidx_iopart1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.oldIdx_IOPART1', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_oldidx_iopers1</obj_name>
  <obj_hashval>4a1476373b023dd6c4f455bebc6d0835</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_oldidx_iopers1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.oldIdx_IOPERS1', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_ponderecomanda</obj_name>
  <obj_hashval>2469e1f915d36c01ad742977def86c2c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_ponderecomanda(INOUT wme_result numeric, INOUT pcodies numeric, INOUT pcodcomanda numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vTipIes  numeric;
  vPondere numeric;
begin
  vPondere := 0;
  SELECT TipDoc INTO vTipIes FROM iesiri WHERE codies = pCodIes;
  IF  vTipIes = 26 THEN
    SELECT Sum( CASE WHEN  codcomanda = pCodComanda THEN VLIN ELSE 0 END ) / Sum( VLIN) INTO vPondere
    FROM (SELECT Coalesce( c1.codcomanda, 0) CODCOMANDA,
                 CASE WHEN  I1.PU = 0 THEN 0 ELSE (I1.PU * I1.CANT + I1.TVA) * I1.PRETORIG * CASE
                                                                                               WHEN  I1.COEFDISCMAJ=0       THEN 1
                                                                                               WHEN  I1.COEFDISCMAJ IS NULL THEN 1
                                                                                               ELSE  I1.COEFDISCMAJ
                                                                                             END  / I1.PU
                 END  VLIN
          FROM iesiri1 i1
            LEFT JOIN ieslink  ila ON  ila.codies1 = i1.codies1
            LEFT JOIN ieslink  ilc ON  ilc.codies1 = ila.codlinieaviz
            LEFT JOIN comanda1 c1  ON  c1.codcomanda1 = ilc.codliniecomanda
          WHERE i1.codies = pCodIes
         ) A_PG
    WHERE VLIN &lt;&gt; 0;
  ELSE
    SELECT Sum( CASE WHEN  codcomanda = pCodComanda THEN VLIN ELSE 0 END ) / Sum( VLIN) INTO vPondere
    FROM (SELECT Coalesce( c1.codcomanda, 0) CODCOMANDA,
                 CASE WHEN  I1.PU = 0 THEN 0
                      ELSE (I1.PU * I1.CANT + CASE WHEN vTipIes IN (16, 21) THEN 0 ELSE I1.TVA END) * I1.PRETORIG * CASE
                                                                                                                      WHEN  I1.COEFDISCMAJ=0       THEN 1
                                                                                                                      WHEN  I1.COEFDISCMAJ IS NULL THEN 1
                                                                                                                      ELSE  I1.COEFDISCMAJ
                                                                                                                    END  / I1.PU
                 END  VLIN
          FROM iesiri1 i1
            LEFT JOIN ieslink  ilc ON  ilc.codies1    = i1.codies1
            LEFT JOIN comanda1 c1  ON  c1.codcomanda1 = ilc.codliniecomanda
          WHERE i1.codies = pCodIes
         ) B_PG
    WHERE VLIN &lt;&gt; 0;
  END IF;

  WME_Result :=  vPondere;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_ponderecomanda</obj_name>
  <obj_hashval>959c3e133c13b8b7ec0ee235ca85d79d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_ponderecomanda(pcodies numeric, pcodcomanda numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vTipIes   numeric;
  vPondere   numeric;
BEGIN
  --Adina 28 septembrie 2020
  vPondere := 0;

  SELECT TipDoc INTO vTipIes FROM iesiri WHERE codies = pCodIes;

  IF  vTipIes = 26 THEN
    SELECT Sum( CASE WHEN  codcomanda = pCodComanda THEN VLIN ELSE 0 END ) / Sum( VLIN)
    INTO vPondere
    FROM (SELECT   Coalesce( c1.codcomanda, 0) CODCOMANDA,
                  CASE WHEN  I1.PU = 0 THEN 0 ELSE (  I1.PU * I1.CANT + I1.TVA)  * I1.PRETORIG *
                    CASE WHEN  I1.COEFDISCMAJ=0 THEN 1
                         WHEN  I1.COEFDISCMAJ IS NULL THEN 1
                         ELSE  I1.COEFDISCMAJ
                    END  / I1.PU
                   END  VLIN
          FROM   iesiri1 i1
                LEFT JOIN ieslink ila ON  ila.codies1 = i1.codies1
                LEFT JOIN ieslink ilc ON  ilc.codies1 = ila.codlinieaviz
                LEFT JOIN comanda1 c1 ON  c1.codcomanda1 = ilc.codliniecomanda
          WHERE i1.codies = pCodIes
         ) A_PG
    WHERE VLIN &lt;&gt; 0;
  ELSE
    SELECT Sum( CASE WHEN  codcomanda = pCodComanda THEN VLIN ELSE 0 END ) / Sum( VLIN)
    INTO vPondere
    FROM (SELECT   Coalesce( c1.codcomanda, 0) CODCOMANDA,
                  CASE WHEN  I1.PU = 0 THEN 0 ELSE (  I1.PU * I1.CANT + CASE WHEN vTipIes IN (16, 21) THEN 0 ELSE I1.TVA END )  *
                    I1.PRETORIG * CASE WHEN  I1.COEFDISCMAJ=0 THEN 1
                                       WHEN  I1.COEFDISCMAJ IS NULL THEN 1
                                       ELSE  I1.COEFDISCMAJ
                                  END  / I1.PU
                   END  VLIN
          FROM   iesiri1 i1
                LEFT JOIN ieslink ilc ON  ilc.codies1 = i1.codies1
                LEFT JOIN comanda1 c1 ON  c1.codcomanda1 = ilc.codliniecomanda
          WHERE i1.codies = pCodIes
         ) B_PG
    WHERE VLIN &lt;&gt; 0;
  END IF;

  RETURN vPondere;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_puma1</obj_name>
  <obj_hashval>f32444d3314315ffd9ce02a55f5e8867</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_puma1(INOUT wme_result numeric, INOUT pcodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_LIST_BASE_UTILS_SET_UMA( pCodObiect);
  WME_Result :=  current_setting('PKG_LIST_BASE_UTILS.vPUMA1', true)::numeric;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_puma2</obj_name>
  <obj_hashval>fe588a49f02e18c529d911a07cbe1c5a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_puma2(INOUT wme_result numeric, INOUT pcodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_LIST_BASE_UTILS_SET_UMA( pCodObiect);
  WME_Result :=  current_setting('PKG_LIST_BASE_UTILS.vPUMA2', true)::numeric;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_puma3</obj_name>
  <obj_hashval>a7e1a63bbf8c41e78af83c1b260a0415</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_puma3(INOUT wme_result numeric, INOUT pcodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_LIST_BASE_UTILS_SET_UMA( pCodObiect);
  WME_Result :=  current_setting('PKG_LIST_BASE_UTILS.vPUMA3', true)::numeric;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_pumac</obj_name>
  <obj_hashval>a89909407a1e14806d36fed4287dd925</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_pumac(INOUT wme_result numeric, INOUT pcodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_LIST_BASE_UTILS_SET_UMA( pCodObiect);
  WME_Result :=  current_setting('PKG_LIST_BASE_UTILS.vPUMAC', true)::numeric;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_pumap</obj_name>
  <obj_hashval>7a1b0a9a47a8140a88dea272cf0f8cd7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_pumap(INOUT wme_result numeric, INOUT pcodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_LIST_BASE_UTILS_SET_UMA( pCodObiect);
  WME_Result :=  current_setting('PKG_LIST_BASE_UTILS.vPUMAP', true)::numeric;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_scdmartexcl</obj_name>
  <obj_hashval>7cf24e8b3c975547820b82317fc02238</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_scdmartexcl(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_LIST_BASE_UTILS.sCDMArtExcl', true);
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_set_filtre</obj_name>
  <obj_hashval>070eab17187637292e13b2ae879a64d9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_set_filtre(p_filtru character varying, p_val character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_val varchar;
  tmp   varchar;
  i     numeric;
begin
  tmp := p_val;
  IF (   length( tmp) &gt; 0) THEN
    tmp := tmp || ',';
  END IF;

  i := instr( tmp, ',');
  WHILE (i &gt; 0)  AND (length( tmp) &gt; 1)  LOOP
    v_val := substr( tmp, 1, i - 1);
    tmp   := substr( tmp, i + 1, length( tmp));
    i     := instr( tmp, ',');
    INSERT INTO tmp_manevra_liste(filtru, valoare) VALUES(p_filtru, v_val);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_set_lista_simbol_lipsa</obj_name>
  <obj_hashval>7396f483912c627d6d8ba32c7a66ce21</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_set_lista_simbol_lipsa(plista character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vListSimbLipsa VARCHAR;
  vLength INTEGER;
BEGIN
  vListSimbLipsa := pLista;
  vLength        := CASE
                      WHEN InStr(vListSimbLipsa, ',', 1, 5) BETWEEN 1 AND 150 THEN InStr(vListSimbLipsa, ',', 1, 5) - 1
                      WHEN Length(vListSimbLipsa)                       &gt; 150 THEN 150
                      ELSE 0
                    END;
  IF vLength &gt; 0 THEN
    vListSimbLipsa := SubStr(vListSimbLipsa, 1, vLength)||'...';
  END IF;
  perform set_config('PKG_LIST_BASE_UTILS.vListSimbLipsa',vListSimbLipsa,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_set_simbol_lipsa</obj_name>
  <obj_hashval>73d5a797ce3f16ca41ec65934ed69da9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_set_simbol_lipsa(INOUT wme_result numeric, INOUT pcodcont numeric, INOUT psimbol character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  IF  pCodCont = -1 THEN
    INSERT INTO TMP_LIPSA_CORESP_PLANP(SIMBOL) VALUES(pSimbol);
  END IF;
  WME_Result :=  0;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_set_uma</obj_name>
  <obj_hashval>b7736ca49e8b740708b626e8488bdc6e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_set_uma(pcodobiect numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  glb_vDUMA1 varchar;
  glb_vPUMA1 numeric;
  glb_vDUMA2 varchar;
  glb_vPUMA2 numeric;
  glb_vDUMA3 varchar;
  glb_vPUMA3 numeric;
  glb_vPUMAC numeric;
  glb_vPUMAP numeric;
begin
  IF  Coalesce( pCodObiect, 0) &lt;&gt; Coalesce( current_setting('PKG_LIST_BASE_UTILS.vCodObjUMA')::numeric, 0)
  THEN
    perform set_config('PKG_LIST_BASE_UTILS.vCodObjUMA',Coalesce( pCodObiect, 0)::varchar,false);
    SELECT Max( CASE WHEN  IDX=1 THEN DEN_UM1 END ) DUMA1,
           Max( CASE WHEN  IDX=1 THEN paritate END ) PUMA1,
           Max( CASE WHEN  IDX=2 THEN DEN_UM1 END ) DUMA2,
           Max( CASE WHEN  IDX=2 THEN paritate END ) PUMA2,
           Max( CASE WHEN  IDX=3 THEN DEN_UM1 END ) DUMA3,
           Max( CASE WHEN  IDX=3 THEN paritate END ) PUMA3,
           Max( CASE WHEN  CodExtern='CUTIE' THEN paritate END ) PUMAC,
           Max( CASE WHEN  CodExtern='PALET' THEN paritate END ) PUMAP
    INTO glb_vDUMA1, glb_vPUMA1, glb_vDUMA2, glb_vPUMA2, glb_vDUMA3, glb_vPUMA3, glb_vPUMAC, glb_vPUMAP
    FROM (
          SELECT AMB.CODOBIECT, Dense_Rank() OVER (PARTITION BY AMB.CODOBIECT ORDER BY AMB.CODAMB) IDX, U1.DEN_UM1, u1.paritate, Upper( U1.Codextern) CODEXTERN
          FROM NARTAMB AMB
            INNER JOIN NUM1 U1 ON  U1.CODUM1 = AMB.UMSEC
          WHERE
           AMB.CODOBIECT = (current_setting('PKG_LIST_BASE_UTILS.vCodObjUMA'))::numeric
    ) A_PG;
  END IF;
  perform PKG_LIST_BASE_UTILS_SetvDUMA1(glb_vDUMA1);
  perform PKG_LIST_BASE_UTILS_SetvPUMA1(glb_vPUMA1);
  perform PKG_LIST_BASE_UTILS_SetvDUMA2(glb_vDUMA2);
  perform PKG_LIST_BASE_UTILS_SetvPUMA2(glb_vPUMA2);
  perform PKG_LIST_BASE_UTILS_SetvDUMA3(glb_vDUMA3);
  perform PKG_LIST_BASE_UTILS_SetvPUMA3(glb_vPUMA3);
  perform PKG_LIST_BASE_UTILS_SetvPUMAC(glb_vPUMAC);
  perform PKG_LIST_BASE_UTILS_SetvPUMAP(glb_vPUMAP);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_set_var_monedafactinvaluta</obj_name>
  <obj_hashval>e27306d4678d3522372b012a31fd825c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_set_var_monedafactinvaluta(panluna numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  glb_vSimbMFIV varchar;
  glb_vCodMFIV  varchar;
BEGIN
  --Florin 24.05.2022 - sinc. Oracle
  --Bogdan 07.09.2020
  --Florin 14.01.2022 - sinc. Oracle (29.12.2021)
  perform set_config('PKG_LIST_BASE_UTILS.vAnLunaMFIV',pAnLuna::varchar,false);
  BEGIN
     SELECT fnc_array_to_vc3200 (ARRAY_AGG(simbol) ),
            CASE WHEN Count(1) = 1 THEN Max(CodMoneda) ELSE NULL END
     INTO glb_vSimbMFIV, glb_vCodMFIV
     FROM NMONEDE
     WHERE CODMONEDA IN (SELECT CV.VALOARE::numeric
     FROM CONST1 C1
      INNER JOIN CONSTLUNA CL ON CL.codconst1 = C1.codConst1
      LEFT  JOIN CONSTVAL  CV ON CV.codconstluna = CL.codconstluna
    WHERE UPPER(C1.simbol) = 'MONEDAFACTINVALUTA' AND current_setting('PKG_LIST_BASE_UTILS.vAnLunaMFIV', true)::numeric BETWEEN cl.ALStart AND cl.ALStop);
    EXCEPTION WHEN OTHERS THEN glb_vSimbMFIV = ''; glb_vCodMFIV = '';
  END;

  perform PKG_LIST_BASE_UTILS_SetvSimbMFIV(glb_vSimbMFIV);
  perform PKG_LIST_BASE_UTILS_SetvCodMFIV(glb_vCodMFIV);

end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setganfin</obj_name>
  <obj_hashval>986dab24e15c3269ba76571b1d98b499</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setganfin(aganfin numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.gAnFin',to_char(agAnFin,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setganini</obj_name>
  <obj_hashval>4ddcbddc3ad06cfc462a44368fb949cc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setganini(aganini numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.gAnIni',to_char(agAnIni,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setgestdedicate</obj_name>
  <obj_hashval>5aab9b241b1c57e4d79f038bc33eeeb9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setgestdedicate()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 04.02.2025
  delete FROM tmp_manevra_liste where filtru = 'CODGEST';
  insert into tmp_manevra_liste(filtru,valoare)
  select 'CODGEST', codgest
  from tmp_gestdedicate;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setglunafin</obj_name>
  <obj_hashval>6e20f4cfec83a5826c396942127025b1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setglunafin(aglunafin numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.gLunaFin',to_char(agLunaFin,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setglunaini</obj_name>
  <obj_hashval>de4c4f8cb2cd88e3f40725db907324d8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setglunaini(aglunaini numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.gLunaIni',to_char(agLunaIni,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setoldal_iopart1</obj_name>
  <obj_hashval>6a10de33c38340bb5cd6889bb51c40bc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setoldal_iopart1(aoldal_iopart1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.oldAL_IOPART1',to_char(aoldAL_IOPART1,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setoldal_iopers1</obj_name>
  <obj_hashval>7b9518906c917f752b265eca828de225</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setoldal_iopers1(aoldal_iopers1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.oldAL_IOPERS1',to_char(aoldAL_IOPERS1,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setoldcod_iopart1</obj_name>
  <obj_hashval>b8617d47627dfe2812772605958933d4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setoldcod_iopart1(aoldcod_iopart1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.oldCod_IOPART1',to_char(aoldCod_IOPART1,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setoldcod_iopers1</obj_name>
  <obj_hashval>c1e2086b1fdfa80d150e10171a6028be</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setoldcod_iopers1(aoldcod_iopers1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.oldCod_IOPERS1',to_char(aoldCod_IOPERS1,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setoldcodc_iopart1</obj_name>
  <obj_hashval>47a6d1a48aa56cd1ed1bfbb5562da721</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setoldcodc_iopart1(aoldcodc_iopart1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.oldCodC_IOPART1',to_char(aoldCodC_IOPART1,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setoldcodc_iopers1</obj_name>
  <obj_hashval>72b7a0b65486b48cea81fa63b6055c17</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setoldcodc_iopers1(aoldcodc_iopers1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.oldCodC_IOPERS1',to_char(aoldCodC_IOPERS1,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setoldcodp_iopart1</obj_name>
  <obj_hashval>30d4078dbfac9fe4c09f96ec91028ebc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setoldcodp_iopart1(aoldcodp_iopart1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.oldCodP_IOPART1',to_char(aoldCodP_IOPART1,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setoldcodp_iopers1</obj_name>
  <obj_hashval>02592c7c4622a5c429b8ca9531f5bf21</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setoldcodp_iopers1(aoldcodp_iopers1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.oldCodP_IOPERS1',to_char(aoldCodP_IOPERS1,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setoldden_iopart1</obj_name>
  <obj_hashval>f8df9bd1e5b611a4283ae7ea14950b44</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setoldden_iopart1(aoldden_iopart1 character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.oldDen_IOPART1',aoldDen_IOPART1,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setoldden_iopers1</obj_name>
  <obj_hashval>ed9a53bc23f40b607ffe15306734cc73</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setoldden_iopers1(aoldden_iopers1 character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.oldDen_IOPERS1',aoldDen_IOPERS1,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setoldidx_iopart1</obj_name>
  <obj_hashval>8fb5445855029429027d1ecc82222b2f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setoldidx_iopart1(aoldidx_iopart1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.oldIdx_IOPART1',to_char(aoldIdx_IOPART1,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setoldidx_iopers1</obj_name>
  <obj_hashval>4cac7a28bcf2f8008adeb651365aaa9f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setoldidx_iopers1(aoldidx_iopers1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.oldIdx_IOPERS1',to_char(aoldIdx_IOPERS1,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setscdmartexcl</obj_name>
  <obj_hashval>99958318a5d777502993c9073dec46bb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setscdmartexcl(ascdmartexcl character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.sCDMArtExcl',asCDMArtExcl,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setsubdedicate</obj_name>
  <obj_hashval>7155a9d9a324398498d9cb4a55f976a2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setsubdedicate()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 26.11.2024
  insert into tmp_manevra_liste(filtru,valoare)
  select 'CODSUBUNIT', codsubunit
    from tmp_subunitdedicate;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvanlunabcpuv</obj_name>
  <obj_hashval>67276eb0c1cfa209beee0eae8c49603a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvanlunabcpuv(avanlunabcpuv numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vAnLunaBCPUV',to_char(avAnLunaBCPUV,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvanlunamfiv</obj_name>
  <obj_hashval>53c040f9cc78906d73c036f6b658f0dc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvanlunamfiv(avanlunamfiv numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vAnLunaMFIV',to_char(avAnLunaMFIV,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvanlunamin</obj_name>
  <obj_hashval>c3ab67414a2a8cc78e155bea72a0acf8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvanlunamin(avanlunamin numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vAnLunaMin',to_char(avAnLunaMin,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvanlunatva</obj_name>
  <obj_hashval>861dd00034da87e57acfa154df012062</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvanlunatva(avanlunatva numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vAnLunaTVA',to_char(avAnLunaTVA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvcdman</obj_name>
  <obj_hashval>0857445eef9065ecac5a1d1aaaa1c511</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvcdman(avcdman numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vCDMAn',to_char(avCDMAn,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvcdmcintermedcm</obj_name>
  <obj_hashval>c40530df2b519b487fcb71e1dcff5f68</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvcdmcintermedcm(avcdmcintermedcm numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vCDMCIntermedCM',to_char(avCDMCIntermedCM,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvcdmcodies</obj_name>
  <obj_hashval>61a4de356e473128f3ae3080a8bb645b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvcdmcodies(avcdmcodies numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vCDMCodIes',to_char(avCDMCodIes,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvcdmconincfact</obj_name>
  <obj_hashval>8fe1025d2c1e7344ae5e8391c63b267d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvcdmconincfact(avcdmconincfact numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vCDMConIncFact',to_char(avCDMConIncFact,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvcdmluna</obj_name>
  <obj_hashval>a8b54498c6a6eccf70c64306c3ad7670</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvcdmluna(avcdmluna numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vCDMLuna',to_char(avCDMLuna,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvcdmtvadisc</obj_name>
  <obj_hashval>50ede889f89102f309f763ca9a84c855</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvcdmtvadisc(avcdmtvadisc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vCDMTvaDisc',to_char(avCDMTvaDisc,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvcdmtvadoc</obj_name>
  <obj_hashval>523e0e4d6df85aa8e191d9d80d7f81ab</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvcdmtvadoc(avcdmtvadoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vCDMTvaDoc',to_char(avCDMTvaDoc,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvcdmtvalin</obj_name>
  <obj_hashval>a68077c0972354b7cbffc2ad1d15cdb2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvcdmtvalin(avcdmtvalin numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vCDMTvaLin',to_char(avCDMTvaLin,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvcdmvaldisc</obj_name>
  <obj_hashval>23349d3c81b40dd8ff10f05926f582f7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvcdmvaldisc(avcdmvaldisc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vCDMValDisc',to_char(avCDMValDisc,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvcdmvaldoc</obj_name>
  <obj_hashval>391b62b7e0ee5e39872a682995ef9665</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvcdmvaldoc(avcdmvaldoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vCDMValDoc',to_char(avCDMValDoc,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvcdmvallin</obj_name>
  <obj_hashval>161f1bf336e123abf5a396a6874a79b0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvcdmvallin(avcdmvallin numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vCDMValLin',to_char(avCDMValLin,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvcodmfiv</obj_name>
  <obj_hashval>c53235a95d41da1d7b4a49ac623662af</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvcodmfiv(avcodmfiv character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vCodMFIV',avCodMFIV,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvcodobjuma</obj_name>
  <obj_hashval>e858cb09be99304c0b893f30e7e3c56e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvcodobjuma(avcodobjuma numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vCodObjUMA',to_char(avCodObjUMA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvdenbcpuv</obj_name>
  <obj_hashval>6d5c94ff07a6f1ba9e9d418a896fb3c1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvdenbcpuv(avdenbcpuv character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vDenBCPUV',avDenBCPUV,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvduma1</obj_name>
  <obj_hashval>ba8e147d74fbdeab15ac111cf2edb409</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvduma1(avduma1 character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vDUMA1',avDUMA1,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvduma2</obj_name>
  <obj_hashval>123fd58b1ed7beed6e6e6ffef8ec06fc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvduma2(avduma2 character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vDUMA2',avDUMA2,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvduma3</obj_name>
  <obj_hashval>53cfa2d812b2b9a453bc5410ae38dddb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvduma3(avduma3 character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vDUMA3',avDUMA3,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvlistsimblipsa</obj_name>
  <obj_hashval>19e0ef739d2c21442c97cffb7dbbe9d1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvlistsimblipsa(avlistsimblipsa character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vListSimbLipsa',avListSimbLipsa,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvpj1tip</obj_name>
  <obj_hashval>3cb1f814d55e6dbd1885a6b99f9cd1dc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvpj1tip(avpj1tip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vPj1TIP',to_char(avPj1TIP,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvpj1tva</obj_name>
  <obj_hashval>981a28644b69f812be92a7f0ee0d5644</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvpj1tva(avpj1tva numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vPj1TVA',to_char(avPj1TVA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvpj2tip</obj_name>
  <obj_hashval>88775248f8491548902bf45fd08c6514</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvpj2tip(avpj2tip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vPj2TIP',to_char(avPj2TIP,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvpj2tva</obj_name>
  <obj_hashval>4487171df58759fdf593c1e3b416ba9a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvpj2tva(avpj2tva numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vPj2TVA',to_char(avPj2TVA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvpj3tip</obj_name>
  <obj_hashval>b8722e852563a6a772e3c0a001d970fa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvpj3tip(avpj3tip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vPj3TIP',to_char(avPj3TIP,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvpj3tva</obj_name>
  <obj_hashval>3cbef5c9940f68a25b370d66345e868f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvpj3tva(avpj3tva numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vPj3TVA',to_char(avPj3TVA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvpj4tip</obj_name>
  <obj_hashval>662ad57a9151fe25a536fa02fda22d9f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvpj4tip(avpj4tip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vPj4TIP',to_char(avPj4TIP,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvpj4tva</obj_name>
  <obj_hashval>0afd732fc208e7c85f6ea351d9c4d855</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvpj4tva(avpj4tva numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vPj4TVA',to_char(avPj4TVA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvpj5tip</obj_name>
  <obj_hashval>918d42e1ba4d153d5360e61ea4daa5fd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvpj5tip(avpj5tip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vPj5TIP',to_char(avPj5TIP,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvpuma2</obj_name>
  <obj_hashval>ba0c2ec0dc4378a399943ae6ae958db6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvpuma2(avpuma2 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vPUMA2',avPUMA2::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvpuma3</obj_name>
  <obj_hashval>77589ce3173c56353346e890b4b6104c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvpuma3(avpuma3 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vPUMA3',avPUMA3::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvpumac</obj_name>
  <obj_hashval>f8c3d9ddb2561790500066d508d0af08</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvpumac(avpumac numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vPUMAC',avPUMAC::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvpumap</obj_name>
  <obj_hashval>5ef2f3e4eeedfddc08c5b4010adcc11a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvpumap(avpumap numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vPUMAP',avPUMAP::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvsdd_obsdoc</obj_name>
  <obj_hashval>42b50e2333ed7095ab4d688dede41dd2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvsdd_obsdoc(avsdd_obsdoc character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vSDD_ObsDoc',avSDD_ObsDoc,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvsdd_partdoc</obj_name>
  <obj_hashval>2dcabc3cbbce98421ea88c7b49e10fe7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvsdd_partdoc(avsdd_partdoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vSDD_PartDoc',to_char(avSDD_PartDoc,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvsdd_tabladoc</obj_name>
  <obj_hashval>4a1bc70a4118122437a3d872dc985b1a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvsdd_tabladoc(avsdd_tabladoc character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vSDD_TablaDoc',avSDD_TablaDoc,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvsdd_tipdoc</obj_name>
  <obj_hashval>c1e791dac45a7d799b7fed8ca874ea7c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvsdd_tipdoc(avsdd_tipdoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vSDD_TipDoc',to_char(avSDD_TipDoc,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvsdd_userdoc</obj_name>
  <obj_hashval>f5eb7195cfb829e3e4677432d55680e7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvsdd_userdoc(avsdd_userdoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vSDD_UserDoc',to_char(avSDD_UserDoc,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvsimbmfiv</obj_name>
  <obj_hashval>dae2d8b9dad18c2346e93bafc55fd9cd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvsimbmfiv(avsimbmfiv character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vSimbMFIV',avSimbMFIV,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvtt0_al</obj_name>
  <obj_hashval>7530f2b9886f131e9a39280551b310ba</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvtt0_al(avtt0_al numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vTT0_AL',to_char(avTT0_AL,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvtt0_cntjvartneimp</obj_name>
  <obj_hashval>476b69ef3bc6621050098703e51db83a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvtt0_cntjvartneimp(avtt0_cntjvartneimp numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vTT0_CntJVARTNEIMP',to_char(avTT0_CntJVARTNEIMP,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvtt0_codobiect</obj_name>
  <obj_hashval>989de9a8a38240b8dfe4cca353a1066d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvtt0_codobiect(avtt0_codobiect numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vTT0_CodObiect',to_char(avTT0_CodObiect,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvtt0_res</obj_name>
  <obj_hashval>6b53340bb4d6156dd43c28cc9189a264</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvtt0_res(avtt0_res numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vTT0_Res',to_char(avTT0_Res,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvtt0_tva0faraded</obj_name>
  <obj_hashval>9bf933e00c236152b5547313deb1d190</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvtt0_tva0faraded(avtt0_tva0faraded character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vTT0_TVA0FaraDed',avTT0_TVA0FaraDed,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_uma_utils</obj_name>
  <obj_hashval>45cc2470b3395da8517cd3f20aa3ddab</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_uma_utils(INOUT ccant character varying, INOUT ccodobiect character varying, INOUT sinsertuma character varying, INOUT sselectuma character varying, INOUT sjoinuma character varying, INOUT scufunctii boolean DEFAULT false)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vConfirm numeric;
BEGIN
  --Adina 04 august 2020; 01.10.2020 add delault false pt.parametrul scufunctii
  --Florin 14.05.2020 - adaugat group by
  vConfirm := 0;
  --IF  (SELECT pkg_categconst_GetValConstanta.WME_RESULT FROM pkg_categconst_GetValConstanta(NULL, 'ListareUMAmbRapVanz', TO_NUMBER(current_setting('PKG_GLOBALS.anlucru', true),'999999999999999999'), TO_NUMBER(current_setting('PKG_GLOBALS.lunalucru', true),'999999999999999999'))) = '1'
  IF Coalesce(fnc_GetValConstanta('ListareUMAmbRapVanz', getANLUCRU(), getLUNALUCRU()), '1') = '1' THEN
    DELETE FROM TMP_UMA;
    INSERT INTO TMP_UMA(CODOBIECT, DUMA1, PUMA1, DUMA2, PUMA2, DUMA3, PUMA3, PUMAC, PUMAP)
    SELECT CODOBIECT,
           Max( CASE WHEN  IDX=1 THEN DEN_UM1  END ) DUMA1,
           Max( CASE WHEN  IDX=1 THEN paritate END ) PUMA1,
           Max( CASE WHEN  IDX=2 THEN DEN_UM1  END ) DUMA2,
           Max( CASE WHEN  IDX=2 THEN paritate END ) PUMA2,
           Max( CASE WHEN  IDX=3 THEN DEN_UM1  END ) DUMA3,
           Max( CASE WHEN  IDX=3 THEN paritate END ) PUMA3,
           Max( CASE WHEN  CodExtern='CUTIE' THEN paritate END ) PUMAC,
           Max( CASE WHEN  CodExtern='PALET' THEN paritate END ) PUMAP
    FROM (
          SELECT  DISTINCT AMB.CODOBIECT, Dense_Rank() OVER (PARTITION BY AMB.CODOBIECT ORDER BY AMB.CODAMB) IDX, U1.DEN_UM1, u1.paritate, Upper( U1.Codextern) CODEXTERN
          FROM NARTAMB AMB
            INNER JOIN NUM1 U1 ON  U1.CODUM1 = AMB.UMSEC
    ) A_PG GROUP BY CODOBIECT;

    SELECT COUNT( 1) INTO vConfirm FROM TMP_UMA;
  END IF;

  IF  vConfirm &gt; 0 THEN
    sInsertUMA := ', DUMA1, CUMA1, DUMA2, CUMA2, DUMA3, CUMA3, CUMAC, CUMAP';
    sSelectUMA := ', UMA.DUMA1, ' || cCant || '/UMA.PUMA1, UMA.DUMA2, ' || cCant || '/UMA.PUMA2, UMA.DUMA3, ' || cCant || '/UMA.PUMA3, ' || cCant || '/UMA.PUMAC, ' || cCant || '/UMA.PUMAP';
    sJoinUMA := '
    LEFT JOIN TMP_UMA UMA ON UMA.CODOBIECT = ' || cCodObiect;
    IF sCuFunctii THEN
      sSelectUMA := ',
      (select wme_result from PKG_LIST_BASE_UTILS_DUMA1(' || cCodObiect || ')), ' || cCant || '/(select wme_result from PKG_LIST_BASE_UTILS_PUMA1(' || cCodObiect || ')),
      (select wme_result from PKG_LIST_BASE_UTILS_DUMA2(' || cCodObiect || ')), ' || cCant || '/(select wme_result from PKG_LIST_BASE_UTILS_PUMA2(' || cCodObiect || ')),
      (select wme_result from PKG_LIST_BASE_UTILS_DUMA3(' || cCodObiect || ')), ' || cCant || '/(select wme_result from PKG_LIST_BASE_UTILS_PUMA3(' || cCodObiect || ')),
      ' || cCant || '/(select wme_result from PKG_LIST_BASE_UTILS.PUMAC(' || cCodObiect || ')), ' || cCant || '/(select wme_result from PKG_LIST_BASE_UTILS.PUMAP(' || cCodObiect || '))';
      sJoinUMA := '';
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_umple_tmp_camere_lst</obj_name>
  <obj_hashval>77f0d12b334686d8f7bf3bfb01ff9cea</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_umple_tmp_camere_lst()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  VREC       RECORD;
  vLocLib    numeric;
  vLocRez    numeric;
  vLocContr  numeric;
  vDataRef   date;
  vCodObjCam numeric;
BEGIN
  --Florin 31.05.2024 - immediate
  DELETE FROM TMP_CAMERE_LST;
  vCodObjCam := Coalesce( (fnc_GetValConstantaLucru('ArtOcupGestCam')::numeric), 0);
  BEGIN
    EXECUTE 'CREATE INDEX idx_tmp_camere_lst ON TMP_CAMERE_LST (codgest)';
  EXCEPTION
    WHEN OTHERS THEN NULL;
  END;

  INSERT INTO TMP_CAMERE_LST
  SELECT codgest, 0, 0, 0, 0 FROM ngest WHERE Coalesce(tip,0) &lt;&gt; 6;

  vDataRef := To_Date( '01' || To_Char( getlunalucru(), 'fm00') || To_Char( getanlucru(), 'fm0000'), 'ddmmyyyy');
  IF  DATE_TRUNC('DAY', CURRENT_TIMESTAMP, 'mm') = vDataRef THEN
    vDataRef := DATE_TRUNC('DAY', CURRENT_TIMESTAMP, 'dd');
  END IF;

  FOR vRec IN (SELECT codgest, cantitate locuri FROM ngest WHERE Coalesce(tip,0) = 6) LOOP
    SELECT Coalesce( Sum( c1.restacceptat), 0) INTO vLocRez
    FROM comanda1 c1 INNER JOIN comanda c ON  c.codcomanda = c1.codcomanda
    WHERE c1.GestAct = vRec.CodGest AND  c1.CodObiect = vCodObjCam
      AND c.An * 12 + c.Luna &lt;= getAnLunaLucru()
      AND Coalesce( c.anulat, 0) = 0 AND  Coalesce( c.operat, 0) = 1;

    SELECT Coalesce( Sum( c1.cant), 0) INTO vLocContr
    FROM contract1 c1 INNER JOIN contract c ON  c.codcontract = c1.codcontract
    WHERE c1.GestAct = vRec.CodGest AND  c1.CodObiect = vCodObjCam
      AND vDataRef BETWEEN Coalesce( C1.DataStart, C.DataStart) AND Coalesce( C1.DataStop, C.DataStop)
      AND Coalesce( c.anulat, 0) = 0 AND Coalesce( c.operat, 0) = 1;

    vLocLib := vRec.Locuri - vLocContr;
    INSERT INTO TMP_CAMERE_LST(CODGEST, LOCURI, LOCLIB, LOCREZ, LOCCONTR)
    VALUES(vRec.CodGest, vRec.Locuri, vLocLib, vLocRez, vLocContr);
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_umple_tmp_constval_lst</obj_name>
  <obj_hashval>6a2f76db69845599cc7a92bc32e9dfd9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_umple_tmp_constval_lst(psimbollist character varying DEFAULT ''::character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vWhere VARCHAR(10000);
  cSql   TEXT;
begin
  DELETE FROM TMP_CONSTVAL_LST;

  vWhere := Upper(REPLACE(pSimbolList,' ',''));

  IF COALESCE(vWhere, '') &lt;&gt; '' THEN
    vWhere := '
    WHERE (UPPER(C1.simbol) IN ('''||REPLACE(vWhere, ',',''',''')||'''))';
  END IF;

  cSql := 'INSERT INTO TMP_CONSTVAL_LST
  SELECT
    C.SIMBOL,
    CASE
      WHEN LAG(C.ALSTART) OVER (PARTITION BY C.SIMBOL ORDER BY C.ALSTART) IS NOT NULL THEN C.ALSTART
      WHEN C.ALSTART = (SELECT B.ANINITIAL*12+B.LUNAINITIALA FROM FIRMALUNI B) THEN 0
      ELSE C.ALSTART
    END ALUNASTART,
    Coalesce(LEAD(C.ALSTART) OVER (PARTITION BY C.SIMBOL ORDER BY C.ALSTART) - 1, 99999) ANLUNASTOP,
    STRING_AGG(VALOARE, '','') VAL
  FROM (
    SELECT Upper(C1.SIMBOL) AS SIMBOL, CL.ANSTART*12 + CL.LUNASTART AS ALSTART, CV.VALOARE
    FROM CONST1 C1
      INNER JOIN CATEGCONST CT ON CT.CODCATEG     = C1.CODCATEG
      INNER JOIN CONSTLUNA  CL ON CL.CODCONST1    = C1.CODCONST1 AND CL.USERID = CASE WHEN CT.TIPCATEG = ''G'' THEN 0 WHEN CT.TIPCATEG = ''U'' THEN getuserid() END
      LEFT  JOIN CONSTVAL   CV ON CV.CODCONSTLUNA = CL.CODCONSTLUNA'||
  vWhere||'
    ) C
  GROUP BY SIMBOL, ALSTART';

  EXECUTE cSql;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_umple_tmp_lst_curs</obj_name>
  <obj_hashval>740040e46f73af5ac4c2e302f7947c6e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_umple_tmp_lst_curs(acodbanca numeric, adata date, acodmoneda numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCodBanca character varying;
  vData     date;
BEGIN
  --Adina 03.12.2020 tichet 41405 - adaugat PARTITION BY CODMONEDA
  --Adina 17 august 2020 - modif.cu fnc_getvalconstanta si inlocuit conversia cu Last_Value pt.ca nu rezulta acelasi set de date
  IF aCODBANCA IS NULL THEN
    --vCodBanca := (SELECT pkg_categconst_GetValConstanta.WME_RESULT FROM pkg_categconst_GetValConstanta(NULL, 'BancaSitV', TO_NUMBER(current_setting('PKG_GLOBALS.ANLUCRU', true),'999999999999999999'), TO_NUMBER(current_setting('PKG_GLOBALS.LUNALUCRU', true),'999999999999999999')));
    vCodBanca := fnc_GetValConstanta('BancaSitV',getANLUCRU(),getLUNALUCRU());
  ELSE
    vCodBanca := aCODBANCA;
  END IF;

  IF aDATA IS NULL THEN
    vData := CURRENT_TIMESTAMP;
  ELSE
    vData := aData;
  END IF;

  DELETE FROM TMP_LST_CURS;

  IF vCodBanca IS NOT NULL THEN
    INSERT INTO TMP_LST_CURS
    --SELECT  DISTINCT CODMONEDA, LAST_VALUE( VALOARE) OVER (  ORDER BY DATA desc)
    --FROM NMONEDE1
    --WHERE data &lt;= vData AND  CODMONEDA = Coalesce( aCODMONEDA, CODMONEDA);
    SELECT CODMONEDA, Max(VALOARE)
    FROM (SELECT CODMONEDA, VALOARE, Dense_Rank() Over (PARTITION BY CODMONEDA ORDER BY DATA DESC) NR
          FROM NMONEDE1
          WHERE data &lt;= vData AND CODMONEDA = Coalesce(aCODMONEDA, CODMONEDA)
         ) x WHERE x.NR=1
    GROUP BY CODMONEDA;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_umple_tmp_nartatr_lst</obj_name>
  <obj_hashval>982721261e86451cd9006d34c7424506</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_umple_tmp_nartatr_lst()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 29 septembrie 2020
  DELETE FROM TMP_NARTATR_LST;
  BEGIN
    EXECUTE 'CREATE INDEX idx_tmp_nartatr_lst ON TMP_NARTATR_LST (codarticol)';
  EXCEPTION WHEN OTHERS THEN
    NULL;
  END;

  INSERT INTO TMP_NARTATR_LST
  SELECT codarticol, string_agg(obs,COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|') ORDER BY indexlocal) OBS
  FROM nartatr
  GROUP BY codarticol;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vanlunabcpuv</obj_name>
  <obj_hashval>0ff2c5d19dbe70cda1d77d973581e25e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vanlunabcpuv(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vAnLunaBCPUV', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vanlunamfiv</obj_name>
  <obj_hashval>5e3f027b23ee805d7173600f075e7d45</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vanlunamfiv(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vAnLunaMFIV', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vanlunamin</obj_name>
  <obj_hashval>9a46aa1c809ff4fdb362d98371cd3b1f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vanlunamin(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vAnLunaMin', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vanlunatva</obj_name>
  <obj_hashval>3f22a68703cada79a7a4492b23a7d725</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vanlunatva(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vAnLunaTVA', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vcdman</obj_name>
  <obj_hashval>574a7791d5c08cc8a255c5d1e2bd4a67</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vcdman(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vCDMAn', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vcdmcintermedcm</obj_name>
  <obj_hashval>2b73d2748679e70306d2166c4dfa32b8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vcdmcintermedcm(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vCDMCIntermedCM', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vcdmcodies</obj_name>
  <obj_hashval>031b2b085f50e2111142fc234551b408</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vcdmcodies(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vCDMCodIes', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vcdmconincfact</obj_name>
  <obj_hashval>cabb98363bde9d60313b0b6a23f7acdc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vcdmconincfact(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vCDMConIncFact', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vcdmluna</obj_name>
  <obj_hashval>87fdc0dcd650bec16489a75d9d661ecd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vcdmluna(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vCDMLuna', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vcdmtvadisc</obj_name>
  <obj_hashval>1499c10599dd17315780a6b9f5c2073d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vcdmtvadisc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vCDMTvaDisc', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vcdmtvadoc</obj_name>
  <obj_hashval>e6823a73c0df9c41de4e074dbffcd337</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vcdmtvadoc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vCDMTvaDoc', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vcdmtvalin</obj_name>
  <obj_hashval>38d91b2c8f7431363e421aa26f772d1d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vcdmtvalin(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vCDMTvaLin', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vcdmvaldisc</obj_name>
  <obj_hashval>ecb23bcef75d49689a23967a4fb2367b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vcdmvaldisc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vCDMValDisc', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vcdmvaldoc</obj_name>
  <obj_hashval>ce2e5c1c843429195f65eea4edd126dc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vcdmvaldoc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vCDMValDoc', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vcdmvallin</obj_name>
  <obj_hashval>da9af4b7307cb5f1b5dee44538a3d948</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vcdmvallin(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vCDMValLin', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vcodmfiv</obj_name>
  <obj_hashval>0a8e015b1a3db3de725bd15c4b7e1339</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vcodmfiv(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_UTILS.vCodMFIV', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vcodobjuma</obj_name>
  <obj_hashval>4a704a2b371162899abc16d39d3e22a6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vcodobjuma(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vCodObjUMA', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vdenbcpuv</obj_name>
  <obj_hashval>b7b2e894dadbe7e51e718f2fa5d8af49</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vdenbcpuv(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_UTILS.vDenBCPUV', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vduma1</obj_name>
  <obj_hashval>73c9dae8c25b28639cdbf42cf31f2feb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vduma1(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_UTILS.vDUMA1', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vduma2</obj_name>
  <obj_hashval>fef6a0f7ea2b60e021cc9771b634c1dc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vduma2(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_UTILS.vDUMA2', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vduma3</obj_name>
  <obj_hashval>74b96a2f5a0e99edeea598cef5f641e0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vduma3(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_UTILS.vDUMA3', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vlistsimblipsa</obj_name>
  <obj_hashval>a26ecc79ae47f985dd53ddb8b2e15c23</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vlistsimblipsa(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_UTILS.vListSimbLipsa', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vpj1tip</obj_name>
  <obj_hashval>6da8d1b1f269c2be7878e52ba28e34bd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vpj1tip(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPj1TIP', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vpj1tva</obj_name>
  <obj_hashval>28c072ce9fbe61a9659d612e6a3cf798</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vpj1tva(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPj1TVA', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vpj2tip</obj_name>
  <obj_hashval>b04c88ce0f6f58a458dc6634f55fb6dd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vpj2tip(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPj2TIP', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vpj2tva</obj_name>
  <obj_hashval>37b97aadac9a8bb0853a26668ca4e174</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vpj2tva(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPj2TVA', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vpj3tip</obj_name>
  <obj_hashval>5bed4c4cb529f50dac0af48c0239ce6e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vpj3tip(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPj3TIP', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vpj3tva</obj_name>
  <obj_hashval>357f181e4b4f7eb3669ec1ca714eccfd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vpj3tva(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPj3TVA', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vpj4tip</obj_name>
  <obj_hashval>002ec07de310c1560e9b7929a6985cf8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vpj4tip(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPj4TIP', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vpj4tva</obj_name>
  <obj_hashval>5ce392b15e4184819462631f94910fd7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vpj4tva(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPj4TVA', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vpj5tip</obj_name>
  <obj_hashval>5da27d498523799ef88b472f68fe78b2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vpj5tip(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPj5TIP', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vpj5tva</obj_name>
  <obj_hashval>da1ff95515800af6974a13010af5d9f0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vpj5tva(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPj5TVA', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vpuma1</obj_name>
  <obj_hashval>3aa2fa4aa4b7bd8f7aef25de42f16807</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vpuma1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPUMA1', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vpuma2</obj_name>
  <obj_hashval>4d9a043c45dc1e07a42443bdb45995b9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vpuma2(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPUMA2', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vpuma3</obj_name>
  <obj_hashval>d3d8c9d48b95a25a32de9d42928a4b85</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vpuma3(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPUMA3', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vpumac</obj_name>
  <obj_hashval>d28e6362263dec3c5fc3be3e0ad3c21d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vpumac(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPUMAC', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vpumap</obj_name>
  <obj_hashval>55a950b3e17babe5ad6730c2073b40d8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vpumap(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vPUMAP', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vsdd_coddoc</obj_name>
  <obj_hashval>0635e101cfb76b5173766ab284f22cb8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vsdd_coddoc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vSDD_CodDoc', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vsdd_dendoc</obj_name>
  <obj_hashval>0c6aa207b7c1559f5d98b70654d5b63a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vsdd_dendoc(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_UTILS.vSDD_DenDoc', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vsdd_obsdoc</obj_name>
  <obj_hashval>7ddf575e5086a84a3eaf0a69c76d3872</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vsdd_obsdoc(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_UTILS.vSDD_ObsDoc', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vsdd_partdoc</obj_name>
  <obj_hashval>0c872bffa181cb5db27a9759c845077b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vsdd_partdoc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vSDD_PartDoc', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vsdd_tabladoc</obj_name>
  <obj_hashval>c1601f1d120504f0898610b766fb3f23</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vsdd_tabladoc(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_UTILS.vSDD_TablaDoc', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vsdd_tipdoc</obj_name>
  <obj_hashval>2d40e291c6d2e93d28320290fe24310e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vsdd_tipdoc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vSDD_TipDoc', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vsdd_userdoc</obj_name>
  <obj_hashval>a446ae5f74cf004327f322e66c0ae4f6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vsdd_userdoc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vSDD_UserDoc', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vsimbmfiv</obj_name>
  <obj_hashval>9eb2833692a824f994d51f08a92dd387</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vsimbmfiv(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_UTILS.vSimbMFIV', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vtt0_al</obj_name>
  <obj_hashval>d472e3d5b3bcce2f0425956f8cbf4d35</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vtt0_al(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vTT0_AL', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vtt0_cntjvartneimp</obj_name>
  <obj_hashval>70f8784b39082e7334bd6137954622b6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vtt0_cntjvartneimp(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vTT0_CntJVARTNEIMP', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vtt0_codobiect</obj_name>
  <obj_hashval>b94821f23e419cc4e5d758a6e9442c1d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vtt0_codobiect(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vTT0_CodObiect', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vtt0_res</obj_name>
  <obj_hashval>d8fa0021724fdbd885d2857eeb3eacdb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vtt0_res(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vTT0_Res', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_vtt0_tva0faraded</obj_name>
  <obj_hashval>fe1ef18e5542272328bcb57391313c8e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_vtt0_tva0faraded(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_UTILS.vTT0_TVA0FaraDed', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanz_spec_setjoinuri</obj_name>
  <obj_hashval>c2d47c4fb28f1ffe39afa52082236d0f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanz_spec_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 22.08.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_VANZ_SPEC.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzagent_baga_dinamic_cols</obj_name>
  <obj_hashval>0a716631e5131708b583a1ed40b70e49</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzagent_baga_dinamic_cols()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  S  varchar;
  L1 NUMERIC;
  L2 NUMERIC;
  K  NUMERIC := 0;
BEGIN
  --Florin 22.08.2020
  DELETE FROM tmp_dinamic_cols;

  FOR i IN current_setting('pkg_list_base_vanzagent.vAnIni', TRUE)::NUMERIC..current_setting('pkg_list_base_vanzagent.vAnFin', TRUE)::NUMERIC LOOP
    IF i = current_setting('pkg_list_base_vanzagent.vAnIni', TRUE)::NUMERIC
    THEN L1 := current_setting('pkg_list_base_vanzagent.vLunaIni', TRUE)::NUMERIC;
    ELSE L1 := 1;
    END IF;

    IF i = current_setting('pkg_list_base_vanzagent.vAnFin', TRUE)::NUMERIC
    THEN L2 := current_setting('pkg_list_base_vanzagent.vLunaFin', TRUE)::NUMERIC;
    ELSE L2 := 12;
    END IF;

    FOR j IN L1..L2 LOOP
      S := to_char(j,'fm00')||'.'||to_char(i,'fm0000');
      K := K + 1;
      INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('VV'||To_Char(k,'fm999'), 'Val.Vanzari'          ||S, k);
      INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('VI'||To_Char(k,'fm999'), 'Val.Incasari'         ||S, k);
      INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('XV'||To_Char(k,'fm999'), 'Val.Vanz.(TVA excl.)' ||S, k);
      INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('NV'||To_Char(k,'fm999'), 'Val.Vanz.(disc.incl.)'||S, k);
    END LOOP;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzagent_completeazas</obj_name>
  <obj_hashval>8ce7887c37802dccf51b6be7f70b3bee</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzagent_completeazas(vanluna numeric, vlabel character varying, ptip character varying, k numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  S varchar;
  vCamp varchar;
BEGIN
  --Florin 24.08.2020
  IF pTIP = 'SELECT' THEN
    IF vAnLuna = 0 THEN
      vCamp := 'SUM(T.' || coalesce(SubStr(vLabel, 3),'') || ') ';
    ELSE
      vCamp := 'SUM(CASE WHEN T.AL = ' || coalesce(vAnLuna, 0) || ' THEN T.' || coalesce(vLabel,'') || ' ELSE 0 END) ';
    END IF;
  END IF;
  S := coalesce(S,'') || ',
      ' || coalesce(vCamp,'') || coalesce(vLabel,'');
  IF vAnLuna &lt;&gt; 0 THEN
    S := coalesce(S,'') || coalesce((k)::varchar,'');
  END IF;
  RETURN S;
 END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzagent_setparams</obj_name>
  <obj_hashval>dc9def0b6e343c92b3fb6f9d047960e5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzagent_setparams(plunaini numeric, panini numeric, plunafin numeric, panfin numeric, pallclient numeric, pallagent numeric, pcodjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vDataIni   date;
  vDataFin   date;
  vAnLunaIni NUMERIC := pAnIni * 12 + pLunaIni;
  vAnLunaFin NUMERIC := pAnFin * 12 + pLunaFin;
  vAnIni     NUMERIC := 0;
  vLunaIni   NUMERIC := 0;
  vAnFin     NUMERIC := 0;
  vLunaFin   NUMERIC := 0;
BEGIN
  --Adina 16.12.2020 tichet 41643
  --Florin 22.08.2020
  PERFORM set_config('PKG_LIST_BASE_VANZAGENT.vAnLunaIni', vAnLunaIni::varchar, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZAGENT.vAnLunaFin', vAnLunaFin::varchar, FALSE);

  IF pCodJob1 &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(pCodJob1, vDataIni, vDataFin, vAnLunaIni, vAnLunaFin);
  END IF;

  SELECT
    FNC_ExtractAnLuna.pan,
    FNC_ExtractAnLuna.pluna
  INTO
    vAnIni,
    vLunaIni
  FROM FNC_ExtractAnLuna(vAnLunaIni);

  SELECT
    FNC_ExtractAnLuna.pan,
    FNC_ExtractAnLuna.pluna
  INTO
    vAnFin,
    vLunaFin
  FROM FNC_ExtractAnLuna(vAnLunaFin);

  PERFORM set_config('PKG_LIST_BASE_VANZAGENT.vAnIni'    , vAnIni   ::varchar, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZAGENT.vLunaIni'  , vLunaIni ::varchar, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZAGENT.vAnFin'    , vAnFin   ::varchar, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZAGENT.vLunaFin'  , vLunaFin ::varchar, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZAGENT.vAllClient', (COALESCE(pAllClient, 0) = 1)::varchar, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZAGENT.vAllAgent' , (COALESCE(pAllAgent, 0) = 1) ::varchar, FALSE);
  PERFORM pkg_list_base_vanzagent_baga_dinamic_cols();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzagentart_baga_dinamic_cols</obj_name>
  <obj_hashval>2d548fba02caff8f3b7c302889d31e11</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzagentart_baga_dinamic_cols()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  S  varchar;
  L1 NUMERIC;
  L2 NUMERIC;
  K  NUMERIC := 0;
BEGIN
  --Florin 28.08.2020
  DELETE FROM tmp_dinamic_cols;

  FOR i IN current_setting('pkg_list_base_vanzagentart.vAnIni', TRUE)::NUMERIC..current_setting('pkg_list_base_vanzagentart.vAnFin', TRUE)::NUMERIC LOOP
    IF i = current_setting('pkg_list_base_vanzagentart.vAnIni', TRUE)::NUMERIC
    THEN L1 := current_setting('pkg_list_base_vanzagentart.vLunaIni', TRUE)::NUMERIC;
    ELSE L1 := 1;
    END IF;

    IF i = current_setting('pkg_list_base_vanzagentart.vAnFin', TRUE)::NUMERIC
    THEN L2 := current_setting('pkg_list_base_vanzagentart.vLunaFin', TRUE)::NUMERIC;
    ELSE L2 := 12;
    END IF;

    FOR j IN L1..L2 LOOP
      S := to_char(j,'fm00')||'.'||to_char(i,'fm0000');
      K := K + 1;
      INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('VV'||To_Char(k,'fm999'), 'Val.Vanzari'          ||S, k);
      INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('VI'||To_Char(k,'fm999'), 'Val.Incasari'         ||S, k);
      INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('XV'||To_Char(k,'fm999'), 'Val.Vanz.(TVA excl.)' ||S, k);
      INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('NV'||To_Char(k,'fm999'), 'Val.Vanz.(disc.incl.)'||S, k);
      INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('VA'||To_Char(k,'fm999'), 'Val.Adaos'            ||S, k);
    END LOOP;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzagentart_campuri</obj_name>
  <obj_hashval>90dd67881b71285b5ec2ba70bfe4c253</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzagentart_campuri(ptip character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  S        VARCHAR;
  K        NUMERIC := 0;
  vAnIni   NUMERIC := current_setting('pkg_list_base_vanzagentart.vAnIni'  , TRUE)::NUMERIC;
  vLunaIni NUMERIC := current_setting('pkg_list_base_vanzagentart.vLunaIni', TRUE)::NUMERIC;
  vAnFin   NUMERIC := current_setting('pkg_list_base_vanzagentart.vAnFin'  , TRUE)::NUMERIC;
  vLunaFin NUMERIC := current_setting('pkg_list_base_vanzagentart.vLunaFin', TRUE)::NUMERIC;
BEGIN
  --Adina 16.12.2020 tichet 41674 - add vAnIni,vLunaIni,vAnFin,vLunaFin si modificat cond.in FOR
  --Florin 24.08.2020
  S:= COALESCE(S, '') || PKG_LIST_BASE_VANZAGENTART_CompleteazaS(0,'T_VV', ptip, k);
  S:= COALESCE(S, '') || PKG_LIST_BASE_VANZAGENTART_CompleteazaS(0,'T_VI', ptip, k);
  S:= COALESCE(S, '') || PKG_LIST_BASE_VANZAGENTART_CompleteazaS(0,'T_XV', ptip, k);
  S:= COALESCE(S, '') || PKG_LIST_BASE_VANZAGENTART_CompleteazaS(0,'T_NV', ptip, k);
  S:= COALESCE(S, '') || PKG_LIST_BASE_VANZAGENTART_CompleteazaS(0,'T_VA', ptip, k);
  FOR i IN vAnIni*12+vLunaIni..vAnFin*12+vLunaFin  --current_setting('pkg_list_base_vanzagentart.vAnIni', TRUE)::NUMERIC..current_setting('pkg_list_base_vanzagentart.vAnFin', TRUE)::NUMERIC
  LOOP
    K := K + 1;
    S:= COALESCE(S, '') || PKG_LIST_BASE_VANZAGENTART_CompleteazaS(i,'VV', ptip, k);
    S:= COALESCE(S, '') || PKG_LIST_BASE_VANZAGENTART_CompleteazaS(i,'VI', ptip, k);
    S:= COALESCE(S, '') || PKG_LIST_BASE_VANZAGENTART_CompleteazaS(i,'XV', ptip, k);
    S:= COALESCE(S, '') || PKG_LIST_BASE_VANZAGENTART_CompleteazaS(i,'NV', ptip, k);
    S:= COALESCE(S, '') || PKG_LIST_BASE_VANZAGENTART_CompleteazaS(i,'VA', ptip, k);
  END LOOP;
  RETURN S;
 END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzagentart_completeazas</obj_name>
  <obj_hashval>ea8db092a6782fc3cc529d62ec431f72</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzagentart_completeazas(vanluna numeric, vlabel character varying, ptip character varying, k numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  S      VARCHAR;
  vCamp  VARCHAR;
BEGIN
  --Florin 22.08.2020
  IF pTIP = 'SELECT' THEN
    IF vAnLuna = 0 THEN
      vCamp := 'SUM(T.' || coalesce(SubStr(vLabel, 3),'') || ') ';
    ELSE
      vCamp := 'SUM(CASE WHEN T.AL = ' || coalesce(vAnLuna,0) || ' THEN T.' || coalesce(vLabel,'') || ' ELSE 0 END) ';
    END IF;
  END IF;

  S := coalesce(S,'') || ',
      ' || coalesce(vCamp,'') || coalesce(vLabel,'');

  IF vAnLuna &lt;&gt; 0 THEN
    S := coalesce(S,'') || coalesce((k)::varchar,'');
  END IF;

  RETURN S;
 END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzagentart_setparams</obj_name>
  <obj_hashval>76d1473096d168289c260133a190bf20</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzagentart_setparams(plunaini numeric, panini numeric, plunafin numeric, panfin numeric, pallclient numeric, pallagent numeric, pcodjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aTipInterval NUMERIC := 0;
  vAnMaxim     NUMERIC := 0;
  vLunaMaxima  NUMERIC := 0;
begin
  --Adina 16.12.2020 : COALESCE(pCODJOB1,0), COALESCE(pAllClient, 1), COALESCE(pAllAgent, 1)
  IF COALESCE(pCODJOB1,0) &gt; 0 THEN
    aTipInterval := 1;
  END IF;

  IF ATIPINTERVAL = 0 THEN
    PERFORM set_config('PKG_LIST_BASE_VANZAGENTART.vLunaIni', pLunaIni::varchar, FALSE);
    PERFORM set_config('PKG_LIST_BASE_VANZAGENTART.vAnIni'  , pAnIni  ::varchar, FALSE);
    PERFORM set_config('PKG_LIST_BASE_VANZAGENTART.vLunaFin', pLunaFin::varchar, FALSE);
    PERFORM set_config('PKG_LIST_BASE_VANZAGENTART.vAnFin'  , pAnFin  ::varchar, FALSE);
  ELSE
    SELECT AnMaxim, LunaMaxima
    INTO vAnMaxim, vLunaMaxima FROM FIRMALUNI;
    PERFORM set_config('PKG_LIST_BASE_VANZAGENTART.vAnIni'  , vAnMaxim   ::varchar, FALSE);
    PERFORM set_config('PKG_LIST_BASE_VANZAGENTART.vLunaIni', vLunaMaxima::varchar, FALSE);
    PERFORM set_config('PKG_LIST_BASE_VANZAGENTART.vAnFin'  , vAnMaxim   ::varchar, FALSE);
    PERFORM set_config('PKG_LIST_BASE_VANZAGENTART.vLunaFin', vLunaMaxima::varchar, FALSE);
  END IF;

  PERFORM set_config('PKG_LIST_BASE_VANZAGENTART.vAllClient', (COALESCE(pAllClient, 1) = 1)::varchar, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZAGENTART.vAllAgent' , (COALESCE(pAllAgent, 1) = 1) ::varchar, FALSE);
  PERFORM pkg_list_base_vanzagentart_baga_dinamic_cols();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzari_processlist</obj_name>
  <obj_hashval>a02908920ecafedebf47a5b9680b8df9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzari_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  S               varchar := '';
  gSuplCols        VARCHAR := 'RESTCMD C,RESTNP NP,EMULARE E,RESTNP1 NP1,NARTOBJ O,NUM1 U1,OSPATARI OS,NPERS PE,SALI S,MESE M,NPART P';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Florin 23.11.2023 - sinc. Oracle
  --Florin 25.05.2022 - fixat 54409
  --Adina 16.10.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_VANZARI.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  S :=
    'INSERT INTO ' || coalesce(TMPNAME,'') || '(SALA, MASA, OSPATAR, NRCOMANDA, DESCHIDERE, INCHIDERE, NRNOTAPLATA, DENART, DENUM, CANT, PRET, DISCOUNT, VALARTICOL, PRELPEMONETAR' || gUserFields || ') ' || CHR(13) ||
    'SELECT '                                                                           || CHR(13) ||
    '  S.DENUMIRE AS SALA, '                                                             || CHR(13) ||
    '  CASE '                                                                           || CHR(13) ||
    '    WHEN M.TEXTAFISARE IS NOT NULL THEN M.TEXTAFISARE '                             || CHR(13) ||
    '    ELSE TO_CHAR(M.INDEXLOCAL) '                                                   || CHR(13) ||
    '  END AS MASA, '                                                                   || CHR(13) ||
    '  PE.NUME || '' '' ||  PE.PRENUME AS OSPATAR, '                                     || CHR(13) ||
    '  C.NRCOMANDA, '                                                                     || CHR(13) ||
    '  TO_CHAR(C.DESCHIDERE, ''DD.MM.YYYY:HH24:MI'') AS DESCHIDERE, '                   || CHR(13) ||
    '  TO_CHAR(C.INCHIDERE,  ''DD.MM.YYYY:HH24:MI'') AS INCHIDERE,  '                   || CHR(13) ||
    '  NP.NRDOC AS NRNOTAPLATA,'                                                         || CHR(13) ||
    '  O.DENUMIRE AS DENART,'                                                           || CHR(13) ||
    '  U1.DEN_UM1 AS DENUM,'                                                             || CHR(13) ||
    '  NP1.CANT,'                                                                       || CHR(13) ||
    '  NP1.PRET,'                                                                       || CHR(13) ||
    '  NP1.DISCOUNT,'                                                                   || CHR(13) ||
    '  NP1.CANT * NP1.PRET * (100 + coalesce(NP1.DISCOUNT, 0)) / 100 AS VALARTICOL,'     || CHR(13) ||
    '  (case when coalesce(E.PRELUAT, 0)= 0 then ''NU'' else ''DA'' end)' || gUserAlias || CHR(13) ||
    'FROM '                                                                             || CHR(13) ||
    '  RESTCMD C'                                                                       || CHR(13) ||
    '  INNER JOIN RESTNP NP   ON NP.CODRESTCMD  = C.CODRESTCMD'   || CHR(13) ||
    '  INNER JOIN RESTNP1 NP1 ON NP1.CODRESTNP  = NP.CODRESTNP'    || CHR(13) ||
    '  INNER JOIN NARTOBJ O   ON O.CODOBIECT    = NP1.CODOBIECT'   || CHR(13) ||
    '  INNER JOIN NUM1 U1     ON U1.CODUM1      = NP1.UMSEC'       || CHR(13) ||
    '  INNER JOIN MESE M      ON M.CODMASA      = C.CODMASA'       || CHR(13) ||
    '  INNER JOIN SALI S      ON S.CODSALA      = M.CODSALA'       || CHR(13) ||
    '  LEFT  JOIN OSPATARI OS ON OS.COD         = C.CODOSPATAR'   || CHR(13) ||
    '  LEFT  JOIN NPERS PE    ON PE.CODPERS     = OS.CODPERS'     || CHR(13) ||
    '  LEFT  JOIN EMULARE E   ON E.CODRESTNP    = NP.CODRESTNP'   || CHR(13) ||
    '  LEFT  JOIN NPART P     ON P.CODPART      = NP.CODPART'     || CHR(13) || gSuplJoins || CHR(13) ||
    'WHERE '                                                       || CHR(13) ||
    '  coalesce(C.INCHISA, 0)    = 1'                             || CHR(13) ||
    '  AND C.DESCHIDERE     &gt;= to_timestamp(''' || coalesce(current_setting('PKG_LIST_BASE_VANZARI.DATASTART', true),'') || ''', ''DD.MM.YYYY:HH24:MI:SS'')' || CHR(13) ||
    '  AND C.INCHIDERE      &lt;= to_timestamp(''' || coalesce(current_setting('PKG_LIST_BASE_VANZARI.DATAEND', true),'') || ''', ''DD.MM.YYYY:HH24:MI:SS'')'   || CHR(13) ||
    '  AND S.CODRESTAURANT = ' || coalesce((COALESCE(current_setting('PKG_LIST_BASE_VANZARI.CODRESTAURANT', true)::numeric, 0))::varchar,'');

  PERFORM LIST_EXECUTE_IMMEDIATE(s, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzari_setparams</obj_name>
  <obj_hashval>4f9621eec57faaa904d7e5471c37fe37</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzari_setparams(acodrestaurant numeric, adatastart character varying, adataend character varying, aid numeric, aver numeric, pcodjob1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
BEGIN
  --Adina 16.10.2020
  perform set_config('PKG_LIST_BASE_VANZARI.DATASTART',(aDATASTART)::varchar,false);
  perform set_config('PKG_LIST_BASE_VANZARI.DATAEND'  ,(aDATAEND)::varchar  ,false);

  IF  pCodJob1 &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(pCodJob1, current_setting('PKG_LIST_BASE_VANZARI.DATASTART', true), current_setting('PKG_LIST_BASE_VANZARI.DATAEND', true), xLunaAnIni, xLunaAnFin);
  END IF;

  perform set_config('PKG_LIST_BASE_VANZARI.CODRESTAURANT',(aCODRESTAURANT)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzari_sint_processlist</obj_name>
  <obj_hashval>0a28a02ba3296f0514c197c83a0eebfa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzari_sint_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  s             varchar := '';
  CODRESTAURANT  varchar := current_setting('PKG_LIST_BASE_VANZARI_SINT.CODRESTAURANT',TRUE);
  DATASTART      varchar := current_setting('PKG_LIST_BASE_VANZARI_SINT.DATASTART'    ,TRUE);
  DATAEND        varchar := current_setting('PKG_LIST_BASE_VANZARI_SINT.DATAEND'      ,TRUE);
BEGIN
  --Florin 26.05.2022 - fixat 54409
  --Adina 19.10.2020
  S := 'INSERT INTO ' || TMPNAME || '(OSPATAR, VANZARI, DISCOUNT, DISCFACT, PROTOCOL, FACTURARE,
          PLATA0,
          PLATA1,
          PLATA2,
          PLATA3,
          PLATA4,
          PLATA5,
          PLATA6,
          ALTMODPLATA
       ) ' || CHR(13) ||
       'SELECT '                                     ||  CHR(13) ||
       '  P.NUME || '' '' || P.PRENUME AS OSPATAR,'  ||  CHR(13) ||
       '  VANZARI,'                                  ||  CHR(13) ||
       '  ABS(DISCOUNT) AS DISCOUNT,'                ||  CHR(13) ||
       '  ABS(DISCFACT) AS DISCFACT,'                ||  CHR(13) ||
       '  PROTOCOL,'                                 ||  CHR(13) ||
       '  FACTURARE,'                                ||  CHR(13) ||
       '  PLATA0,'                                   ||  CHR(13) ||
       '  PLATA1,'                                   ||  CHR(13) ||
       '  PLATA2,'                                   ||  CHR(13) ||
       '  PLATA3,'                                   ||  CHR(13) ||
       '  PLATA4,'                                   ||  CHR(13) ||
       '  PLATA5,'                                   ||  CHR(13) ||
       '  PLATA6,'                                   ||  CHR(13) ||
       '  ALTMODPLATA'                               ||  CHR(13) ||
       'FROM'                                        ||  CHR(13) ||
       '('                                           ||  CHR(13) ||
       '   SELECT'                                   ||  CHR(13) ||
       '    CODOSPATAR,'                             ||  CHR(13) ||
       '    SUM(VALARTICOL) AS VANZARI,'             ||  CHR(13) ||
       '    SUM(DISCOUNT)   AS DISCOUNT,'            ||  CHR(13) ||
       '    SUM(DISCFACT)   AS DISCFACT,'            ||  CHR(13) ||
       '    SUM(PROTOCOL)   AS PROTOCOL,'            ||  CHR(13) ||
       '    SUM(FACTURARE)  AS FACTURARE'            ||  CHR(13) ||
       '   FROM'                                     ||  CHR(13) ||
       '   ( '                                       ||  CHR(13) ||
       '   SELECT '                                  ||  CHR(13) ||
       '     C.CODOSPATAR,'                          ||  CHR(13) ||
       '     NP1.CANT * NP1.PRET AS VALARTICOL,'     ||  CHR(13) ||
       '     CASE '                                  ||  CHR(13) ||
       '       WHEN coalesce(NP.FACTURARE, 0) = 0 THEN NP1.CANT * NP1.PRET * (coalesce(DISCOUNT, 0)) / 100 ' ||
       '       ELSE 0 '||
       '     END  AS DISCOUNT,' ||
       '     CASE '                                   ||  CHR(13) ||
       '       WHEN coalesce(NP.FACTURARE, 0) = 1 THEN NP1.CANT * NP1.PRET * (coalesce(DISCOUNT, 0)) / 100 ' ||
       '       ELSE 0 '||
       '     END  AS DISCFACT,' ||
       '     CASE'                                   ||  CHR(13) ||
       '       WHEN coalesce(NP.PROTOCOL, 0) = 1 THEN NP1.CANT * NP1.PRET' ||
       '       ELSE 0 '                              ||  CHR(13) ||
       '     END AS PROTOCOL,'                       ||  CHR(13) ||
       '     CASE'                                   ||  CHR(13) ||
       '       WHEN coalesce(NP.FACTURARE, 0) = 1 THEN NP1.CANT * NP1.PRET' ||
       '       ELSE 0 '                              ||  CHR(13) ||
       '     END AS FACTURARE'                       ||  CHR(13) ||
       '   FROM'                                     ||  CHR(13) ||
       '      RESTCMD C,'                            ||  CHR(13) ||
       '      RESTNP NP,'                            ||  CHR(13) ||
       '      RESTNP1 NP1,'                          ||  CHR(13) ||
       '      MESE M,'                               ||  CHR(13) ||
       '      SALI S'                                ||  CHR(13) ||
       '   WHERE '                                   ||  CHR(13) ||
       '      coalesce(C.INCHISA, 0)   = 1'          ||  CHR(13) ||
       '      AND C.DESCHIDERE     &gt;= TO_timestamp('''    || DATASTART || ''', ''DD.MM.YYYY:HH24:MI:SS'')'
                                                     ||  CHR(13) ||
       '      AND C.INCHIDERE      &lt;= TO_timestamp('''    || DATAEND  || ''', ''DD.MM.YYYY:HH24:MI:SS'')'
                                                     ||  CHR(13) ||
       '      AND NP.CODRESTCMD = C.CODRESTCMD '     ||  CHR(13) ||
       '      AND NP1.CODRESTNP = NP.CODRESTNP'      ||  CHR(13) ||
       '      AND M.CODMASA     = C.CODMASA'         ||  CHR(13) ||
       '      AND S.CODSALA     = M.CODSALA'         || CHR(13)  ||
       '     AND S.CODRESTAURANT = '                 || coalesce(CODRESTAURANT, '0')
                                                     ||  CHR(13) ||
       '   ) A_PG'                                   ||  CHR(13) ||
       '   GROUP BY CODOSPATAR'                      ||  CHR(13) ||
       ') VANZ'                                      ||  CHR(13) ||
       ' LEFT OUTER JOIN '                           ||  CHR(13) ||
       '( '                                          ||  CHR(13) ||
       '  SELECT '                                   ||  CHR(13) ||
       '    C.CODOSPATAR,'                           ||  CHR(13) ||
       '    SUM(case when coalesce(np2.tipplata,0) = 0 then NP2.VALOARE else 0 end) AS PLATA0, '||  CHR(13) ||
       '    SUM(case when np2.tipplata = 1 then NP2.VALOARE else 0 end) AS PLATA1, '            ||  CHR(13) ||
       '    SUM(case when np2.tipplata = 2 then NP2.VALOARE else 0 end) AS PLATA2, '            ||  CHR(13) ||
       '    SUM(case when np2.tipplata = 3 then NP2.VALOARE else 0 end) AS PLATA3, '            ||  CHR(13) ||
       '    SUM(case when np2.tipplata = 4 then NP2.VALOARE else 0 end) AS PLATA4, '            ||  CHR(13) ||
       '    SUM(case when np2.tipplata = 5 then NP2.VALOARE else 0 end) AS PLATA5, '            ||  CHR(13) ||
       '    SUM(case when np2.tipplata = 6 then NP2.VALOARE else 0 end) AS PLATA6, '            ||  CHR(13) ||
       '    SUM(case when np2.tipplata &gt; 6 then NP2.VALOARE else 0 end) AS ALTMODPLATA '        ||  CHR(13) ||
       '  FROM '                                     ||  CHR(13) ||
       '     RESTCMD C,'                             ||  CHR(13) ||
       '     RESTNP  NP,'                            ||  CHR(13) ||
       '     RESTNP2 NP2,'                           ||  CHR(13) ||
       '     MESE    M,'                             ||  CHR(13) ||
       '     SALI    S'                              ||  CHR(13) ||
       '  WHERE'                                     ||  CHR(13) ||
       '     coalesce(C.INCHISA, 0)   = 1 '          ||  CHR(13) ||
       '     AND C.DESCHIDERE     &gt;= TO_timestamp('''     || DATASTART|| ''', ''DD.MM.YYYY:HH24:MI:SS'')'  || CHR(13) ||
       '     AND C.INCHIDERE      &lt;= TO_timestamp('''     || DATAEND  || ''', ''DD.MM.YYYY:HH24:MI:SS'')'  || CHR(13) ||
       '     AND NP.CODRESTCMD = C.CODRESTCMD'       ||  CHR(13) ||
       '     AND NP2.CODRESTNP = NP.CODRESTNP'       ||  CHR(13) ||
       '     AND M.CODMASA     = C.CODMASA '         ||  CHR(13) ||
       '     AND S.CODSALA     = M.CODSALA'          ||  CHR(13) ||
       '     AND S.CODRESTAURANT = '                 || coalesce(CODRESTAURANT, '0') ||  CHR(13) ||
       '  GROUP BY C.CODOSPATAR '                    ||  CHR(13) ||
       ') ALTMP ON ALTMP.CODOSPATAR = VANZ.CODOSPATAR,'||  CHR(13) ||
       '  OSPATARI O, '                              ||  CHR(13) ||
       '  NPERS P '                                  ||  CHR(13) ||
       'WHERE '                                      ||  CHR(13) ||
       '  P.CODPERS = O.CODPERS'                     ||  CHR(13) ||
       '  AND VANZ.CODOSPATAR = O.COD';
  PERFORM LIST_EXECUTE_IMMEDIATE(s, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzaridiscount_processlist</obj_name>
  <obj_hashval>3cf87947805f6b8bc4ddda3bad01ae36</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzaridiscount_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert   varchar := '';
  sDiscOff   varchar := '';
BEGIN
  --Adina 10 septembrie 2020
  PERFORM PKG_GLOBALS_SetSeparator(',');

  WITH x AS
    (SELECT fnc_GetValConstanta('ArtDiscAcVol', getANLUCRU(), getLUNALUCRU()) COD
    union ALL
     SELECT fnc_GetValConstanta('ArtDiscAcCant', getANLUCRU(), getLUNALUCRU()) COD
    union ALL
     SELECT fnc_GetValConstanta('ArtPenAc', getANLUCRU(), getLUNALUCRU()) COD
    )
  SELECT string_agg(cod,',') || coalesce(fnc_GetValConstanta('ArtDiscAcTer', getANLUCRU(), getLUNALUCRU()),'') INTO sDiscOff
  FROM x
  WHERE COALESCE(x.cod::numeric, 0) &gt; 0;

  IF sDiscOff IS NOT NULL THEN
    sDiscOff := 'SUM (CASE WHEN IES1.CODOBIECT IN (' || sDiscOff || ') THEN coalesce(L1.CANT,IES1.CANT) * IES1.PU ELSE 0 END)';
  ELSE
    sDiscOff := 0::varchar;
  END IF;

  sInsert := 'INSERT INTO ' || TMPNAME || ' (MEASURE, EXPLICATIE, ANLUNA, VALORI, NIVEL)
  WITH
    A AS (
      SELECT
        SUM( (case when IES1.TIPLINIE = ''='' then IES1.PU * L1.CANT else 0 end) ) VALFARADISC,
        SUM( (case when IES1.TIPLINIE = ''='' then IES1.PU * L1.CANT else 0 end) ) - SUM((case when IES1.TIPLINIE =''='' then IES1.PU * L1.CANT * IES1.COEFDISCMAJ else 0 end)) DISCINVOICE,
        SUM( (case when IES1.TIPLINIE = ''='' then (NS.PRET - NS.ADAOS)*L1.CANT else 0 end)) COSTDESC ,
        ' || sDiscOff || ' DISCOFFINVOICE,
        IES.AN,IES.LUNA
      FROM IESIRI1 IES1
        INNER JOIN IESIRI IES ON IES1.CODIES   = IES.CODIES
        LEFT  JOIN LIVR1   L1 ON L1.CODIES1    = IES1.CODIES1
        LEFT  JOIN NIRSTOC NS ON NS.CODNIRSTOC = L1.CODNIRSTOC
      WHERE IES.TIPDOC IN (19,21,22, 20) AND IES.ANULAT &lt;&gt; 1 AND IES.OPERAT = 1
        AND IES.AN = GetANLUCRU() AND IES.LUNA = GetLUNALUCRU() ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('IES',NULL,NULL,NULL),'') || '
      GROUP BY IES.AN,IES.LUNA),
    T AS (SELECT 1 NIVEL union SELECT 2 NIVEL union SELECT 3 NIVEL union SELECT 4 NIVEL)
  SELECT
    (case T.NIVEL when 1 then ''M1_GSV001'' when 2 then ''M1_OG00ON'' when 3 then ''M1_OG00OF'' when 4 then ''M2_BIPC0R'' end) MEASURE,
    (case T.NIVEL when 1 then ''pret*cantitate fara discount'' when 2 then ''discountul on invoice total'' when 3 then ''discountul off invoice total'' when 4 then ''cost descarcare'' end) EXPLICATIE,
    A.AN::varchar||TO_CHAR(A.LUNA,''00'') ANLUNA,
    (case T.NIVEL when 1 then A.VALFARADISC when 2 then - A.DISCINVOICE when 3 then A.DISCOFFINVOICE when 4 then A.COSTDESC end) VALORI,
    T.NIVEL
  FROM A CROSS JOIN T ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzclaseart_processlist</obj_name>
  <obj_hashval>3830d28e41fbccb3579c9d136e0ea15f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzclaseart_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert      varchar;
  vPerioada    varchar := CURRENT_SETTING('PKG_LIST_SELCLASEART.vPerioada', TRUE);
  vToateClaseA BOOLEAN := fnc_current_setting_boolint('PKG_LIST_SELCLASEART.vToateClaseA');
  vTotiPart    BOOLEAN := fnc_current_setting_boolint('PKG_LIST_SELCLASEART.vTotiPart');
  vWhereIG     varchar;
BEGIN
  --Florin 10.09.2020
  IF NOT vTotiPart THEN
    vWhereIG := coalesce(vWhereIG,'') || '
            AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODPART'' AND VALOARE = I.PARTENER::varchar) ';
  END IF;

  IF NOT vToateClaseA THEN
    vWhereIG := coalesce(vWhereIG,'') || '
            AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODCLASEA'' AND VALOARE = COALESCE(NA.CLASA,0)::varchar) ';
  END IF;

  sInsert := 'INSERT INTO ' || tmpName || '(ClasaA, DenClasaA, Client, CodExtCli, LocCli, JudCli, ZonaCli, Val, ValTVA, Adaos, NrDoc )
        WITH IESGRUP AS (
          SELECT
            NA.CLASA, COALESCE(I.PARTENER,0) PARTENER,
            SUM(I1.PRETORIG * I1.CANT * COALESCE(I1.COEFDISCMAJ,1)*(CASE WHEN I.MONEDA = 0 THEN 1 ELSE COALESCE(I.CURS,1) END)) VALLEI ,
            SUM((CASE WHEN I1.PU = 0 THEN 0 ELSE I1.TVA*I1.PRETORIG/I1.PU END) * COALESCE(I1.COEFDISCMAJ,1)*(CASE WHEN I.MONEDA = 0 THEN 1 ELSE COALESCE(I.CURS,1) END)) TVALEI,
            SUM(I1.CANT * I1.PRETORIG * COALESCE(I1.ADDIM/100,0)) ADAOS,
            COUNT(DISTINCT I.CODIES) NRDEDOC
          FROM IESIRI I
            INNER JOIN IESIRI1 I1  ON I1.CODIES     = I.CODIES
            INNER JOIN NARTOBJ NAO ON NAO.CODOBIECT = I1.CODOBIECT
            INNER JOIN NART    NA  ON NA.CODARTICOL = NAO.CODARTICOL
            INNER JOIN NUM1        ON NUM1.CODUM1   = I1.UMSEC
          WHERE I.DATADOC  BETWEEN ' || coalesce(vPerioada,'') || '
            AND I1.TIPLINIE IN (''='',''S'') ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || coalesce(vWhereIG,'') || '
            AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''TIPDOC'' AND VALOARE = I.TIPDOC::VARCHAR)
          GROUP BY NA.CLASA, COALESCE(I.PARTENER,0)
        )
        SELECT NCA.SIMBOL, NCA.DEN_CLASEA, NP.DEN_PART, NP.CODEXTERN, L.DEN_LOCALIT, J.DEN_JUDET, Z.DEN_ZONA, IG.VALLEI, IG.TVALEI, IG.ADAOS, IG.NRDEDOC
        FROM IESGRUP IG
          INNER JOIN NCLASEA  NCA ON NCA.CODCLASEA = COALESCE(IG.CLASA,0)
          LEFT  JOIN NPART    NP  ON NP.CODPART    = IG.PARTENER
          LEFT  JOIN NAGENDA  A   ON A.CODPART     = IG.PARTENER AND A.SEDIUSOCIAL BETWEEN 4 AND 7 AND COALESCE(A.INACTIV, 0) = 0
          LEFT  JOIN NLOCALIT L   ON L.CODLOCALIT  = A.CODLOCALIT
          LEFT  JOIN NJUDET   J   ON J.CODJUDET    = L.CODJUDET
          LEFT  JOIN NZONE    Z   ON Z.CODZONA     = L.CODZONA';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzper_adaugacamp</obj_name>
  <obj_hashval>dbe56c5f9563e5efb832784cb2a4d231</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzper_adaugacamp(INOUT s character varying, INOUT k numeric, INOUT vcamp character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vLabel      varchar := '';
  vCantitativ boolean := current_setting('PKG_LIST_BASE_VANZPER.vCantitativ', true)::boolean;
  vValoric    boolean := current_setting('PKG_LIST_BASE_VANZPER.vValoric'   , true)::boolean;
  vInclTVA    boolean := current_setting('PKG_LIST_BASE_VANZPER.vInclTVA'   , true)::boolean;
  vInclUnit   boolean := current_setting('PKG_LIST_BASE_VANZPER.vInclUnit'  , true)::boolean;
  vTipPer     NUMERIC := current_setting('PKG_LIST_BASE_VANZPER.vTipPer'    , TRUE)::NUMERIC;
BEGIN
  --Florin 03.05.2023 - sinc. Oracle
  --Florin 21.04.2023 - sinc. Oracle/fixat
  --Florin 23.03.2023 - sinc. Oracle
  --Adina 21.10.2020 - scos incrementarea lui k si am pus-o in Campuri()
  --k := k + 1;
  IF vCantitativ THEN
    vLabel := 'C' || coalesce(To_Char(k, 'fm999'),'');
    S := coalesce(S,'') || ', ' || coalesce(REPLACE(vCamp, 'XAux', 'CAux'),'') || coalesce(vLabel,'');
  END IF;

  IF vValoric THEN
    vLabel := 'V' || coalesce(To_Char(k, 'fm999'),'');
    S := coalesce(S,'') || ', ' || coalesce(REPLACE(vCamp, 'XAux', 'VAux'),'') || coalesce(vLabel,'');
  END IF;

  IF vInclTVA THEN
    vLabel := 'VT' || coalesce(To_Char(k, 'fm999'),'');
    S := coalesce(S,'') || ', ' || coalesce(REPLACE(vCamp, 'XAux', 'VTAux'),'') || coalesce(vLabel,'');
  END IF;

  IF vInclUnit THEN
    vLabel := 'VU' || coalesce(To_Char(k, 'fm999'),'');
    S := coalesce(S,'') || ', ' || coalesce(REPLACE(vCamp, 'XAux', 'VUAux'),'') || coalesce(vLabel,'');
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzper_baga_job_dinamic_cols</obj_name>
  <obj_hashval>3f33494184c7922137efb048aa14d107</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzper_baga_job_dinamic_cols(stablename character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sTableKind varchar;
BEGIN
  --Florin 20.08.2020
  --Adina 20.10.2020
  BEGIN
    --SELECT TEMPORARY INTO sTableKinD FROM user_tables WHERE upper(table_name) = upper(sTableName);
    SELECT DISTINCT CASE WHEN table_type LIKE '%TEMPORARY%' THEN 'Y' ELSE 'N' END
    INTO sTableKinD
    FROM information_schema.TABLES
    WHERE table_name = lower(sTableName);
  EXCEPTION WHEN others THEN
    RETURN;
  END;

  IF  sTableKind = 'N' THEN
    INSERT INTO JOB_DINAMIC_COLS(tableName, FIELDNAME, DISPLAY, INDEXLOCAL)
    SELECT sTableName, FIELDNAME, DISPLAY, INDEXLOCAL
    FROM TMP_DINAMIC_COLS;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzper_campuri</obj_name>
  <obj_hashval>704a880b69410a2a92b3f3da51b7d465</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzper_campuri(ptip character varying, palias character varying DEFAULT NULL::character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  S           varchar;
  I           NUMERIC;
  J           NUMERIC;
  K           NUMERIC;
  vCamp       varchar;
  dAux         date;
   vCantitativ  boolean := current_setting('PKG_LIST_BASE_VANZPER.vCantitativ', true)::boolean;
   vCantCutii  boolean := current_setting('PKG_LIST_BASE_VANZPER.vCantCutii' , true)::boolean;
   vCantPaleti  boolean := current_setting('PKG_LIST_BASE_VANZPER.vCantPaleti', true)::boolean;
   vValoric    boolean := current_setting('PKG_LIST_BASE_VANZPER.vValoric'   , true)::boolean;
   vInclTVA    boolean := current_setting('PKG_LIST_BASE_VANZPER.vInclTVA'   , true)::boolean;
   vInclUnit    boolean := current_setting('PKG_LIST_BASE_VANZPER.vInclUnit'  , true)::boolean;
   vVariatie    boolean := current_setting('PKG_LIST_BASE_VANZPER.vVariatie'  , true)::boolean;
   vTipPer      NUMERIC := current_setting('PKG_LIST_BASE_VANZPER.vTipPer'    , true)::NUMERIC;
   vDataIni    varchar := current_setting('PKG_LIST_BASE_VANZPER.vDataIni'   , true);
   vDataFin    varchar := current_setting('PKG_LIST_BASE_VANZPER.vDataFin'   , true);
   vInceput    varchar := current_setting('PKG_LIST_BASE_VANZPER.vInceput'   , TRUE);
   vSfarsit    varchar := current_setting('PKG_LIST_BASE_VANZPER.vSfarsit'   , TRUE);
BEGIN
  --Florin 23.03.2023 - sinc. Oracle
  --Adina 16.12.2020 tichet 41674 - linia 72 am mai scazut o zi pt. a da aceeasi zi a saptamanii ca in Oracle
  --Florin 20.08.2020
  --Adina 21.10.2020 adaugat default null la palias; adaugat incrementarea lui k; modificat in Select .. from pkg_list_base_vanzper_ADAUGACAMP(S, K, vCAMP) in loc de Perform
  IF (pTIP = 'INSERT') AND (TRIM( pAlias) IS NOT NULL) THEN
    vCamp := coalesce(TRIM(pAlias),'') || '.';
  END IF;
  IF pTIP = 'SELECT' THEN
    IF vCantitativ THEN S := coalesce(S,'') || ', SUM(CAux) C0';   END IF;
    IF vValoric    THEN S := coalesce(S,'') || ', SUM(VAux) V0'; END IF;
    IF vInclTVA    THEN S := coalesce(S,'') || ', SUM(VTAux) VT0'; END IF;
    IF vInclUnit   THEN S := coalesce(S,'') || ', SUM(VUAux) VU0'; END IF;
    IF vTipPer = 1 THEN S := COALESCE(S, '')||', SUM(DAux) D0'; END IF;
  ELSE
    IF vCantitativ THEN S := coalesce(S,'') || ', ' || coalesce(vCamp,'') || 'C0';  END IF;
    IF vValoric    THEN S := coalesce(S,'') || ', ' || coalesce(vCamp,'') || 'V0';  END IF;
    IF vInclTVA    THEN S := coalesce(S,'') || ', ' || coalesce(vCamp,'') || 'VT0'; END IF;
    IF vInclUnit   THEN S := coalesce(S,'') || ', ' || coalesce(vCamp,'') || 'VU0'; END IF;
  END IF;

  k := 0;
  CASE vTipPer
    WHEN 1 THEN
      dAux := TO_DATE(vDataIni, 'dd.mm.yyyy');
      WHILE  dAux &lt;= TO_DATE(vDataFin, 'dd.mm.yyyy') LOOP
        IF pTIP = 'SELECT' THEN
          vCamp := 'SUM((CASE WHEN DATADOC = ''' || dAux || ''' THEN XAux ELSE 0 END)) ';
        END IF;
        k := k + 1;
        SELECT pkg_list_base_vanzper_ADAUGACAMP.S INTO s FROM pkg_list_base_vanzper_ADAUGACAMP(S, K, vCAMP);
        dAux := dAux + 1;
      END LOOP;
    WHEN 2 THEN
      j    := To_Char(date_trunc('YEAR', to_date(vDataIni, 'dd.mm.yyyy')),'D')::NUMERIC - 1 - 1;
      dAux := add_days(to_date(to_char(date_trunc('year', to_date(vDataIni, 'dd.mm.yyyy')), 'dd.mm.yyyy'), 'dd.mm.yyyy'), (-j)::integer);
      WHILE add_days(dAux, 7::integer) &lt;= to_date(vDataIni, 'dd.mm.yyyy') LOOP dAux := add_days(dAux, 7::integer); END LOOP;
        WHILE dAux &lt;= to_date(vDataFin, 'dd.mm.yyyy') LOOP
          IF pTIP = 'SELECT' THEN
            vCamp := 'SUM(CASE WHEN DATADOC BETWEEN '''|| dAux ||''' AND '''|| add_days(dAux,6::integer) ||''' THEN XAux ELSE 0 END) ';
          END IF;
          k := k + 1;
          SELECT pkg_list_base_vanzper_ADAUGACAMP.S INTO s FROM pkg_list_base_vanzper_ADAUGACAMP(S,K,vCAMP);
          dAux := add_days(dAux, 7::integer);
      END LOOP;
    WHEN 3 THEN
      dAux := DATE_TRUNC('MONTH',to_date(vDataIni, 'dd.mm.yyyy'));
      WHILE dAux &lt;= to_date(current_setting('PKG_LIST_BASE_VANZPER.vDataFin', true), 'dd.mm.yyyy') LOOP
        IF pTIP = 'SELECT' THEN
          vCamp := 'SUM(CASE WHEN LUNA = ' || coalesce(To_Char(dAux, 'mm'),'') || ' AND AN = ' || coalesce(To_Char(dAux, 'yyyy'),'') || ' THEN XAux ELSE 0 END) ';
        END IF;
        k := k + 1;
        SELECT pkg_list_base_vanzper_ADAUGACAMP.S INTO s FROM pkg_list_base_vanzper_ADAUGACAMP(S, K, vCAMP);
        dAux := ADD_MONTHS(dAux, 1);
      END LOOP;
    WHEN 4 THEN
      dAux := DATE_TRUNC('QUARTER',to_date(vDataIni, 'dd.mm.yyyy'));
      WHILE dAux &lt;= to_date(current_setting('PKG_LIST_BASE_VANZPER.vDataFin', true), 'dd.mm.yyyy') LOOP
        i := EXTRACT( MONTH FROM dAux);
        IF  pTIP = 'SELECT' THEN
          vCamp := 'SUM(CASE WHEN LUNA BETWEEN ' || coalesce(i,0) || ' AND ' || coalesce((  i + 2) ,0) || ' AND AN = ' || coalesce(To_Char(dAux, 'yyyy'),'') || ' THEN XAux ELSE 0 END) ';
        END IF;
        k := k + 1;
        SELECT pkg_list_base_vanzper_ADAUGACAMP.S INTO s FROM pkg_list_base_vanzper_ADAUGACAMP(S, K, vCAMP);
        dAux := ADD_MONTHS(dAux, 3);
      END LOOP;
    WHEN 5 THEN
      FOR i IN vInceput..vSfarsit LOOP
        IF pTIP = 'SELECT' THEN
          vCamp := 'SUM(CASE WHEN AN = '||i||' THEN XAux ELSE 0 END) ';
        END IF;
        k := k + 1;
        SELECT pkg_list_base_vanzper_ADAUGACAMP.S INTO s FROM pkg_list_base_vanzper_ADAUGACAMP(S,K,vCAMP);
      END LOOP;
  END CASE;
  RETURN S;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzper_fl_campuri</obj_name>
  <obj_hashval>42b7c538482dedb4b3508da971099eff</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzper_fl_campuri(ptip character varying, palias character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  S varchar;
  I NUMERIC;
  J NUMERIC;
  K NUMERIC;
  vCamp varchar;
  dAux date;
BEGIN
  --Florin 20.08.2020
  IF (pTIP = 'INSERT') AND (TRIM( pAlias) IS NOT NULL)
  THEN
    vCamp := coalesce(TRIM(pAlias),'') || '.';
  END IF;
  IF pTIP = 'SELECT'
  THEN
    IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vCantitativ')
    THEN
      S := coalesce(S,'') || ', SUM(CAux) C0';
    END IF;
    IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vValoric')
    THEN
      S := coalesce(S,'') || ', SUM(VAux) V0';
    END IF;
    IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vInclTVA')
    THEN
      S := coalesce(S,'') || ', SUM(VTAux) VT0';
    END IF;
    IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vInclUnit')
    THEN
      S := coalesce(S,'') || ', SUM(VUAux) VU0';
    END IF;
    ELSE
    IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vCantitativ')
    THEN
     S := coalesce(S,'') || ', ' || coalesce(vCamp,'') || 'C0';
    END IF;
    IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vValoric')
    THEN
      S := coalesce(S,'') || ', ' || coalesce(vCamp,'') || 'V0';
    END IF;
    IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vInclTVA')
    THEN
      S := coalesce(S,'') || ', ' || coalesce(vCamp,'') || 'VT0';
    END IF;
    IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vInclUnit')
    THEN
      S := coalesce(S,'') || ', ' || coalesce(vCamp,'') || 'VU0';
    END IF;
  END IF;
  k := 0;
  CASE current_setting('PKG_LIST_BASE_VANZPER.vTipPer', TRUE)::numeric
  WHEN 1
  THEN
    dAux := TO_DATE(current_setting('PKG_LIST_BASE_VANZPER.vDataIni', true), 'dd.mm.yyyy');
    WHILE  dAux &lt;= TO_DATE(current_setting('PKG_LIST_BASE_VANZPER.vDataFin', true), 'dd.mm.yyyy') LOOP
      IF pTIP = 'SELECT'
      THEN
        vCamp := 'SUM((CASE WHEN DATADOC = ''' || dAux || ''' THEN XAux ELSE 0 END)) ';
      END IF;
      PERFORM pkg_list_base_vanzper_ADAUGACAMP(S, K, vCAMP);
      dAux := dAux + 1;
    END LOOP;
  WHEN 2
  THEN
    j := To_Char(date_trunc('YEAR', to_date(current_setting('PKG_LIST_BASE_VANZPER.vDataIni', true), 'dd.mm.yyyy')),'D')::NUMERIC - 1;
     dAux := add_days(to_date(to_char(date_trunc('year', to_date(current_setting('PKG_LIST_BASE_VANZPER.vDataIni', true), 'dd.mm.yyyy')), 'dd.mm.yyyy'), 'dd.mm.yyyy'), (-j)::integer);
    WHILE add_days(dAux, 7::integer) &lt;= to_date(current_setting('PKG_LIST_BASE_VANZPER.vDataIni', true), 'dd.mm.yyyy') LOOP dAux := add_days(dAux, 7::integer); END LOOP;
      WHILE dAux &lt;= to_date(current_setting('PKG_LIST_BASE_VANZPER.vDataFin', true), 'dd.mm.yyyy') LOOP
        IF pTIP = 'SELECT' THEN
          vCamp := 'SUM(CASE WHEN DATADOC BETWEEN '''|| dAux ||''' AND '''|| add_days(dAux,6::integer) ||''' THEN XAux ELSE 0 END) ';
        END IF;
        PERFORM pkg_list_base_vanzper_ADAUGACAMP(S,K,vCAMP);
        dAux := add_days(dAux, 7::integer);
    END LOOP;
  WHEN 3
  THEN
    dAux := DATE_TRUNC('MONTH',to_date(current_setting('PKG_LIST_BASE_VANZPER.vDataIni', true), 'dd.mm.yyyy'));
    WHILE dAux &lt;= to_date(current_setting('PKG_LIST_BASE_VANZPER.vDataFin', true), 'dd.mm.yyyy') LOOP
    IF pTIP = 'SELECT'
    THEN
      vCamp := 'SUM(CASE WHEN LUNA = ' || coalesce(To_Char(dAux, 'mm'),'') || ' AND AN = ' || coalesce(To_Char(dAux, 'yyyy'),'') || ' THEN XAux ELSE 0 END) ';
    END IF;
    PERFORM pkg_list_base_vanzper_ADAUGACAMP(S, K, vCAMP);
    dAux := ADD_MONTHS(dAux, 1);
    END LOOP;
  WHEN 4
  THEN
    dAux := DATE_TRUNC('QUARTER',to_date(current_setting('PKG_LIST_BASE_VANZPER.vDataIni', true), 'dd.mm.yyyy'));
    WHILE dAux &lt;= to_date(current_setting('PKG_LIST_BASE_VANZPER.vDataFin', true), 'dd.mm.yyyy') LOOP
    i := EXTRACT( MONTH FROM dAux);
    IF  pTIP = 'SELECT'
    THEN
      vCamp := 'SUM(CASE WHEN LUNA BETWEEN ' || coalesce(i,0) || ' AND ' || coalesce((  i + 2) ,0) || ' AND AN = ' || coalesce(To_Char(dAux, 'yyyy'),'') || ' THEN XAux ELSE 0 END) ';
    END IF;
      PERFORM pkg_list_base_vanzper_ADAUGACAMP(S, K, vCAMP);
    dAux := ADD_MONTHS(dAux, 3);
    END LOOP;
  WHEN 5
  THEN
    FOR i IN current_setting('PKG_LIST_BASE_VANZPER.vInceput', TRUE)..current_setting('PKG_LIST_BASE_VANZPER.vSfarsit', TRUE) LOOP
        IF pTIP = 'SELECT' THEN
          vCamp := 'SUM(CASE WHEN AN = '||i||' THEN XAux ELSE 0 END) ';
        END IF;
        PERFORM pkg_list_base_vanzper_ADAUGACAMP(S,K,vCAMP);
      END LOOP;
  END CASE;
  RETURN S;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzper_fl_setparams</obj_name>
  <obj_hashval>5172686b638757f2a9292aa9cc38b1a3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzper_fl_setparams(ptipper numeric, ptipdata numeric, pinceput character varying, psfarsit character varying, ptipdate numeric, pincltva numeric, pinclunit numeric, pvaluta numeric, plunaini numeric, plunafin numeric, ptipum numeric, pum numeric, pinclserv numeric, pfaravanz numeric, pcodjob1 numeric, pcodatribut numeric, pvalachiz numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aTipInterval numeric := 0;
  An numeric;
  Luna numeric;
  DataRef date;
  vListUMA BOOLEAN := fnc_getvalconstantalucru('ListareUMAmbRapVanz')::NUMERIC = 1;
  vDif numeric;
  dInceput date;
  dSfarsit date;
  aux varchar;
  auxD varchar;
BEGIN
  --Florin 20.08.2020
  IF pCodJob1 &gt; 0
  THEN
    aTipInterval := 1;
  END IF;
  IF aTipInterval = 0
  THEN
    PERFORM set_config('PKG_LIST_BASE_VANZPER.vInceput', pInceput, FALSE);
    PERFORM set_config('PKG_LIST_BASE_VANZPER.vSfarsit', pSfarsit, FALSE);
  ELSE
    SELECT ANMAXIM, LUNAMAXIMA
    INTO An, Luna
    FROM FIRMALUNI;
    IF pTIPPER = 5
    THEN
      vDif := pSfarsit::numeric - pInceput::numeric;
      PERFORM set_config('PKG_LIST_BASE_VANZPER.vInceput', An-vDif, FALSE);
      PERFORM set_config('PKG_LIST_BASE_VANZPER.vSfarsit', An     , FALSE);
    ELSIF pTipData = 1
    THEN
      dInceput := To_Date(pInceput, 'DD.MM.YYYY');
      dSfarsit := To_Date(pSfarsit, 'DD.MM.YYYY');
      IF DATE_TRUNC('MONTH', dInceput) = dInceput AND Last_Day(dSfarsit) = dSfarsit
      THEN
        vDif := Months_Between(dInceput, DATE_TRUNC('MONTH', dSfarsit));
        DataRef := Last_day(To_Date(coalesce(An,'') || '.' || coalesce(Luna,''), 'YYYY.MM'));
        PERFORM set_config('PKG_LIST_BASE_VANZPER.vSfarsit', To_Char(DataRef, 'DD.MM.YYYY'), FALSE);
        DataRef := DATE_TRUNC('MONTH', Add_Months(DataRef, vDif));
        PERFORM set_config('PKG_LIST_BASE_VANZPER.vInceput', To_Char(DataRef, 'DD.MM.YYYY'), FALSE);
      ELSE
        vDif := dSfarsit - dInceput;
        DataRef := To_Date(coalesce(An,'') || '.' || coalesce(Luna,''), 'YYYY.MM');
        PERFORM set_config('PKG_LIST_BASE_VANZPER.vSfarsit', To_Char(DataRef, 'DD.MM.YYYY'), FALSE);
        DataRef := DataRef - vDif;
        PERFORM set_config('PKG_LIST_BASE_VANZPER.vInceput', To_Char(DataRef, 'DD.MM.YYYY'), FALSE);
      END IF;
    ELSE
      vDif := pSfarsit::numeric - pInceput::numeric;
      PERFORM set_config('PKG_LIST_BASE_VANZPER.vInceput', An * 12 + Luna-vDif, FALSE);
      PERFORM set_config('PKG_LIST_BASE_VANZPER.vSfarsit', An * 12 + Luna     , FALSE);
    END IF;
  END IF;
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vTipPer'    , pTipPer            ::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vTipData'   , (pTipData = 1)     ::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vCantitativ', pTipDate IN (0,2,3)::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vCantCutii' , (pTipPer &gt;= 3 AND pTipDate IN (0,2,3) AND vListUMA)  ::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vCantPaleti', (pTipPer &gt;= 3 AND pTipDate IN (0,2,3) AND vListUMA)  ::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vValoric'   , pTipDate IN (1,2,4)                      ::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vInclTVA'   , (pTipDate IN (1,2,4) AND (pInclTVA  = 1))::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vInclUnit'  , (pTipDate IN (1,2,4) AND (pInclUnit = 1))::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vVariatie'  , pTipDate IN (3,4) ::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vValuta'    , (pValuta = 1)     ::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vLunaIni'   , pLunaIni          ::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vLunaFin'   , pLunaFin          ::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vTipUM'     , pTipUM            ::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vUM'        , pUM               ::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vInclServ'  , (pInclServ = 1)   ::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vFaraVanz'  , (pFaraVanz = 1)   ::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vValAchiz'  , (pValAchiz = 1)   ::VARCHAR, FALSE);
  IF pTipPer = 5
  THEN
    PERFORM set_config('PKG_LIST_BASE_VANZPER.vDataIni', '01.01.'|| current_setting('PKG_LIST_BASE_VANZPER.vInceput', TRUE), FALSE);
    PERFORM set_config('PKG_LIST_BASE_VANZPER.vDataFin', '31.12.'|| current_setting('PKG_LIST_BASE_VANZPER.vSfarsit', TRUE), FALSE);
  ELSIF pTipData = 1
  THEN
    PERFORM set_config('PKG_LIST_BASE_VANZPER.vDataIni', current_setting('PKG_LIST_BASE_VANZPER.vInceput', TRUE), FALSE);
    PERFORM set_config('PKG_LIST_BASE_VANZPER.vDataFin', current_setting('PKG_LIST_BASE_VANZPER.vSfarsit', TRUE), FALSE);
  ELSE
    SELECT
    FNC_ExtractAnLuna.pan,
    FNC_ExtractAnLuna.pluna
    INTO
      An,
      Luna
    FROM FNC_ExtractAnLuna(current_setting('PKG_LIST_BASE_VANZPER.vInceput', TRUE)::NUMERIC);
    auxD = to_char(To_Date(Luna::varchar||'.'||An::varchar, 'MM.YYYY'), 'DD.MM.YYYY');
    PERFORM set_config('PKG_LIST_BASE_VANZPER.vDataIni', auxD, FALSE);
    SELECT
    FNC_ExtractAnLuna.pan,
    FNC_ExtractAnLuna.pluna
    INTO
      An,
      Luna
    FROM FNC_ExtractAnLuna(current_setting('PKG_LIST_BASE_VANZPER.vSfarsit', TRUE)::NUMERIC);
    aux = to_char(Last_Day(To_Date(Luna::varchar||'.'||An::varchar, 'MM.YYYY')), 'dd.mm.yyyy');
    PERFORM set_config('PKG_LIST_BASE_VANZPER.vDataFin', aux, FALSE);
  END IF;
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vCodAtribut', COALESCE(pCodAtribut, 0)::varchar, FALSE);
  PERFORM pkg_list_base_vanzper_BAGA_DINAMIC_COLS();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzper_setparams</obj_name>
  <obj_hashval>d2495af25e3890d36865ea63be076409</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzper_setparams(ptipper numeric DEFAULT NULL::numeric, ptipdata numeric DEFAULT 0, pinceput character varying DEFAULT NULL::character varying, psfarsit character varying DEFAULT NULL::character varying, ptipdate numeric DEFAULT NULL::numeric, pincltva numeric DEFAULT 0, pinclunit numeric DEFAULT 0, pvaluta numeric DEFAULT 0, plunaini numeric DEFAULT NULL::numeric, plunafin numeric DEFAULT NULL::numeric, ptipum numeric DEFAULT NULL::numeric, pum numeric DEFAULT NULL::numeric, pinclserv numeric DEFAULT 0, pfaravanz numeric DEFAULT 0, pcodjob1 numeric DEFAULT 0, pcodatribut numeric DEFAULT 0, pvalachiz numeric DEFAULT 0, pexclcust numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aTipInterval numeric := 0;
  An           numeric;
  Luna         numeric;
  DataRef      date;
  vListUMA     BOOLEAN := fnc_getvalconstantalucru('ListareUMAmbRapVanz')::NUMERIC = 1;
  vDif         numeric;
  dInceput     date;
  dSfarsit     date;
  aux          varchar;
  auxD         varchar;
BEGIN
  --Stef 08.01.2025
  IF COALESCE(pCodJob1,0) &gt; 0 THEN
    aTipInterval := 1;
  END IF;
  IF aTipInterval = 0 THEN
    PERFORM set_config('PKG_LIST_BASE_VANZPER.vInceput', pInceput, FALSE);
    PERFORM set_config('PKG_LIST_BASE_VANZPER.vSfarsit', pSfarsit, FALSE);
  ELSE
    SELECT ANMAXIM, LUNAMAXIMA INTO An, Luna FROM FIRMALUNI;
    IF pTIPPER = 5 THEN
      vDif := pSfarsit::numeric - pInceput::numeric;
      PERFORM set_config('PKG_LIST_BASE_VANZPER.vInceput', An-vDif, FALSE);
      PERFORM set_config('PKG_LIST_BASE_VANZPER.vSfarsit', An     , FALSE);
    ELSIF pTipData = 1 THEN
      dInceput := To_Date(pInceput, 'DD.MM.YYYY');
      dSfarsit := To_Date(pSfarsit, 'DD.MM.YYYY');
      IF DATE_TRUNC('MONTH', dInceput) = dInceput AND Last_Day(dSfarsit) = dSfarsit THEN
        vDif := Months_Between(dInceput, DATE_TRUNC('MONTH', dSfarsit));
        DataRef := Last_day(To_Date(coalesce(An,'') || '.' || coalesce(Luna,''), 'YYYY.MM'));
        PERFORM set_config('PKG_LIST_BASE_VANZPER.vSfarsit', To_Char(DataRef, 'DD.MM.YYYY'), FALSE);
        DataRef := DATE_TRUNC('MONTH', Add_Months(DataRef, vDif));
        PERFORM set_config('PKG_LIST_BASE_VANZPER.vInceput', To_Char(DataRef, 'DD.MM.YYYY'), FALSE);
      ELSE
        vDif := dSfarsit - dInceput;
        DataRef := To_Date(coalesce(An,'') || '.' || coalesce(Luna,''), 'YYYY.MM');
        PERFORM set_config('PKG_LIST_BASE_VANZPER.vSfarsit', To_Char(DataRef, 'DD.MM.YYYY'), FALSE);
        DataRef := DataRef - vDif;
        PERFORM set_config('PKG_LIST_BASE_VANZPER.vInceput', To_Char(DataRef, 'DD.MM.YYYY'), FALSE);
      END IF;
    ELSE
      vDif := pSfarsit::numeric - pInceput::numeric;
      PERFORM set_config('PKG_LIST_BASE_VANZPER.vInceput', An * 12 + Luna-vDif, FALSE);
      PERFORM set_config('PKG_LIST_BASE_VANZPER.vSfarsit', An * 12 + Luna     , FALSE);
    END IF;
  END IF;

  PERFORM set_config('PKG_LIST_BASE_VANZPER.vTipPer'    , pTipPer            ::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vTipData'   , (pTipData = 1)     ::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vCantitativ', pTipDate IN (0,2,3)::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vCantCutii' , (pTipPer &gt;= 3 AND pTipDate IN (0,2,3) AND vListUMA)  ::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vCantPaleti', (pTipPer &gt;= 3 AND pTipDate IN (0,2,3) AND vListUMA)  ::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vValoric'   , pTipDate IN (1,2,4)                      ::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vInclTVA'   , (pTipDate IN (1,2,4) AND (pInclTVA  = 1))::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vInclUnit'  , (pTipDate IN (1,2,4) AND (pInclUnit = 1))::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vVariatie'  , pTipDate IN (3,4) ::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vValuta'    , (pValuta = 1)     ::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vLunaIni'   , pLunaIni          ::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vLunaFin'   , pLunaFin          ::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vTipUM'     , pTipUM            ::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vUM'        , pUM               ::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vInclServ'  , (pInclServ = 1)   ::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vFaraVanz'  , (pFaraVanz = 1)   ::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vValAchiz'  , (pValAchiz = 1)   ::VARCHAR, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vExclCust'  , (pExclCust = 1)   ::VARCHAR, FALSE);

  IF pTipPer = 5 THEN
    PERFORM set_config('PKG_LIST_BASE_VANZPER.vDataIni', '01.01.'|| current_setting('PKG_LIST_BASE_VANZPER.vInceput', TRUE), FALSE);
    PERFORM set_config('PKG_LIST_BASE_VANZPER.vDataFin', '31.12.'|| current_setting('PKG_LIST_BASE_VANZPER.vSfarsit', TRUE), FALSE);
  ELSIF pTipData = 1 THEN
    PERFORM set_config('PKG_LIST_BASE_VANZPER.vDataIni', current_setting('PKG_LIST_BASE_VANZPER.vInceput', TRUE), FALSE);
    PERFORM set_config('PKG_LIST_BASE_VANZPER.vDataFin', current_setting('PKG_LIST_BASE_VANZPER.vSfarsit', TRUE), FALSE);
  ELSE
    SELECT FNC_ExtractAnLuna.pan, FNC_ExtractAnLuna.pluna
    INTO An, Luna
    FROM FNC_ExtractAnLuna(current_setting('PKG_LIST_BASE_VANZPER.vInceput', TRUE)::NUMERIC);

    auxD = to_char(To_Date(Luna::varchar||'.'||An::varchar, 'MM.YYYY'), 'DD.MM.YYYY');
    PERFORM set_config('PKG_LIST_BASE_VANZPER.vDataIni', auxD, FALSE);

    SELECT FNC_ExtractAnLuna.pan, FNC_ExtractAnLuna.pluna
    INTO   An, Luna
    FROM FNC_ExtractAnLuna(current_setting('PKG_LIST_BASE_VANZPER.vSfarsit', TRUE)::NUMERIC);

    aux = to_char(Last_Day(To_Date(Luna::varchar||'.'||An::varchar, 'MM.YYYY')), 'dd.mm.yyyy');
    PERFORM set_config('PKG_LIST_BASE_VANZPER.vDataFin', aux, FALSE);
  END IF;
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vCodAtribut', COALESCE(pCodAtribut, 0)::varchar, FALSE);
  PERFORM pkg_list_base_vanzper_BAGA_DINAMIC_COLS();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_voucher_processlist</obj_name>
  <obj_hashval>f824bd303d85c5ccf32684337f6865e7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_voucher_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sSelect     varchar;
  gSuplCols   varchar := 'VOUCHER V,VOUCHERLINK VL';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
begin

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config('pkg_list_base_voucher.gSuplCols', gSuplCols, false);

  sInsert := 'INSERT INTO ' || coalesce(tmpName,'') || '(
       OBS,
       PART,
       DATASTART,
       DATASTOP,
       MONEDA,
       VALOARE,
       REST,
       GestFol,
       GestEmit,
       NrDataRez,
       ValoareUt,
       NAV_CodDoc,
       NAV_TipDoc' || gUserFields || '
   )';
  sSelect := '
  SELECT
     V.OBS,
      P.DEN_PART,
      V.DATASTART,
      V.DATASTOP,
      M.SIMBOL,
      V.VALOARE,
      V.VALOARE - coalesce(X.FOLOSIT,0) REST,
      NF.Den_gest GestFol,
      NE.Den_gest GestEmit,
      CMDVL.NRDOc||'' / ''||CMDVL.DataDoc NrDataRez,
      VL.Valoare ValoareUt,
      V.CodVoucher, 99' || gUserAlias || '
  FROM VOUCHER V
         INNER JOIN NPART       P      on P.CodPART          = coalesce(V.CODPARTENER,0)
         INNER JOIN NMONEDE     M      on M.CodMoneda        = coalesce(V.Moneda,0)
         LEFT  JOIN (Select CodVoucher, Sum(Valoare) FOLOSIT from VOUCHERLINK group by CodVoucher) X on X.CodVoucher = V.Codvoucher
         LEFT  JOIN VOUCHERLINK VL     on VL.CodVoucher      = V.CODVOUCHER
         LEFT  JOIN COMANDA1    CMDVL1 on CMDVL1.CodComanda1 = VL.CodCmD
         LEFT  JOIN COMANDA     CMDVL  on CMDVL.CodComanda   = CMDVL1.CodComanda
         LEFT  JOIN RAC_REZ     RRVL   on RRVL.codcomanda    = CMDVL.codcomanda
         LEFT  JOIN NGEST       NF     on NF.CodGest         = RRVL.CodGestSursa
         LEFT  JOIN NGEST       NE     on NE.CodGest         = V.CodGest' || gSuplJoins;
  EXECUTE coalesce(sInsert,'') || coalesce(sSelect,'');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_voucher_setjoinuri</obj_name>
  <obj_hashval>4f430b44d823d9fdb46c543e9e34c659</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_voucher_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 06.08.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_voucher.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_voucherdoc_add_list_params</obj_name>
  <obj_hashval>df2019ef5b82520a09b7ba8520480a77</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_voucherdoc_add_list_params()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_rec record;
BEGIN
  --Florin 20.03.2023
  --Florin 05.10.2020
  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  FOR v_rec IN (
    SELECT P.Den_part, V.Valoare, v.DataStart, V.DataStop, M.Den_moneda Moneda,G.Den_Gest AgentiaEmitenta,V.Obs
    FROM VOUCHER V
        LEFT JOIN NPART   P   on P.CodPart      = V.CodPartener
        LEFT JOIN NMONEDE M   ON M.CODMONEDA    = V.Moneda
        LEFT JOIN RAC_REZ RAC on RAC.CodVoucher = V.CodVoucher
        LEFT JOIN NGEST   G   on G.CodGEST      = V.CodGEST
     WHERE V.CODVOUCHER = current_setting('PKG_LIST_BASE_VOUCHERDOC.vCodDoc', true)::numeric
  ) LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Vouch_PARTENER',             v_rec.DEN_PART);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Vouch_VALOARE',              v_rec.Valoare::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Vouch_Moneda',               v_rec.Moneda);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Vouch_DataStart',            v_rec.DataStart::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Vouch_DataStop',             v_rec.DataStop::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Vouch_AgentiaEmitenta',      v_rec.AgentiaEmitenta);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Obs',                        v_rec.Obs);
      EXIT;
    END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_voucherdoc_processlist</obj_name>
  <obj_hashval>f907a81b353613de8e4e640d9ce1c538</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_voucherdoc_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  gSuplCols   varchar:= 'COMANDA CMD, RAC_REZ RAC, VOUCHER V';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 20.03.2023
  --Florin 05.10.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('pkg_list_base_voucherdoc.gSuplCols', gSuplCols, FALSE);

  sInsert:=
  'INSERT INTO '||tmpName|| '(
    OBS, PART, DATASTART, DATASTOP, MONEDA, Valoare, Rest,GestFol,GestEmit,NrDataRez,ValoareUt'||
    gUserFields||')
  SELECT
    V.OBS, P.DEN_PART, V.DATASTART, V.DATASTOP, M.SIMBOL, V.VALOARE, V.VALOARE - coalesce(X.FOLOSIT,0) REST,
    NF.Den_gest GestFol,
    NE.Den_gest GestEmit,
    CMDVL.NRDOc||'' / ''||to_char(CMDVL.DataDoc, ''dd.mm.yyyy'') NrDataRez,
    VL.Valoare ValoareUt
    '||gUserAlias||'
  FROM VOUCHER V
    INNER JOIN NPART       P      on P.CodPART          = COALESCE(V.CODPARTENER,0)
    INNER JOIN NMONEDE     M      on M.CodMoneda        = COALESCE(V.Moneda,0)
    LEFT  JOIN (Select CodVoucher, Sum(Valoare) FOLOSIT from VOUCHERLINK group by CodVoucher) X on X.CodVoucher = V.Codvoucher
    LEFT  JOIN RAC_REZ     RAC    on RAC.CodVoucher     = V.CodVoucher
    LEFT  JOIN COMANDA     CMD    on CMD.CodComanda     = RAC.CodComanda
    LEFT  JOIN VOUCHERLINK VL     on VL.CodVoucher      = V.CODVOUCHER
    LEFT  JOIN COMANDA1    CMDVL1 on CMDVL1.CodComanda1 = VL.CodCmD
    LEFT  JOIN COMANDA     CMDVL  on CMDVL.CodComanda   = CMDVL1.CodComanda
    LEFT  JOIN RAC_REZ     RRVL   on RRVL.codcomanda    = CMDVL.codcomanda
    LEFT  JOIN NGEST       NF     on NF.CodGest         = RRVL.CodGestSursa
    LEFT  JOIN NGEST       NE     on NE.CodGest         = V.CodGest
    '||gSuplJoins||'
  WHERE V.CODVOUCHER = '||current_setting('PKG_LIST_BASE_VOUCHERDOC.vCodDoc', true) ;


  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
  PERFORM pkg_list_base_VoucherDoc_add_list_params();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_voucherinc_add_list_params</obj_name>
  <obj_hashval>7f0600f0e1bd7df75d292b21950a2b6b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_voucherinc_add_list_params()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Adina 16.06.2021
  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  FOR v_rec IN (SELECT COD_CASTOTUTILITY, FURNIZOR, SERVICIU, DEPLATA, PLATIT, PLATIT_TEXT, COD_SCALA, DATATRANZACTIE, CODCLIENT, TELEFON, NRFACTURA, DATAFACTURA,
                       SUCURSALA, ATMCOD, CUSTOMCODE1, CUSTOMPAYMENTFIELD3, JSONRESPONSE, LISTAT
                FROM CASTOT_UTILITY CU
                WHERE CU.COD_CASTOTUTILITY = current_setting('PKG_LIST_BASE_VOUCHERINC.vCod', true)::numeric
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener'            , v_rec.FURNIZOR);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Serviciu'            , v_rec.SERVICIU);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('De plata'            , TO_CHAR(v_rec.DEPLATA, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Platit'              , TO_CHAR(v_rec.PLATIT , 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Platit litere'       , v_rec.PLATIT_TEXT);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Chitanta'            , v_rec.COD_SCALA);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Data tranzactie'     , to_char(v_rec.DATATRANZACTIE, 'dd.mm.yyyy hh24:mi'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Cod client'          , v_rec.CODCLIENT);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Nr. factura'         , v_rec.NRFACTURA);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Data factura'        , to_char(v_rec.DATAFACTURA, 'dd.mm.yyyy hh24:mi'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Sucursala'           , v_rec.SUCURSALA);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('ATM cod'             , v_rec.ATMCOD);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Telefon'             , v_rec.telefon);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Custom cod'          , v_rec.CUSTOMCODE1);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Custom payment field', v_rec.CUSTOMPAYMENTFIELD3);
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_voucherinc_processlist</obj_name>
  <obj_hashval>4ae8f5d103207f332375bec59f6e30e7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_voucherinc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  gSuplCols   varchar := '';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Adina 16.06.2021
  PERFORM PKG_LIST_STRUCT_GOLESTE_PARAM();

  call pkg_list_struct_StartSuplCols();
  call pkg_list_struct_GetSuplCols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config('PKG_LIST_BASE_VOUCHERINC.gSuplCols', gSuplCols, false);

  sInsert := 'INSERT INTO ' || coalesce(TMPNAME,'') || '(
      COD_CASTOTUTILITY,
      FURNIZOR,
      SERVICIU,
      DEPLATA,
      PLATIT,
      PLATIT_TEXT,
      COD_SCALA,
      DATATRANZACTIE,
      CODCLIENT,
      TELEFON,
      NRFACTURA,
      DATAFACTURA,
      SUCURSALA,
      ATMCOD,
      CUSTOMCODE1,
      CUSTOMPAYMENTFIELD3,
      JSONRESPONSE,
      LISTAT
      ' || coalesce(gUserFields,'') || ')
    SELECT
      COD_CASTOTUTILITY,
      FURNIZOR,
      SERVICIU,
      DEPLATA,
      PLATIT,
      PLATIT_TEXT,
      COD_SCALA,
      DATATRANZACTIE,
      CODCLIENT,
      TELEFON,
      NRFACTURA,
      DATAFACTURA,
      SUCURSALA,
      ATMCOD,
      CUSTOMCODE1,
      CUSTOMPAYMENTFIELD3,
      JSONRESPONSE,
      LISTAT' || coalesce(gUserAlias,'') || '
    FROM CASTOT_UTILITY' || coalesce(gSuplJoins,'') || '
    WHERE COD_CASTOTUTILITY = ' || coalesce(current_setting('PKG_LIST_BASE_VOUCHERINC.vCod', true),'');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
  PERFORM PKG_LIST_BASE_VOUCHERINC_add_list_params();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_voucherinc_setjoinuri</obj_name>
  <obj_hashval>bce3ab27744869f92a5c7530dfc10017</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_voucherinc_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 16.06.2021
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_VOUCHERINC.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_voucherinc_setparams</obj_name>
  <obj_hashval>5d2be985e26018dd65bf8d6f79e21651</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_voucherinc_setparams(pcodvoucher numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 16.06.2021
  perform set_config('PKG_LIST_BASE_VOUCHERINC.vCod',(pCodVoucher)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_casabanka_setparams</obj_name>
  <obj_hashval>1aa92e4be7803ac0f794cdaeec7f2a91</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_casabanka_setparams(v_dataini character varying, v_datafin character varying, v_tipdoc numeric, pcodjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni INTEGER;
  xLunaAnFin INTEGER;
BEGIN
  --Florin 17.05.2022 - fixat 52291
  --Florin 30.07.2020

  perform set_config('PKG_LIST_CASABANKA.p_DataIni', v_DataIni::varchar, false);
  perform set_config('PKG_LIST_CASABANKA.p_DataFin', v_DataFin::varchar, false);

  IF  pCodJob1 &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(pCodJob1, current_setting('PKG_LIST_CASABANKA.p_DataIni', true), current_setting('PKG_LIST_CASABANKA.p_DataFin', true), xLunaAnIni, xLunaAnFin);
  END IF;

  perform set_config('PKG_LIST_CASABANKA.p_tipDoc',v_tipDoc::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_config_cautacoloana</obj_name>
  <obj_hashval>d3d8bf81901d976a4a0c3b4da17bfba8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_config_cautacoloana(INOUT wme_result boolean, INOUT scol character varying, INOUT ssircoloane character varying, INOUT desc_ boolean)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult       BOOLEAN := FALSE;
  sirTemp       varchar;
  coloanaDinSir varchar;
BEGIN
  --Adina 07.07.2021 - tichet 50767 - am pus upper la linia 14
  sirTemp := sSirColoane || ',';
  WHILE  char_length( sirTemp) &gt; 0 LOOP
    coloanaDinSir := substring( SirTemp from 1 for position( ',' in sirTemp) - 1);
    IF  upper(coloanaDinSir) = upper(sCol) || ' DESC' THEN
      Desc_   := TRUE;
      sResult := TRUE;
    ELSIF coloanaDinSir = sCol THEN
      Desc_   := FALSE;
      sResult := TRUE;
    END IF;
    sirTemp := substring( sirTemp from char_length( ColoanaDinSir) + 2 for char_length( SirTemp));
  END LOOP;
  WME_Result :=  sResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_config_formatnullselect</obj_name>
  <obj_hashval>fd20bcb8ce12a9e6a9690c2e11ccca96</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_config_formatnullselect(stab character varying, visiblecols character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vRec     RECORD;
  sCols    varchar;
  sResult  varchar := 'SELECT 1::numeric NRCRT';
BEGIN
  sCols      := ','||Lower(REPLACE(visibleCols, ' ', ''))||',';
  FOR vRec IN (
                SELECT ORDINAL_POSITION, COLUMN_NAME::VARCHAR COLUMN_NAME, DATA_TYPE
                FROM information_schema.columns
                WHERE TABLE_NAME = lower( stab)
                  AND POSITION(','||COLUMN_NAME::VARCHAR||',' IN sCols) &gt; 0
                ORDER BY 1
              )
  LOOP
    sResult := sResult||', NULL::'||vRec.DATA_TYPE||' '||vRec.COLUMN_NAME;
  END LOOP;
  RETURN sResult;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_config_formatnullstring</obj_name>
  <obj_hashval>99ab8fd56220e560024a3b83e35d7e9d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_config_formatnullstring(INOUT wme_result character varying, INOUT scols character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  idx     integer;
  cols    varchar;
  sResult varchar;
begin
  cols := sCols;
  idx  := position( ';' in cols);

  IF  idx = 0 AND char_length( cols) &gt; 0  THEN
    sResult := 'NULL ' || cols;
  ELSE
    WHILE  idx &gt; 0 LOOP
      sResult := sResult || 'NULL ' || substring( cols from 1 for idx - 1) || ', ';
      cols    := substring( cols from idx + 1 for char_length( cols));
      idx     := position( ';' in cols);
      IF  idx = 0 AND  char_length( cols) &gt; 0 THEN  sResult := sResult || 'NULL ' || cols; END IF;
    END LOOP;
  END IF;

  WME_Result :=  sResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_config_get_expresii</obj_name>
  <obj_hashval>484414a156381f5816859fa329f5a28f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_config_get_expresii(INOUT wme_result character varying, INOUT calc_cols character varying, INOUT expr_lst character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  idx      integer;
  j        integer;
  col_name varchar;
  expr     varchar;
  sResult  varchar := '';
  cols     varchar;
  expresii varchar;
begin
  cols     := calc_cols;
  expresii := expr_lst;
  idx      := position( ', ' in cols);
  j        := position( ', ' in expresii);

  IF  idx = 0 AND  char_length( cols) &gt; 0 THEN
     sResult := expresii || ' ' || cols;
  ELSE
    WHILE  idx &gt; 0 LOOP
      col_name := substring( cols from 1 for idx - 1);
      expr     := substring( expresii from 1 for j - 1);
      sResult  := sResult || expr || ' ' || col_name || ',';
      cols     := substring( cols from idx + 1 for char_length( cols));
      expresii := substring( expresii from j + 1 for char_length( expresii));
      idx      := position( ', ' in cols);
      j        := position( ', ' in expresii);
      IF  idx = 0 AND  char_length( cols) &gt; 0 THEN  sResult := sResult || expresii || ' ' || cols; END IF;
    END LOOP;
  END IF;

  WME_Result :=  sResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_config_get_group_id</obj_name>
  <obj_hashval>dea412980f9ea292876a4767b211041a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_config_get_group_id(nrcrt numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  GR_ID numeric;
begin
  IF    nrcrt &lt;= -999999999 THEN gr_id := round( (log( 2, abs( 200 + nrcrt) + 1))::numeric) + 1;
  ELSIF nrcrt &gt;=  999999999 THEN gr_id := round( (log( 2, abs( nrcrt - 999999999) + 1))::numeric) + 1;
  END IF;
  return gr_id;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_config_get_sum_calc</obj_name>
  <obj_hashval>59909384df3201ab3869f02879267156</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_config_get_sum_calc(INOUT wme_result character varying, INOUT sum_calc character varying, INOUT fara_total character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  idx        integer;
  str        varchar;
  sResult    varchar := '';
  nr         numeric;
  vFaraTotal varchar := TRIM( both ' ' from fara_total);
begin
  str := sum_calc;
  idx := position( ';' in str);
  IF  idx = 0 AND  char_length( str) &gt; 0 THEN
    IF vFaraTotal IS NULL
      THEN  sResult := 'SUM' || substring( str from  1 for  position( ')' in str)) || substring( str from  position( ')' in str) + 1 for char_length( str));
      ELSE  sResult := 'SUM(CASE WHEN ' || vFaraTotal || ' THEN ' || substring( str from  1 for  position( ')' in str)) || ' ELSE 0 END) ' || substring( str from  position( ')' in str) + 1 for char_length( str));
    END IF;
  ELSE
    WHILE  idx &gt; 0 LOOP
      IF vFaraTotal IS NULL
        THEN sResult := sResult || 'SUM' || substring( str from  1 for  position( ')' in str)) || (SELECT PKG_LIST_CONFIG_getColoanefromExpresii.WME_RESULT FROM PKG_LIST_CONFIG_getColoanefromExpresii(NULL, substring( str from  1 for  idx - 1), nr)) || ',';
        ELSE sResult := sResult || 'SUM(CASE WHEN ' || vFaraTotal || ' THEN ' || substring( str from  1 for  position( ')' in str)) || ' ELSE 0 END) ' || (SELECT PKG_LIST_CONFIG_getColoanefromExpresii.WME_RESULT FROM PKG_LIST_CONFIG_getColoanefromExpresii(NULL, substring( str from  1 for  idx - 1), nr)) || ',';
      END IF;
      str := substring( str from  idx + 1 for char_length( str));
      idx := position( ';' in str);
      IF  idx = 0 AND  char_length( str) &gt; 0 THEN
        IF vFaraTotal IS NULL
          THEN  sResult := sResult || 'SUM' || substring( str from  1 for  position( ')' in str)) || substring( str from  position( ')' in str) + 1 for char_length( str));
          ELSE  sResult := sResult || 'SUM(CASE WHEN ' || vFaraTotal || ' THEN ' || substring( str from  1 for  position( ')' in str)) || ' ELSE 0 END) ' || substring( str from  position( ')' in str) + 1 for char_length( str));
        END IF;
      END IF;
    END LOOP;
  END IF;
  WME_Result :=  sResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_config_getcoloanefromcalccols</obj_name>
  <obj_hashval>9062119e102b6833bee7384bf0a52d84</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_config_getcoloanefromcalccols(INOUT wme_result character varying, INOUT sum_calc character varying, INOUT calc_cols character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  idxs       integer;
  idxc       integer;
  sCols      varchar;
  cCols      varchar;
  sResult    varchar := '';
  nrColsSuma integer;
  nrColsCalc integer;
  col        varchar := '';
begin
  SELECT coalesce(PKG_LIST_CONFIG_getColoanefromExpresii.WME_RESULT, '') into sCols FROM PKG_LIST_CONFIG_getColoanefromExpresii(NULL, sum_calc, nrColsSuma);
  SELECT coalesce(PKG_LIST_CONFIG_getColoanefromExpresii.WME_RESULT, '') into cCols FROM PKG_LIST_CONFIG_getColoanefromExpresii(NULL, calc_cols, nrColsCalc);
  idxs := position( ';' in sCols);
  IF  idxs = 0 AND  char_length( sCols) &gt; 0  THEN
    idxc := position( cCols in sCols);
    IF  idxc = 1 THEN sRESULT := substring( cCols from idxc + char_length( sCols) + 1 for char_length( cCols));
    ELSE
      sResult := substring( cCols from 1 for idxc - 2);
      sResult := sResult || substring( cCols from idxc + 1 for char_length( cCols));
    END IF;
  ELSE
    WHILE  idxs &gt; 0 LOOP
      col     := substring( sCols from 1 for idxs - 1);
      idxc    := position( cCols in col);
      sResult := substring( cCols from 1 for idxc - 1);
      sResult := sResult || substring( cCols from char_length( col) + idxc + 1 for char_length( cCols));
      sCols   := Substring( sCols from idxs + 1 for char_length( sCols));
      idxs    := position( ';' in sCols);
      cCols   := sResult;
      IF  idxs = 0 AND  char_length( sCols) &gt; 0 THEN
        idxc := position( cCols in sCols);
        IF  idxc = 1 THEN sRESULT := substring( cCols from idxc + char_length( sCols) + 1 for char_length( cCols));
        ELSE
          sResult := substring( cCols from 1 for idxc - 2);
          sResult := sResult || substring( cCols from idxc + 1 for char_length( cCols));
        END IF;
      END IF;
    END LOOP;
  END IF;
  WME_Result :=  sResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_config_getcoloanefromexpresii</obj_name>
  <obj_hashval>f3c6e7cea2c492b4d7a40b9031bcacd3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_config_getcoloanefromexpresii(INOUT wme_result character varying, INOUT calc_cols character varying, INOUT nrcols numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult varchar;
  idx     integer;
  i       integer;
  tmp     varchar;
  aCol    varchar;
  aExp    varchar;
  pExp    integer;
  lExp    integer;
begin
  tmp    := calc_cols;
  nrCols := 0;
  WHILE  char_length( TRIM( both ' ' from tmp)) &gt; 0 LOOP
    idx := position( ';' in tmp);
    IF  idx = 0 THEN  idx := char_length( tmp) + 1;END IF;
    aExp := substring( tmp from 1 for idx - 1);
    lExp := char_length(aExp);
    pExp := 0;
    i    := 1;
    WHILE  i &lt;= lExp LOOP
       if substring( aExp from i for 1) = ')' then pExp := i; end if;
       i := i + 1;
    END LOOP;
    acol    := substring( aExp from pExp + 1 for char_length(aExp));
    sRESULT := sResult || ',' || acol;
    nrcols  := nrcols + 1;
    tmp     := substring( tmp from idx + 1 for char_length( tmp));
  END LOOP;
  sResult := substring( sResult from 2 for char_length( sResult));
  WME_Result :=  sRESULT;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_config_getdenserankclause</obj_name>
  <obj_hashval>2fde4f586593e73bd99a491967243f1f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_config_getdenserankclause(INOUT wme_result character varying, INOUT scols character varying, INOUT nrcols numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  SRESULT  varchar := '';
  I        integer;
  IDX      integer := 1;
  COL_NAME varchar := '';
  STR      varchar;
  ORD      varchar;
  PART     varchar := '';
begin
  STR := UPPER(SCOLS);
  I   := position( ',' in str);
  IF (I = 0)  AND  char_length( STR) &gt; 0  THEN
     SRESULT := '(DENSE_RANK() OVER ( ORDER BY ' || STR || ' ))::numeric NRG_' || IDX || ',';
  ELSE
    WHILE  I &gt; 0 LOOP
--insert into X(view_name, Test) values('21 str', str);
      COL_NAME := substring( str from 1 for I - 1);
      ORD      := COL_NAME;
--insert into X(view_name, Test) values('22 ORD', ORD);
      IF PART = ''
      THEN  SRESULT := SRESULT || '(DENSE_RANK() OVER ( ORDER BY ' || ORD || ' ))::numeric NRG_' || IDX || ',';
      ELSE  SRESULT := SRESULT || '(DENSE_RANK() OVER ( PARTITION BY ' || Replace( substring( PART from 1 for char_length( PART) - 1), ' DESC', '') || ' ORDER BY ' || ORD || ' ))::numeric NRG_' || IDX || ',';
      END IF;
--insert into X(view_name, Test) values('23 SRESULT', SRESULT);
      PART := PART || ORD || ',';
--insert into X(view_name, Test) values('24 PART', PART);
      STR  := substring( str from i + 1 for char_length( str));
--insert into X(view_name, Test) values('25 str', str);
      I    := position( ',' in str);
      IDX  := IDX + 1;
      IF (I = 0)  AND (char_length( STR) &gt; 0) THEN
        ORD     := STR;
        SRESULT := SRESULT || '(DENSE_RANK() OVER ( PARTITION BY ' || replace( substring( PART from  1 for char_length( PART) - 1), ' DESC', '') || ' ORDER BY ' || ORD || ' ))::numeric NRG_' || IDX || ',';
        --insert into X(view_name, Test) values('26 SRESULT', SRESULT);
      END IF;
    END LOOP;
  END IF;
  NRCOLS     := IDX;
  sResult    := substring( sResult from 1 for char_length( sResult) - 1);
  WME_Result := sResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_config_getrownumclause</obj_name>
  <obj_hashval>90f5c6f994ca9dd0df4018f11d75f724</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_config_getrownumclause(INOUT wme_result character varying, INOUT scols character varying, INOUT nrcols numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult  varchar := '';
  i        integer;
  idx      integer := 1;
  col_name varchar := '';
  cols     varchar := '';
  str      varchar := '';
  sIdx     varchar := '';
begin
  str := UPPER( sCols);
  --insert into X(view_name, Test) values('10 str', str);
  i   := position( ',' in str);
  IF (i = 0)  and  char_length( str) &gt; 0 THEN
    sIdx    := IDX::varchar;
    sResult := '(ROW_NUMBER() OVER (PARTITION BY ' || replace( STR, ' DESC', ' ') || ' ORDER BY ' || STR || ' ))::numeric NRCRT_' || sIdx || ',';
  ELSE
    WHILE  i &gt; 0 LOOP
      col_name := substring( str from  1 for i - 1);
      cols     := cols || ',' || col_name;
      str      := substring( str from  i + 1 for char_length( str));
      i        := position( ',' in str);
      sIdx     := IDX::varchar;
      sResult  := sResult || '(ROW_NUMBER() OVER (PARTITION BY ' || replace( substring( cols from  2 for char_length( cols)), ' DESC', ' ') || ' ORDER BY ' || substring( cols from  2 for char_length( cols)) || '))::numeric NRCRT_' || sIdx || ',';
  --insert into X(view_name, Test) values('11 idx', To_char(idx, '9999'));
  --insert into X(view_name, Test) values('11 sResult', sResult);
      idx := idx + 1;
      IF (i = 0)  and (char_length( str) &gt; 0) THEN
        col_name := STR;
        cols     := cols || ',' || col_name;
        sIdx     := IDX::varchar;
        sResult  := sResult || '(ROW_NUMBER() OVER (PARTITION BY ' || replace( substring( cols from  2 for char_length( cols)), ' DESC', ' ') || ' ORDER BY ' || substring( cols from  2 for char_length( cols)) || '))::numeric NRCRT_' || sIdx || ',';
  --insert into X(view_name, Test) values('12 idx', To_char(idx, '9999'));
  --insert into X(view_name, Test) values('12 sResult', sResult);
        idx      := idx;
      END IF;
    END LOOP;
  END IF;
  nrCols     := idx;
  --insert into X(view_name, Test) values('13 idx', To_char(idx, '9999'));
  --insert into X(view_name, Test) values('13 sResult', sResult);
  sResult    := substring( sResult from 1 for char_length( sResult) - 1);
  --insert into X(view_name, Test) values('14 sResult', sResult);
  WME_Result := sResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_config_getselectsimplu</obj_name>
  <obj_hashval>4a56b4e376c9d1435948cbe1b4a7a9c1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_config_getselectsimplu(tmptable character varying, visible_cols character varying, where_clause character varying, order_cols character varying, calc_cols character varying, sum_calc character varying, bcentralizat boolean, finterval character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_COLS           RECORD;
  strSelect        varchar := 'SELECT null ';
  strSelectAll     varchar := 'SELECT ';
  strSelectHeader  varchar := 'SELECT ';
  strSelectFooter  varchar := 'SELECT ';
  strSelectDetalii varchar := 'SELECT ';
  strSelectNull    varchar := 'SELECT ';
  strWhereClause   varchar := 'WHERE NOT (';
  sNVL_header      varchar;
  sNVL_footer      varchar;
  visibleCols      varchar;
  sWhere           varchar;
  allCols          varchar := '';
  sColoaneCalc     varchar := '';
  nrCalcCols       numeric;
  sType            varchar := '';
  sCol             varchar := '';
begin
  --Adina 19.02.2021 - reparat eroare la safe mode liste (add sCol si sType, scos from Dual, pus alias-uri, pus cast-uri la Null; inlocuit ROWNUM)
  visibleCols := visible_cols;
  FOR V_COLS IN (SELECT COLUMN_NAME FROM information_schema.columns WHERE TABLE_NAME = lower(tmptable)) LOOP
    sCol             := v_cols.column_name;
    strSelectAll     := strSelectAll || v_cols.column_name || ',';
    strSelectDetalii := strSelectDetalii || v_cols.column_name || ',';
    select
      PKG_LIST_CONFIG_GetNVLClause.snvl_header,
      PKG_LIST_CONFIG_GetNVLClause.snvl_footer,
      PKG_LIST_CONFIG_GetNVLClause.swhere,
      PKG_LIST_CONFIG_GetNVLClause.sType
    into sNVL_header,sNVL_footer,sWhere,sType
    from PKG_LIST_CONFIG_GetNVLClause(tmptable,sCol,sNVL_header,sNVL_footer,sWhere,sType,false);
    strSelectHeader := strSelectHeader || sNVL_header || ' ' || v_cols.column_name || ',';
    strSelectFooter := strSelectFooter || sNVL_footer || ' ' || v_cols.column_name || ',';
    strSelectNull   := strSelectNull   || 'NULL::'|| sType ||' AS ' || v_cols.column_name || ',';
    strWhereClause  := strWhereClause  || ' ' || v_cols.column_name || sWhere;
    allCols         := allCols || v_cols.column_name || ',';
  END LOOP;
  allCols      := substring(allcols from 1 for char_length(allCols) - 1);
  strSelectAll := substring(strSelectAll from 1 for char_length(strSelectAll) - 1) || ' FROM ' || UPPER(tmptable);
  IF char_length(TRIM(both ' ' from where_clause)) &gt; 0 then strSelectAll := strSelectAll || ' WHERE ' || where_clause;  END IF;
  IF char_length(TRIM(both ' ' from order_cols  )) &gt; 0 then strSelectAll := strSelectAll || ' ORDER BY ' || order_cols;   END IF;

  SELECT
  PKG_LIST_CONFIG_getColoanefromExpresii.WME_RESULT,
  PKG_LIST_CONFIG_getColoanefromExpresii.calc_cols,
  PKG_LIST_CONFIG_getColoanefromExpresii.nrcols
  into sColoaneCalc,calc_cols,nrCalcCols
  FROM PKG_LIST_CONFIG_getColoanefromExpresii(NULL,calc_cols,nrCalcCols);

  IF char_length(calc_cols) &gt; 0 then strSelectDetalii := strSelectDetalii || replace(calc_cols, ';', ',') || ',';  END IF;
  strSelectDetalii := strSelectDetalii || 'row_number() over() AS NRCRT';
  strSelectHeader  := strSelectHeader  || 'NRCRT ';
  strSelectFooter  := strSelectFooter  || 'NRCRT ';
  IF char_length(calc_cols) &gt; 0 THEN allCols := allCols || ',' || sColoaneCalc; END IF;
  allCols          := allCols || ',NRCRT';
  strSelectHeader  := strSelectHeader  || ' FROM (' || strSelectNull || ' NULL::numeric NRCRT ) C_PG';
  strSelectFooter  := strSelectFooter  || ' FROM (' || strSelectNull || ' NULL::numeric NRCRT ) B_PG';
  strSelectDetalii := strSelectDetalii || ' FROM (' || strSelectAll  || ') A_PG';
  strWhereClause   := substring(strWhereClause from 1 for char_length(strWhereClause) - char_length('AND'));
  strWhereClause   := strWhereClause || ')';
  strSelect        := 'SELECT ' || allCols || ',';
  strSelect        := substring(strSelect from 1 for char_length(strSelect) - 1);
  strSelect        := strSelect || '  FROM ( ';
  strSelect        := strSelect || strSelectDetalii || ' UNION ALL ';
  strSelect        := strSelect || strSelectHeader || ' UNION ALL ';
  IF char_length(TRIM(both ' ' from order_cols)) &gt; 0
  THEN strSelect := strSelect || strSelectFooter || ' ) D_PG ' || strWhereClause || ' ORDER BY ' || order_cols || ', NRCRT';
  ELSE strSelect := strSelect || strSelectFooter || ' ) D_PG ' || strWhereClause || ' ORDER BY NRCRT';
  END IF;
  strSelect := 'SELECT SQL.*, row_number() over() AS GLOBALID FROM (' || STRSELECT || ') sql ';
  IF bCentralizat THEN
    strSelect := 'SELECT * FROM  (' || strSelect || ') WHERE  (NRCRT &gt;= ' || PKG_LIST_CONFIG_get_Sid_footer || ' OR NRCRT &lt;= -'|| PKG_LIST_CONFIG_get_Sid_header || ')  ';
    IF char_length(TRIM(both ' ' from fInterval)) &gt; 0 THEN strSelect := strSelect || fInterval; END IF;
  END IF;
  RETURN strSelect;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_config_getsoldsumclause</obj_name>
  <obj_hashval>94a4666c96c485357a54aebba7c332c5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_config_getsoldsumclause(INOUT wme_result character varying, INOUT ssoldcols character varying, INOUT sresetcols character varying, INOUT sordercols character varying, INOUT pexp numeric, INOUT pgroup boolean)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult        varchar := '';
  sCols          varchar;
  sReset         varchar;
  idx_grup_sold  integer := 0;
  idx_cols_sold  integer := 0;
  idx_grup_reset integer := 0;
  idx_cols_reset integer := 0;
  grup_sold      varchar;
  grup_reset     varchar;
  i              integer;
  j              integer;
  nrEXP          integer := 1;
  sOver          varchar := 'OVER';
begin
  --Florin 11.11.2021 - sin. Oracle (47805)
  -- Stef 28.07.2020
  IF COALESCE(length(sordercols),0) = 0
  THEN sOver := sOver||'()';
  ELSE sOver := sOver||'(ORDER BY ' ||sOrderCols ||')';
  END IF;

  sCols          := Upper(sSoldCols);
  sReset         := Upper(sResetCols);
  IF Coalesce(Length(sReset), 0) = 0 THEN
    sReset := '0';
  END IF;
  idx_grup_reset := strpos(sReset, ';');

  IF NOT pGroup THEN
    grup_sold     := sCols;
    idx_cols_sold := strpos(grup_sold, ',');
    IF (idx_cols_sold = 0) and (length(grup_sold) &gt; 0) THEN
      sResult := sResult || ' SUM (' || grup_sold || ')'||sOver||' EXP_' ||nrExp || ',';
      nrExp   := nrExp + 1;
    ELSE
      WHILE idx_cols_sold &gt; 0 LOOP
        sResult       := sResult || ' SUM (' ||substr(grup_sold, 1, idx_cols_sold - 1) ||')'||sOver||' EXP_' ||nrExp || ',';
        nrExp         := nrExp + 1;
        grup_sold     := substr(grup_sold,idx_cols_sold + 1,length(grup_sold));
        idx_cols_sold := strpos(grup_sold, ',');
        IF (idx_cols_sold = 0) and (length(grup_sold) &gt; 0) THEN
          sResult := sResult || ' SUM (' || grup_sold || ')'||sOver||' EXP_' ||nrExp || ',';
          nrExp   := nrExp + 1;
        END IF;
      END LOOP;
    END IF;
  ELSIF trim(both ' ' from sResetCols) IS NULL THEN
    grup_sold     := sCols;
    idx_cols_sold := strpos(grup_sold, ',');
    IF (idx_cols_sold = 0) and (length(grup_sold) &gt; 0) THEN
      sResult := sResult || ' SUM (CASE WHEN NRG_1 IS NULL THEN '|| grup_sold ||' ELSE 0 END)'||sOver||' EXP_' ||nrExp || ',';
      nrExp   := nrExp + 1;
    ELSE
      WHILE idx_cols_sold &gt; 0 LOOP
        sResult       := sResult || ' SUM (CASE WHEN NRG_1 IS NULL THEN ' ||substr(grup_sold, 1, idx_cols_sold - 1) ||' ELSE 0 END)'||sOver||' EXP_' ||nrExp || ',';
        nrExp         := nrExp + 1;
        grup_sold     := substr(grup_sold,idx_cols_sold + 1,length(grup_sold));
        idx_cols_sold := strpos(grup_sold, ',');
        IF (idx_cols_sold = 0) and (length(grup_sold) &gt; 0) then
          IF LENGTH(TRIM(sOrderCols))&gt;0 THEN
          sResult := sResult || ' SUM (CASE WHEN NRG_1 IS NULL THEN ' || grup_sold ||' ELSE 0 END)OVER (ORDER BY ' || sOrderCols ||') EXP_' ||nrExp || ',';
          else
            sResult := sResult || ' SUM (CASE WHEN NRG_1 IS NULL THEN ' || grup_sold ||' ELSE 0 END)OVER (ORDER BY nrct) EXP_' ||nrExp || ',';
          end if;
          nrExp   := nrExp + 1;
        END IF;
      END LOOP;
    END IF;
  ELSE
    grup_reset    := sReset;
    grup_sold     := sCols;
    idx_cols_sold := strpos(grup_sold, ',');
    IF (idx_cols_sold = 0) and (length(grup_sold) &gt; 0) THEN
      sResult := sResult || ' SUM (CASE WHEN NRG_1 IS NULL THEN ' || grup_sold ||' ELSE 0 END) OVER (PARTITION BY ' || grup_reset ||' ORDER BY NRCRT) EXP_' ||nrExp || ',';
      nrExp   := nrExp + 1;
    ELSE
      WHILE idx_cols_sold &gt; 0 LOOP
        sResult       := sResult || ' SUM (CASE WHEN NRG_1 IS NULL THEN ' ||substr(grup_sold, 1, idx_cols_sold - 1) ||' ELSE 0 END) OVER (PARTITION BY ' || grup_reset ||' ORDER BY NRCRT) EXP_' ||nrExp || ',';
        nrExp         := nrExp + 1;
        grup_sold     := substr(grup_sold,idx_cols_sold + 1,length(grup_sold));
        idx_cols_sold := strpos(grup_sold, ',');
        IF (idx_cols_sold = 0) and (length(grup_sold) &gt; 0) THEN
          sResult := sResult || ' SUM (CASE WHEN NRG_1 IS NULL THEN ' || grup_sold ||' ELSE 0 END) OVER (PARTITION BY ' || grup_reset ||' ORDER BY NRCRT) EXP_' ||nrExp || ',';
          nrExp   := nrExp + 1;
        END IF;
      END LOOP;
    END IF;
  END IF;
  pexp       := nrExp - 1;
  WME_Result := sResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_config_prelucreazacolcalc</obj_name>
  <obj_hashval>e003d74298a0bb7197740b2b80d9af5d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_config_prelucreazacolcalc(INOUT pcoloanecalc character varying, INOUT psumcalc character varying, INOUT psumheaderfooter character varying, INOUT fara_total character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sCalc       varchar;
  sSumCalc    varchar;
  aColCalc    varchar;
  aColSumCalc varchar;
  i           integer;
  idx         integer;
begin
  sCalc            := pColoaneCalc || ';';
  sSumCalc         := pSumCalc || ';';
  pColoaneCalc     := '';
  pSumCalc         := '';
  pSumHeaderFooter := '';
  idx := strpos( sCalc, ';');
  WHILE  idx &gt; 0 LOOP
    aColCalc    := substr( sCalc, 1, strpos( sCalc, ';') - 1);
    aColSumCalc := substr( sSumCalc, 1, strpos( sSumCalc, ';') - 1);
    SELECT PKG_LIST_CONFIG_getColoanefromExpresii.WME_RESULT  into aColCalc    FROM PKG_LIST_CONFIG_getColoanefromExpresii(NULL, aColCalc, i);
    SELECT PKG_LIST_CONFIG_getColoanefromExpresii.WME_RESULT  into aColSumCalc FROM PKG_LIST_CONFIG_getColoanefromExpresii(NULL, aColSumCalc, i);
    IF  aColCalc = aColSumCalc
    THEN
      pColoaneCalc     := pColoaneCalc || aColCalc || ',';
      pSumCalc         := pSumCalc || (SELECT PKG_LIST_CONFIG_get_sum_calc.WME_RESULT FROM PKG_LIST_CONFIG_get_sum_calc(NULL, aColSumCalc, fara_total)) || ',';
      pSumHeaderFooter := pSumHeaderFooter || (SELECT PKG_LIST_CONFIG_getColoanefromExpresii.WME_RESULT FROM PKG_LIST_CONFIG_getColoanefromExpresii(NULL, aColSumCalc, i)) || ',';
      sCalc            := substr( sCalc, strpos( sCalc, ';') + 1, length( sCalc));
      sSumCalc         := substr( sSumCalc, strpos( sSumCalc, ';') + 1, length( sSumCalc));
    ELSE
      pColoaneCalc     := pColoaneCalc || aColCalc || ',';
      pSumCalc         := pSumCalc || 'NULL,';
      pSumHeaderFooter := pSumHeaderFooter || 'NULL,';
      sCalc            := substr( sCalc, strpos( sCalc, ';') + 1, length( sCalc));
    END IF;
    idx := strpos( sCalc, ';');
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_config_proceseazatotal</obj_name>
  <obj_hashval>ef0fd092df5cfb4f0cbed3658dffe5d6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_config_proceseazatotal(INOUT tmptable character varying, INOUT sum_cols character varying, INOUT group_cols character varying, INOUT susername character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_COLS     RECORD;
  vTable     varchar;
  strSelect  varchar := '';
  strGroupBy varchar := '';
  DESC_      BOOLEAN;
  asVarcharStr varchar := ''; --53069
BEGIN
  --Bogdan 14.02.2022 53069 : PG - Lista balanta stocurilor: grupare fara afisare linie de titlu si subtotal
  --Adina 29.07.2020 adaugat AS
  FOR V_COLS IN (SELECT COLUMN_NAME, DATA_TYPE FROM information_schema.columns WHERE TABLE_NAME = lower( tmptable) ) loop --53069
    IF (SELECT PKG_LIST_CONFIG_CautaColoana.WME_RESULT FROM PKG_LIST_CONFIG_CautaColoana(NULL, lower( v_cols.column_name), lower( group_cols), desc_)) THEN
      strSelect  := strSelect || ',' || v_cols.column_name;
      strGroupBy := strGroupBy || ',' || v_cols.column_name;
    ELSIF
    (SELECT PKG_LIST_CONFIG_CautaColoana.WME_RESULT FROM PKG_LIST_CONFIG_CautaColoana(NULL, lower( v_cols.column_name), lower( sum_cols), desc_))  THEN
      strSelect := strSelect || ', SUM(' || v_cols.column_name || ') AS ' || v_cols.column_name;
    else
           -- 53069
      if (v_cols.data_type = 'character varying') then
         asVarcharStr := ' ::varchar ';
      else
         asVarcharStr := '';
      end if;
      strSelect := strSelect || ', MAX(' || v_cols.column_name || ') '||asVarcharStr||' AS ' || v_cols.column_name;
      --- END  53069
    END IF;
  END LOOP;
  IF coalesce(strGroupBy, '') &lt;&gt; '' THEN
    vTable    := 'T' || tmptable;
    strSelect := 'SELECT ' || SubStr( strSelect, 2) || ' FROM ' || tmptable || ' Group BY ' || SubStr( strGroupBy, 2);
--insert into X(view_name, Test) values('8aa', strSelect);
--RETURN;
    PERFORM PKG_LIST_CONFIG_TryToDropTMP( vTable);
    EXECUTE ' CREATE TEMPORARY TABLE ' || vTable || ' ON COMMIT PRESERVE ROWS AS ' || strSelect;
    EXECUTE ' GRANT SELECT ON ' || vTable || ' TO ' || sUserName;
    tmptable := vTable;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_config_scoatecoloanadinsir</obj_name>
  <obj_hashval>5f086c0b61c7d26e45fc11d1535a8d01</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_config_scoatecoloanadinsir(INOUT wme_result character varying, INOUT scol character varying, INOUT ssircoloane character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult    varchar;
  ColTemp    varchar;
  sirTemp    varchar;
  virgula    varchar;
  desc_      BOOLEAN;
begin
  IF strpos(sSirColoane, sCol || ',') = 1 THEN
    sResult := substr(sSirColoane, length(sCol) + 2, length(sSirColoane));
  ELSE
    IF (SELECT PKG_LIST_CONFIG_CautaColoana.WME_RESULT FROM PKG_LIST_CONFIG_CautaColoana(NULL, sCol, sSirColoane, desc_)) THEN
      ColTemp := ',' || sCol || ',';
      sirTemp := ',' || sSirColoane || ',';
      sirTemp := substr(sirTemp, 1, strpos(sirTemp, ColTemp) - 1) || ',' ||substr(sirTemp,strpos(sirTemp, colTemp) + length(colTemp),length(sirTemp));
      sirTemp := substr(sirTemp, 2, length(sirTemp));
      virgula := substr(sirtemp, length(sirtemp), 1);
      IF virgula = ',' then sirTemp := substr(sirTemp, 1, length(sirTemp) - 1);  END IF;
      sResult := sirTemp;
    ELSE
      sResult := sSirColoane;
    END IF;
  END IF;
  WME_Result := sResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_config_trytodroptable</obj_name>
  <obj_hashval>5fcea3f1ccf1dd67b1055421ee883d65</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_config_trytodroptable(tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  nr    numeric := 0;
  Skema varchar;
BEGIN
  --Adina 14.07.2021 - pus functia to_regclass
  Skema   := lower(current_setting('PKG_GLOBALS.FIRMANAME'));
  TMPNAME := lower(TMPNAME);

  --SELECT count(*) into NR FROM information_schema.TABLES WHERE table_schema = Skema AND table_name = TMPNAME;
  NR := CASE WHEN (SELECT to_regclass(tmpname)) IS NULL THEN 0 ELSE 1 END;
  IF  NR &gt; 0 THEN
    EXECUTE 'TRUNCATE TABLE ' || TMPNAME;
    EXECUTE 'DROP TABLE '     || TMPNAME;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_config_trytodroptmp</obj_name>
  <obj_hashval>216024aab490dde15f1e7fe19f2327b2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_config_trytodroptmp(tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  nr numeric := 0;
begin
  SELECT count(*) into NR FROM information_schema.TABLES WHERE table_schema like 'pg_temp_%' AND table_name = lower(TMPNAME);
  IF  NR &gt; 0 THEN
    EXECUTE 'TRUNCATE TABLE ' || TMPNAME;
    EXECUTE 'DROP TABLE '     || TMPNAME;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selclaseart_setparams</obj_name>
  <obj_hashval>890f899031292787904a910a9be894a8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selclaseart_setparams(pperioada character varying, ptoateclasea numeric, ptotipart numeric, v_dataini character varying, v_datafin character varying, pcodjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
  p_DataIni  varchar;
  p_DataFin  varchar;
BEGIN
  --Florin 10.09.2020
  PERFORM set_config('PKG_LIST_SELCLASEART.vPerioada', pPerioada, FALSE);
  p_DataIni := v_DataIni;
  p_DataFin := v_DataFin;

  IF pCodJob1 &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(pCodJob1, p_DataIni, p_DataFin, xLunaAnIni, xLunaAnFin);
    PERFORM set_config('PKG_LIST_SELCLASEART.vPerioada', 'TO_DATE('''|| p_DataIni ||''',''DD.MM.YYYY'')' +' AND TO_DATE('''|| p_DataFin ||''',''DD.MM.YYYY'')', FALSE);
  END IF;

  PERFORM set_config('PKG_LIST_SELCLASEART.vToateClaseA', (COALESCE(pToateClaseA, 0) = 1)::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELCLASEART.vTotiPart'   , (COALESCE(pTotiPart   , 0) = 1)::varchar, FALSE);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selcomenzi_allgest</obj_name>
  <obj_hashval>282e0b6f2584168da48b7ed567c2ddae</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selcomenzi_allgest()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
declare
  vAllGest numeric;
begin
  --Bogdan 01.09.2020
  vAllGest := case when current_setting('PKG_LIST_SELCOMENZI.vAllGest', true) = '' then null
          else current_setting('PKG_LIST_SELCOMENZI.vAllGest', true)::numeric end;
  return vAllGest=1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selcomenzi_cominchise</obj_name>
  <obj_hashval>20d4d52af5817f1a07a3c20d82e927e4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selcomenzi_cominchise()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
DECLARE
  vComInchise numeric;
BEGIN
  --Adina 13.05.2021 - sinc.Oracle din 12.05.2021
  vComInchise := NULLIF(current_setting('PKG_LIST_SELCOMENZI.vComInchise', true),'')::numeric;
  return vComInchise;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selcomenzi_dupadata</obj_name>
  <obj_hashval>fd38b125aaf3fe2a9b3293d0f4e8407a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selcomenzi_dupadata()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
declare
  vDupaData numeric;
begin
  --Bogdan 01.09.2020
  vDupaData := case when current_setting('PKG_LIST_SELCOMENZI.vDupaData', true) = '' then null
          else current_setting('PKG_LIST_SELCOMENZI.vDupaData', true)::numeric end;
  return vDupaData=1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selcomenzi_setparams</obj_name>
  <obj_hashval>db0112718275d8c662543b7a5859531b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selcomenzi_setparams(pdupadata numeric DEFAULT 0, ppers character varying DEFAULT NULL::character varying, pperf character varying DEFAULT NULL::character varying, pallgest numeric DEFAULT 0, pcominchise numeric DEFAULT 0, v_codjob1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sDataS    varchar(10);
  sDataF    varchar(10);
  vAL_S      NUMERIC;
  vAL_F      NUMERIC;
  gPerioada VARCHAR(200);
BEGIN
  --Adina 17.05.2021 - 49705
  --Florin 14.05.2021 -  fixat 49670
  --Adina 13.05.2021 - sinc.Oracle din 12.05.2021
  --Bogdan 1.09.2020
  perform set_config('PKG_LIST_SELCOMENZI.vDupaData'  , Coalesce(pDupaData  , 0)::varchar,false);
  perform set_config('PKG_LIST_SELCOMENZI.vAllGest'   , Coalesce(pAllGest   , 0)::varchar,false);
  perform set_config('PKG_LIST_SELCOMENZI.vComInchise', Coalesce(pCOmInchise, 0)::integer::varchar,false);

  IF pkg_list_selcomenzi_dupadata() THEN
      sDataS := pPerS;
      sDataF := pPerF;
  ELSE
      vAL_S := pPerS::numeric;
      vAL_F := pPerF::numeric;
  END IF;

  IF  V_CODJOB1 &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, sDataS, sDataF, vAL_S, vAL_F);
  END IF;

  IF pkg_list_selcomenzi_dupadata() AND  sDataS = sDataF THEN
    gPerioada := '= TO_DATE('''||sDataS||''',''DD.MM.YYYY'')';
  elsif pkg_list_selcomenzi_dupadata() then
    gPerioada := 'BETWEEN TO_DATE('''||sDataS||''',''DD.MM.YYYY'') AND TO_DATE('''||sDataF||''',''DD.MM.YYYY'')';
  elsif vAL_S  = vAL_F then
    gPerioada := '= '||vAL_S;
  else
    gPerioada := 'BETWEEN '||vAL_S||' AND '||vAL_F;
  end if;

  perform set_config('PKG_LIST_SELCOMENZI.vPerioada',gPerioada,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selcont_getsoldsub</obj_name>
  <obj_hashval>fd1836df4d41c9271b6d114079e274cb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selcont_getsoldsub()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Stef 19.03.2024
  RETURN current_setting('PKG_LIST_SELCONT.gSoldSub', true)::boolean;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selcont_getsubunit</obj_name>
  <obj_hashval>bb75b1da5b48fd0c932005adf6bcb62f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selcont_getsubunit()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 03.08.2020
  return  current_setting('PKG_LIST_SELCONT.gSubunit', true)::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selcont_gettipplan</obj_name>
  <obj_hashval>99e12bb3e7ef486258a1c0cc6c41ff58</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selcont_gettipplan()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 03.08.2020
  return  current_setting('PKG_LIST_SELCONT.gPlan', true)::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selcont_setparams</obj_name>
  <obj_hashval>a48fa3f27c5a6e8a34420a8458951601</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selcont_setparams(plunastart numeric, plunafin numeric, pplan numeric, pcuobs numeric, psubunit numeric, psoldsub numeric, pcodjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vDataS    date;
  vDataF    date;
  sSelContS varchar;
  sSelContD varchar;

  gLunaS    NUMERIC(20);
  gLunaF    NUMERIC(20);
  gPlan     INTEGER;
  gLuna     VARCHAR(100);
  gCuObs    BOOLEAN;
  gSoldSub  BOOLEAN;
  gSubunit  NUMERIC(20);
BEGIN
  --Florin 22.03.2024 - fixat 61423
  --Stef 19.03.2024
  gLunaS   := pLunaStart;
  gLunaF   := pLunaFin;
  gPlan    := pPlan;
  gCuObs   := Coalesce(pCuObs,   0) = 1;
  gSoldSub := Coalesce(pSoldSub, 0) = 1;

  gSubunit := Coalesce(pSubunit, 1);
  IF Coalesce(pCodJob1,0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(pCodJob1,vDataS,vDataF,gLunaS,gLunaF);
    IF gSubunit = 1 THEN
      gSubunit := 0;
    END IF;
  END IF;

  IF gSubunit &gt; 1 AND Coalesce(fnc_GetValConstanta('Holding', 0, gLunaF)::numeric, 0) = 1 THEN
    gSoldSub := TRUE;
  END IF;

  PERFORM pkg_list_Struct_GOLESTE_PARAM();
  PERFORM pkg_globals_SetSeparator(',');

  IF gPlan = 2 THEN -- plan secundar
    SELECT fnc_array_to_vc3200(ARRAY_AGG(Simbol ORDER BY clasa, simbol)), fnc_array_to_vc3200(ARRAY_AGG(Den_Cont ORDER BY clasa, simbol)) INTO sSelContS, sSelContD
    FROM nconts
    WHERE codconts::varchar IN (SELECT VALOARE FROM tmp_manevra_liste WHERE filtru = 'CODCONT');
  ELSIF gPlan = 3 THEN -- plan tertiar
    SELECT fnc_array_to_vc3200(ARRAY_AGG(Simbol ORDER BY clasa, simbol)), fnc_array_to_vc3200(ARRAY_AGG(Den_Cont ORDER BY clasa, simbol)) INTO sSelContS, sSelContD
    FROM ncontt c
    WHERE c.codcontt::varchar IN (SELECT VALOARE FROM tmp_manevra_liste WHERE filtru = 'CODCONT');
  ELSE -- plan principal
    SELECT fnc_array_to_vc3200(ARRAY_AGG(Simbol ORDER BY clasa, simbol)), fnc_array_to_vc3200(ARRAY_AGG(Den_Cont ORDER BY clasa, simbol)) INTO sSelContS, sSelContD
    FROM ncont c
    WHERE c.codcont::varchar IN (SELECT VALOARE FROM tmp_manevra_liste WHERE filtru = 'CODCONT');
  END IF;

  PERFORM pkg_list_Struct_ADAUGA_PARAM('Conturi selectate'           , sSelContS);
  PERFORM pkg_list_Struct_ADAUGA_PARAM('Conturi selectate - denumiri', sSelContD);

  perform set_config('PKG_LIST_SELCONT.gLunaS'  , gLunaS::varchar  , false);
  perform set_config('PKG_LIST_SELCONT.gLunaF'  , gLunaF::varchar  , false);
  perform set_config('PKG_LIST_SELCONT.gPlan'   , gPlan::varchar   , false);
  perform set_config('PKG_LIST_SELCONT.gCuObs'  , gCuObs::varchar  , false);
  perform set_config('PKG_LIST_SELCONT.gSoldSub', gSoldSub::varchar, false);
  perform set_config('PKG_LIST_SELCONT.gSubunit', gSubunit::varchar, false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_seldata_getdataref</obj_name>
  <obj_hashval>c91f16405f492337f3c1bb3f049215bc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_seldata_getdataref()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.09.2020
  return to_date(current_setting ('PKG_LIST_SELDATA.vDataRef', true),'dd.mm.yyyy');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_seldata_setallparams</obj_name>
  <obj_hashval>306e3d6b5c99b43a8b6258ffe1fafc9d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_seldata_setallparams(pdataref character varying DEFAULT NULL::character varying, pcodextra1 numeric DEFAULT NULL::numeric, pchkextra1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.09.2020
  perform set_config ('PKG_LIST_SELDATA.vDataRef'  ,pDataRef           ,false);
  perform set_config ('PKG_LIST_SELDATA.vCodExtra1',pCodExtra1::varchar,false);
  perform set_config ('PKG_LIST_SELDATA.vChkExtra1',pChkExtra1::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_seldelegat_setparams</obj_name>
  <obj_hashval>2a987618c53cbd1060d5eb8e2048966c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_seldelegat_setparams(pdupadata numeric, pdataini character varying, pdatafin character varying, plunaanini numeric, plunaanfin numeric, palldeleg numeric, v_codjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vDataIni date := to_date(pDataIni,'dd.mm.yyyy');
  vDataFin date := to_date(pDataFin,'dd.mm.yyyy');
BEGIN
  --Florin 11.09.2020
  PERFORM set_config('PKG_LIST_SELDELEGAT.vAllDeleg' , (COALESCE(pAllDeleg, 0) = 1)::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELDELEGAT.vDupaData' , (COALESCE(pDupaData, 0) = 1)::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELDELEGAT.vDataIni'  , pDataIni, FALSE);
  PERFORM set_config('PKG_LIST_SELDELEGAT.vDataFin'  , pDataFin, FALSE);
  PERFORM set_config('PKG_LIST_SELDELEGAT.vLunaAnIni', COALESCE(pLunaAnIni, 0)::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELDELEGAT.vLunaAnFin', COALESCE(pLunaAnFin, 0)::varchar, FALSE);

  IF v_CodJob1 &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, vDataIni, vDataFin, pLunaAnIni, pLunaAnFin);
  END IF;

  PERFORM PKG_ORA_LISTS_SET_INTERVAL_LISTARE(vDataIni, vDataFin);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_seldocext_setparams</obj_name>
  <obj_hashval>ea499bac2fcd033df051f4a807414cfc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_seldocext_setparams(pdupadata numeric, pdatas character varying, pdataf character varying, v_codjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  ALISTID    numeric := 0;
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
  vDataS     DATE;
  vDataF     DATE;
  sDataS     varchar;
  sDataF     varchar;
BEGIN
  --Florin 10.08.2020
  PERFORM set_config('PKG_LIST_SELDOCEXT.vDupaData', pDupaData::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELDOCEXT.vDataS'   , pDataS   ::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELDOCEXT.vDataF'   , pDataF   ::varchar, FALSE);

  vDataS = fnc_current_setting_date('PKG_LIST_SELDOCEXT.vDataS');
  vDataF = fnc_current_setting_date('PKG_LIST_SELDOCEXT.vDataF');
  xLunaAnIni := EXTRACT(YEAR FROM vDataS) * 12 + EXTRACT(MONTH FROM vDataS);
  xLunaAnFin := EXTRACT(YEAR FROM vDataF) * 12 + EXTRACT(MONTH FROM vDataF);

  IF COALESCE(v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, vDataS, vDataF, xLunaAnIni, xLunaAnFin);
  END IF;

  sDataS := 'TO_DATE(''' ||  To_char(vDataS,'dd.mm.yyyy') || ''',''dd.mm.yyyy'')';
  sDataF := 'TO_DATE(''' ||  To_char(vDataF,'dd.mm.yyyy') || ''',''dd.mm.yyyy'')';

  IF pDupaData = 1 AND vDataS = vDataF THEN
    PERFORM set_config('PKG_LIST_SELDOCEXT.vPerioada', sDataS, FALSE);
  ELSIF pDupaData = 1 THEN
    PERFORM set_config('PKG_LIST_SELDOCEXT.vPerioada', 'BETWEEN ' || sDataS || ' AND ' || sDataF, FALSE);
  ELSIF xLunaAnIni = xLunaAnFin THEN
    PERFORM set_config('PKG_LIST_SELDOCEXT.vPerioada', '= '|| xLunaAnIni::varchar, FALSE);
  ELSE
    PERFORM set_config('PKG_LIST_SELDOCEXT.vPerioada', 'BETWEEN '|| xLunaAnIni::varchar || ' AND ' || xLunaAnFin::varchar, FALSE);
  END IF;

  PERFORM PKG_ORA_LISTS_SET_INTERVAL_LISTARE(vDataS, vDataF);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectemulare_setparams</obj_name>
  <obj_hashval>06bcef981340373fae596effaa93bb5a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectemulare_setparams(v_dataini character varying, v_datafin character varying, v_tipprel numeric, v_tipfiltrare numeric, v_siretur numeric, v_codjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
  vDataS     DATE;
  vDataF     DATE;
BEGIN
  --Florin 17.08.2020
  PERFORM set_config('PKG_LIST_SELECTEMULARE.p_DataIni', v_DataIni, false);
  PERFORM set_config('PKG_LIST_SELECTEMULARE.p_DataFin', v_DataFin, false);

  vDataS = fnc_current_setting_date('PKG_LIST_SELECTEMULARE.p_dataini');
  vDataF = fnc_current_setting_date('PKG_LIST_SELECTEMULARE.p_datafin');
  xLunaAnIni := EXTRACT(YEAR FROM vDataS) * 12 + EXTRACT(MONTH FROM vDataS);
  xLunaAnFin := EXTRACT(YEAR FROM vDataF) * 12 + EXTRACT(MONTH FROM vDataF);

  IF v_CodJob1 &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(v_CODJOB1, vDataS, vDataF, xLunaAnIni, xLunaAnFin);
  END IF;

  PERFORM set_config('PKG_LIST_SELECTEMULARE.p_TipPrel'    , v_TipPrel    ::varchar, false);
  PERFORM set_config('PKG_LIST_SELECTEMULARE.p_TipFiltrare', v_TipFiltrare::varchar, false);
  PERFORM set_config('PKG_LIST_SELECTEMULARE.p_SiRetur'    , v_SiRetur    ::varchar, false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectgest_setparams</obj_name>
  <obj_hashval>e77ba27005abeec67f6ec03a7e900ae7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectgest_setparams(pdataini character varying, pdatafin character varying, pallgest numeric, pdupadata numeric, plunaanini numeric, plunaanfin numeric, paduserii numeric, pcalcpmp numeric, pdatadoc numeric, pextra1 numeric, v_codjob1 numeric, pextra2 numeric, pextra3 numeric, palltipdoc numeric DEFAULT 1, sdocs character varying DEFAULT NULL::character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vDataS DATE;
  vDataF DATE;
BEGIN
  --Florin 05.09.2025 - fixat 65583
  --Florin 11.08.2020
  PERFORM set_config('PKG_LIST_SELECTGEST.vAllGest' , pAllGest ::varchar, false);
  PERFORM set_config('PKG_LIST_SELECTGEST.vDupaData', pDupaData::varchar, false);
  PERFORM set_config('PKG_LIST_SELECTGEST.vDataIni' , pDataIni ::varchar, false);
  PERFORM set_config('PKG_LIST_SELECTGEST.vDataFin' , pDataFin ::varchar, false);
  PERFORM set_config('PKG_LIST_SELECTGEST.vLunaAnIni',COALESCE(pLunaAnIni, 0)::varchar,false);
  PERFORM set_config('PKG_LIST_SELECTGEST.vLunaAnFin',COALESCE(pLunaAnFin, 0)::varchar,false);
  vDataS = fnc_current_setting_date('PKG_LIST_SELECTGEST.vDataIni');
  vDataF = fnc_current_setting_date('PKG_LIST_SELECTGEST.vDataFin');
  IF COALESCE(v_CodJob1, 0) &gt; 0
  THEN
    select adataini, adatafin, alunaanini, alunaanfin into vDataS, vDataF, pLunaAnIni, pLunaAnFin from PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, vDataS, vDataF, pLunaAnIni, pLunaAnFin);
    PERFORM set_config('PKG_LIST_SELECTGEST.vDataIni' , vDataS ::varchar, false);
    PERFORM set_config('PKG_LIST_SELECTGEST.vDataFin' , vDataF ::varchar, false);
    PERFORM set_config('PKG_LIST_SELECTGEST.vLunaAnIni',COALESCE(pLunaAnIni, 0)::varchar,false);
    PERFORM set_config('PKG_LIST_SELECTGEST.vLunaAnFin',COALESCE(pLunaAnFin, 0)::varchar,false);
 END IF;
  PERFORM PKG_ORA_LISTS_SET_INTERVAL_LISTARE(vDataS, vDataF);
  PERFORM set_config('PKG_LIST_SELECTGEST.bAduSerii' , pAduSerii ::varchar, false);
  PERFORM set_config('PKG_LIST_SELECTGEST.bCalcPMP'  , pCalcPMP  ::varchar, false);
  PERFORM set_config('PKG_LIST_SELECTGEST.bDataDoc'  , pDataDoc  ::varchar, false);
  PERFORM set_config('PKG_LIST_SELECTGEST.bExtra1'   , pExtra1   ::varchar, false);
  PERFORM set_config('PKG_LIST_SELECTGEST.bExtra2'   , pExtra2   ::varchar, false);
  PERFORM set_config('PKG_LIST_SELECTGEST.bExtra3'   , pExtra3   ::varchar, false);
  PERFORM set_config('PKG_LIST_SELECTGEST.bAllTipDoc', pAllTipDoc::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTGEST.bDocs'     , sDocs              , FALSE);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectgest2_setparams</obj_name>
  <obj_hashval>b7d90a65303abd81ecc9ac0d3afce1fb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectgest2_setparams(pallgest numeric, pziuaini numeric, pziuafin numeric, pallioart numeric, pdata numeric DEFAULT 1)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vZiMax NUMERIC := Extract( DAY FROM Last_Day( To_Date( coalesce(to_char( getlunalucru(), 'fm00'),'') || '.' || coalesce(to_char( getanlucru(), 'fm0000'),''), 'mm.yyyy')));
begin
  --Adina iulie 2020
  perform set_config('PKG_LIST_SELECTGEST2.vAllGest' , trunc(pAllGest)::varchar ,false);
  perform set_config('PKG_LIST_SELECTGEST2.vAllIOArt', trunc(pAllIOArt)::varchar,false);
  perform set_config('PKG_LIST_SELECTGEST2.vZiIni'   , Least( pZiuaIni, vZiMax)::varchar,false);
  perform set_config('PKG_LIST_SELECTGEST2.vZiFin'   , Least( pZiuaFin, vZiMax)::varchar,false);
  perform set_config('PKG_LIST_SELECTGEST2.vData'    , pData::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectgest2_toateioart</obj_name>
  <obj_hashval>dbca71b9e6e0f3ab9c9cbc6a75ad27b9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectgest2_toateioart(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  --Adina iulie 2020
WME_Result :=  (current_setting('PKG_LIST_SELECTGEST2.vAllIoart', true)::boolean);
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectgest2_ziuafin</obj_name>
  <obj_hashval>e6edc1611c48ffdcb0b60e9e7a0e10f7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectgest2_ziuafin(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  --Adina iulie 2020
WME_Result :=  (current_setting('PKG_LIST_SELECTGEST2.vZiFin', true)::numeric);
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectgest2_ziuaini</obj_name>
  <obj_hashval>f112301c4dc8009ce74e48d083d562f4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectgest2_ziuaini(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  --Adina iulie 2020
WME_Result :=  (current_setting('PKG_LIST_SELECTGEST2.vZiIni', true)::numeric);
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectgestart_setparams</obj_name>
  <obj_hashval>cdc4044fd2eb3cef0d82d4c5982aeef3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectgestart_setparams(pallgest numeric, pallart numeric, pdatastart character varying, pdatafin character varying, pcodcomanda numeric DEFAULT 0, pserii numeric DEFAULT 0, pcodjob1 numeric DEFAULT 0, panaliza numeric DEFAULT 0, psaptamana numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
BEGIN
  --Laura 29.09.2021 - sinc Oracle (27.09.2021)
  --Adina 01 septembrie 2020
  perform set_config('PKG_LIST_SELECTGESTART.vAllGest',( COALESCE(pAllGest,1) = 1)::varchar,false);
  perform set_config('PKG_LIST_SELECTGESTART.vAllArt',( COALESCE(pAllArt,1) = 1)::varchar,false);
  perform set_config('PKG_LIST_SELECTGESTART.vDataStart',pDataStart,false);
  perform set_config('PKG_LIST_SELECTGESTART.vDataFin',pDataFin,false);

  IF  COALESCE(pCodJob1,0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(pCodJob1, current_setting('PKG_LIST_SELECTGESTART.vDataStart', true), current_setting('PKG_LIST_SELECTGESTART.vDataFin', true), xLunaAnIni, xLunaAnFin);
  END IF;

  perform set_config('PKG_LIST_SELECTGESTART.vCodComanda',(COALESCE(pCodComanda, 0))::varchar,false);
  perform set_config('PKG_LIST_SELECTGESTART.vSerii',(COALESCE(pSerii, 0))::varchar,false);
  perform set_config('PKG_LIST_SELECTGESTART.vAnaliza',(COALESCE(pAnaliza, 0))::varchar,false);
    perform set_config('PKG_LIST_SELECTGESTART.vSaptamana',(COALESCE(pSaptamana, 0))::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectgestart_setparams_x</obj_name>
  <obj_hashval>e7ae1b002e7532a377235005579753aa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectgestart_setparams_x(pallgest numeric, pallart numeric, pdatastart character varying, pdatafin character varying, pcodcomanda numeric DEFAULT 0, pserii numeric DEFAULT 0, pcodjob1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
BEGIN
  --Adina 01 septembrie 2020
  perform set_config('PKG_LIST_SELECTGESTART.vAllGest',( COALESCE(pAllGest,1) = 1)::varchar,false);
  perform set_config('PKG_LIST_SELECTGESTART.vAllArt',( COALESCE(pAllArt,1) = 1)::varchar,false);
  perform set_config('PKG_LIST_SELECTGESTART.vDataStart',pDataStart,false);
  perform set_config('PKG_LIST_SELECTGESTART.vDataFin',pDataFin,false);

  IF  COALESCE(pCodJob1,0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(pCodJob1, current_setting('PKG_LIST_SELECTGESTART.vDataStart', true), current_setting('PKG_LIST_SELECTGESTART.vDataFin', true), xLunaAnIni, xLunaAnFin);
  END IF;

  perform set_config('PKG_LIST_SELECTGESTART.vCodComanda',(COALESCE(pCodComanda, 0))::varchar,false);
  perform set_config('PKG_LIST_SELECTGESTART.vSerii',(COALESCE(pSerii, 0))::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectgestper_setparams</obj_name>
  <obj_hashval>6eb9731fe5efb6480d6337529f941ad2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectgestper_setparams(pdataini character varying, pdatafin character varying, pallgest numeric, pdupadata numeric, plunaanini numeric, plunaanfin numeric, paduserii numeric, pcalcpmp numeric, pdatadoc numeric, pextra1 numeric, v_codjob1 numeric, pextra2 numeric, pextra3 numeric, pindiferent numeric, pdatadocini character varying, pdatadocfin character varying, pcod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vDataIni   date;
  vDataFin   date;
  vLunaAnIni NUMERIC;
  vLunaAnFin NUMERIC;
BEGIN
  --Florin 14.09.2020
  vDataIni := to_date(pDataIni,'dd.mm.yyyy');
  vDataFin := to_date(pDataFin,'dd.mm.yyyy');
  vLunaAnIni := COALESCE(pLunaAnIni,0);
  vLunaAnFin := COALESCE(pLunaAnFin,0);
  PERFORM set_config('PKG_LIST_SELECTGESTPER.vAllGest' , (COALESCE(pAllGest, 0) = 1)::varchar , FALSE);
  PERFORM set_config('PKG_LIST_SELECTGESTPER.vDupaData', (COALESCE(pDupaData, 0) = 1)::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTGESTPER.vDataIni' , pDataIni, FALSE);
  PERFORM set_config('PKG_LIST_SELECTGESTPER.vDataFin' , pDataFin, FALSE);
  PERFORM set_config('PKG_LIST_SELECTGESTPER.vLunaAnIni',COALESCE(pLunaAnIni, 0)::varchar,false);
  PERFORM set_config('PKG_LIST_SELECTGESTPER.vLunaAnFin',COALESCE(pLunaAnFin, 0)::varchar,false);

  IF COALESCE(v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, vDataIni, vDataFin, vLunaAnIni, vLunaAnFin);
  END IF;

  PERFORM PKG_ORA_LISTS_SET_INTERVAL_LISTARE(vDataIni, vDataFin);
  PERFORM set_config('PKG_LIST_SELECTGESTPER.bAduSerii'  , (COALESCE(pAduSerii  , 0) = 1)::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTGESTPER.bCalcPMP'   , (COALESCE(pCalcPMP   , 0) = 1)::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTGESTPER.bDataDoc'   , (COALESCE(pDataDoc   , 0) = 1)::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTGESTPER.bExtra1'    , (COALESCE(pExtra1    , 0) = 1)::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTGESTPER.bExtra2'    , (COALESCE(pExtra2    , 0) = 1)::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTGESTPER.bExtra3'    , (COALESCE(pExtra3    , 0) = 1)::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTGESTPER.bIndiferent', (COALESCE(pIndiferent, 0) = 1)::varchar, FALSE);

  IF pDataDocIni = '  .  .    ' THEN
    PERFORM set_config('PKG_LIST_SELECTGESTPER.vDataDocIni', pDataIni, FALSE);
  ELSE
    PERFORM set_config('PKG_LIST_SELECTGESTPER.vDataDocIni', pDataDocIni, FALSE);
  END IF;

  IF pDataDocFin = '  .  .    ' THEN
    PERFORM set_config('PKG_LIST_SELECTGESTPER.vDataDocFin', pDataDocFin, FALSE);
  ELSE
    PERFORM set_config('PKG_LIST_SELECTGESTPER.vDataDocFin', pDataFin, FALSE);
  END IF;

  PERFORM set_config('PKG_LIST_SELECTGESTPER.vCod', pCod::varchar, FALSE);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectluna_lunafin</obj_name>
  <obj_hashval>aa90d581655e3f2b4a41c8f78b616fe5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectluna_lunafin()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 21.09.2020
  return current_setting ('PKG_LIST_SELECTLUNA.vLunaFin', true) ::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectluna_lunastart</obj_name>
  <obj_hashval>e5d9ce53da9a480ec065b498f6799481</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectluna_lunastart()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 21.09.2020
  return current_setting ('PKG_LIST_SELECTLUNA.vLunaStart', true) ::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectluna_setparams</obj_name>
  <obj_hashval>f8681c16b316600ad182dd8ba605fd3b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectluna_setparams(p_lunastart numeric, p_lunafin numeric, p_curs numeric, p_extra1 numeric, pcodjob1 numeric, p_fixed numeric, p_valuta numeric, p_extra2 numeric, p_extra3 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vALIni     NUMERIC;
  vALFin     NUMERIC;
  vAn        NUMERIC;
  vLunaStart NUMERIC;
  vLunaFin   NUMERIC;
  vDif       NUMERIC;
  vCurs      NUMERIC;
  vDataIni   date;
  vDataFin   date;
begin
  -- Stef 24.10.2023
  vDif   := p_LunaFin - p_LunaStart;
  vALIni := getanlucru() * 12 + p_LunaStart;
  vALFin := getanlucru() * 12 + p_LunaFin;
  IF  pCodJob1 &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(pCodJob1, vDataIni, vDataFin, vALIni, vALFin);
  END IF;
  SELECT FNC_ExtractAnLuna.pan, FNC_ExtractAnLuna.pluna INTO vAn, vLunaFin FROM FNC_ExtractAnLuna(vALFin);
  vLunaStart := Greatest(vLunaFin - vDif, 1);
  vCurs      := CASE
                  WHEN p_Valuta = -1 THEN -1
                  WHEN p_Valuta =  0 THEN  1
                  ELSE Coalesce(NULLIF(p_Curs, 0),1)
                END;
  perform set_config('PKG_LIST_SELECTLUNA.vLunaStart', vLunaStart                 ::varchar, false);
  perform set_config('PKG_LIST_SELECTLUNA.vLunaFin'  , vLunaFin                   ::varchar, false);
  perform set_config('PKG_LIST_SELECTLUNA.vCurs'     , vCurs                      ::varchar ,false);
  perform set_config('PKG_LIST_SELECTLUNA.vExtra1'   , (Coalesce(p_Extra1, 0) = 1)::varchar ,false);
  perform set_config('PKG_LIST_SELECTLUNA.vFixed'    , (Coalesce(p_Fixed , 0) = 1)::varchar ,false);
  perform set_config('PKG_LIST_SELECTLUNA.vVALUTA'   , (Coalesce(p_Valuta, 0) = 1)::varchar ,false);
  perform set_config('PKG_LIST_SELECTLUNA.vExtra2'   , (Coalesce(p_Extra2, 0) = 1)::varchar ,false);
  perform set_config('PKG_LIST_SELECTLUNA.vExtra3'   , (Coalesce(p_Extra3, 0) = 1)::varchar ,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectlunaan_datafin</obj_name>
  <obj_hashval>7d2a3336f7ec1f39e692b4f2c5d4ecd3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectlunaan_datafin()
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 15.09.2020
  RETURN current_setting ('PKG_LIST_SELECTLUNAAN.vDataFin', true);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectlunaan_dataini</obj_name>
  <obj_hashval>3e0a6662b1fe4556617a15926a67bfac</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectlunaan_dataini()
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 15.09.2020
  return current_setting ('PKG_LIST_SELECTLUNAAN.vDataIni', true);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectlunaan_lunastart</obj_name>
  <obj_hashval>ea9ecfd55f30ace92864f7db81534d55</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectlunaan_lunastart()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
   return current_setting('PKG_LIST_SELECTLUNAAN.vLunaStart', true)::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectlunaan_lunastop</obj_name>
  <obj_hashval>4804334a64921219cb147fa3302db37e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectlunaan_lunastop()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 26.08.2020
  return current_setting('PKG_LIST_SELECTLUNAAN.vLunaStop', true)::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectlunaan_optiunea1</obj_name>
  <obj_hashval>254f5e16013ed9b4d317fd265032efc7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectlunaan_optiunea1()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 15.09.2020
  RETURN current_setting ('PKG_LIST_SELECTLUNAAN.vOpt1', true)::NUMERIC = 1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectlunaan_optiunea2</obj_name>
  <obj_hashval>362939918dd678bda23b6861a813b63e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectlunaan_optiunea2()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 15.09.2020
  RETURN current_setting ('PKG_LIST_SELECTLUNAAN.vOpt2', true)::NUMERIC = 1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectlunaan_setparams</obj_name>
  <obj_hashval>dd7fbfb21967821a5aa1409dff7afc6d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectlunaan_setparams(p_lunastart numeric, p_lunastop numeric, popt1 numeric, popt2 numeric, pallx numeric, pcodjob1 numeric, pcurs numeric, pally numeric, pdataini character varying, pdatafin character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vDataS date;
  vDataF date;
begin
  perform set_config('PKG_LIST_SELECTLUNAAN.vLunaStart', p_LunaStart::varchar, false);
  perform set_config('PKG_LIST_SELECTLUNAAN.vLunaStop',  p_LunaStop::varchar, false);
  if COALESCE(pCodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(pCodJob1, vDataS, vDataF, current_setting('PKG_LIST_SELECTLUNAAN.vLunaStart', true)::numeric, current_setting('PKG_LIST_SELECTLUNAAN.vLunaStop', true)::numeric);
  END IF;
  perform set_config('PKG_LIST_SELECTLUNAAN.vOpt1',    pOpt1::varchar,    false);
  perform set_config('PKG_LIST_SELECTLUNAAN.vOpt2',    pOpt2::varchar,    false);
  perform set_config('PKG_LIST_SELECTLUNAAN.vAllX',    paLLX::varchar,    false);
  perform set_config('PKG_LIST_SELECTLUNAAN.vAllY',    paLLy::varchar,    false);
  perform set_config('PKG_LIST_SELECTLUNAAN.vCurs',    pCurs::varchar,    false);
  perform set_config('PKG_LIST_SELECTLUNAAN.vDataIni', pDataini::varchar, false);
  perform set_config('PKG_LIST_SELECTLUNAAN.vDataFin', pDataFin::varchar, false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectper_datafin</obj_name>
  <obj_hashval>f2c2f9a5ffb5ccab932aaab277d704b8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectper_datafin()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 09.09.2020
  return to_date(current_setting ('PKG_LIST_SELECTPER.vDataFin', true),'dd.mm.yyyy');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectper_dataini</obj_name>
  <obj_hashval>f826837f5062d6c295708fe75517b625</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectper_dataini()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 09.09.2020
  return to_date(current_setting ('PKG_LIST_SELECTPER.vDataIni', true),'dd.mm.yyyy');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectper_setparams</obj_name>
  <obj_hashval>c0cb80e95a23b8e5939de75c5a0f3b35</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectper_setparams(pdataini character varying, pdatafin character varying, ptoateart numeric DEFAULT 1, ptoategest numeric DEFAULT 1, pdupadata numeric DEFAULT 1, plunaanini numeric DEFAULT 0, plunaanfin numeric DEFAULT 0, paduserii numeric DEFAULT 1, pcodjob1 numeric DEFAULT 0, ptipper numeric DEFAULT 0, pinfonp numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vDataIni   date;
  vDataFin   date;
  vToateArt  NUMERIC;
  vToateGest NUMERIC;
  vDupaData  NUMERIC;
  vLunaAnIni NUMERIC;
  vLunaAnFin NUMERIC;
  bAduSerii  NUMERIC;
  vTipPer    NUMERIC;
  aAn        NUMERIC;
  aLuna      NUMERIC;
  bInfoNP    NUMERIC;
BEGIN
  --Adina 12.04.2021 - sinc.Oracle din 10.04.2021 - add pinfonp
  --Florin 06.08.2020
  --Florin 04.12.2020 - fixat #41424
  vDataIni    := to_date(pDataIni,'dd.mm.yyyy');
  vDataFin    := to_date(pDataFin,'dd.mm.yyyy');
  vToateArt   := pToateArt;
  vToateGest  := pToateGest;
  vDupaData   := pDupaData;
  vLunaAnIni  := COALESCE(pLunaAnIni,0);
  vLunaAnFin  := COALESCE(pLunaAnFin,0);
  bAduSerii   := pAduSerii;
  bInfoNP     := COALESCE(pInfoNP,0);

  IF COALESCE(pCodJob1,0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(pCodJob1,vDataIni,vDataFin,vLunaAnIni,vLunaAnFin);
  END IF;

  vTipPer     := pTipPer;
  IF vDupaData = 0 THEN
    IF trunc(vLunaAnIni/12) = vLunaAnIni/12 THEN
      aAn := trunc(vLunaAnIni/12) - 1;
      aLuna := 12;
    ELSE
      aAn := trunc(vLunaAnIni/12);
      aLuna := trunc(vLunaAnIni - trunc(vLunaAnIni/12)*12);
    END IF;

    vDataIni := to_date('01.'||LPAD(aLuna::varchar,2,'0')||'.'||aAn::varchar, 'dd.mm.yyyy');

    IF trunc(vLunaAnFin/12) = vLunaAnFin/12 THEN
      aAn := trunc(vLunaAnFin/12) - 1;
      aLuna := 12;
    ELSE
      aAn := trunc(vLunaAnFin/12);
      aLuna := trunc(vLunaAnFin - trunc(vLunaAnFin/12)*12);
    END IF;

    vDataFin := last_day(to_date('01.'||LPAD(aLuna::varchar,2,'0')||'.'||aAn::varchar, 'dd.mm.yyyy'));
  END IF;

  PERFORM set_config('PKG_LIST_SELECTPER.vDataIni'   , to_char(vDataIni, 'dd.mm.yyyy'), FALSE);
  PERFORM set_config('PKG_LIST_SELECTPER.vDataFin'   , to_char(vDataFin, 'dd.mm.yyyy'), FALSE);
  PERFORM set_config('PKG_LIST_SELECTPER.vToateArt'  , vToateArt ::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTPER.vToateGest' , vToateGest::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTPER.vDupaData'  , vDupaData ::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTPER.vLunaAnIni' , vLunaAnIni::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTPER.vLunaAnFin' , vLunaAnFin::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTPER.bAduSerii'  , bAduSerii ::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTPER.vTipPer'    , vTipPer::varchar   , FALSE);
  PERFORM set_config('PKG_LIST_SELECTPER.bInfoNP'    , bInfoNP::varchar   , FALSE);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectper_setparams_vechi</obj_name>
  <obj_hashval>58f172a51eb16e474ebb741577940779</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectper_setparams_vechi(pdataini character varying, pdatafin character varying, ptoateart numeric, ptoategest numeric, pdupadata numeric, plunaanini numeric, plunaanfin numeric, paduserii numeric, pcodjob1 numeric, ptipper numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vDataIni   date;
  vDataFin   date;
  vToateArt  NUMERIC;
  vToateGest NUMERIC;
  vDupaData  NUMERIC;
  vLunaAnIni NUMERIC;
  vLunaAnFin NUMERIC;
  bAduSerii  NUMERIC;
  vTipPer    NUMERIC;
  aAn        NUMERIC;
  aLuna      NUMERIC;
BEGIN
  --Florin 06.08.2020
  --Florin 04.12.2020 - fixat #41424
  vDataIni    := to_date(pDataIni,'dd.mm.yyyy');
  vDataFin    := to_date(pDataFin,'dd.mm.yyyy');
  vToateArt   := pToateArt;
  vToateGest  := pToateGest;
  vDupaData   := pDupaData;
  vLunaAnIni  := COALESCE(pLunaAnIni,0);
  vLunaAnFin  := COALESCE(pLunaAnFin,0);
  bAduSerii   := pAduSerii;

  IF COALESCE(pCodJob1,0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(pCodJob1,vDataIni,vDataFin,vLunaAnIni,vLunaAnFin);
  END IF;

  vTipPer     := pTipPer;
  IF vDupaData = 0 THEN
    IF trunc(vLunaAnIni/12) = vLunaAnIni/12 THEN
      aAn := trunc(vLunaAnIni/12) - 1;
      aLuna := 12;
    ELSE
      aAn := trunc(vLunaAnIni/12);
      aLuna := trunc(vLunaAnIni - trunc(vLunaAnIni/12)*12);
    END IF;

    vDataIni := to_date('01.'||LPAD(aLuna::varchar,2,'0')||'.'||aAn::varchar, 'dd.mm.yyyy');

    IF trunc(vLunaAnFin/12) = vLunaAnFin/12 THEN
      aAn := trunc(vLunaAnFin/12) - 1;
      aLuna := 12;
    ELSE
      aAn := trunc(vLunaAnFin/12);
      aLuna := trunc(vLunaAnFin - trunc(vLunaAnFin/12)*12);
    END IF;

    vDataFin := last_day(to_date('01.'||LPAD(aLuna::varchar,2,'0')||'.'||aAn::varchar, 'dd.mm.yyyy'));
  END IF;

  PERFORM set_config('PKG_LIST_SELECTPER.vDataIni'   , to_char(vDataIni, 'dd.mm.yyyy'), FALSE);
  PERFORM set_config('PKG_LIST_SELECTPER.vDataFin'   , to_char(vDataFin, 'dd.mm.yyyy'), FALSE);
  PERFORM set_config('PKG_LIST_SELECTPER.vToateArt'  , vToateArt ::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTPER.vToateGest' , vToateGest::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTPER.vDupaData'  , vDupaData ::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTPER.vLunaAnIni' , vLunaAnIni::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTPER.vLunaAnFin' , vLunaAnFin::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTPER.bAduSerii'  , bAduSerii ::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTPER.vTipPer'    , vTipPer   ::varchar, FALSE);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectperioada_dataorafin</obj_name>
  <obj_hashval>32b75d9367452018327bb99547c80018</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectperioada_dataorafin()
 RETURNS timestamp without time zone
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.09.2020
  RETURN to_timestamp ( current_setting ('PKG_LIST_SELECTPERIOADA.vDataOraFin', true),'dd.mm.yyyy hh24:mi');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectperioada_dataoraini</obj_name>
  <obj_hashval>88367cd78e491ba65fb4a01c709dbad8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectperioada_dataoraini()
 RETURNS timestamp without time zone
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.07.2023
  --Bogdan 10.09.2020
  RETURN to_timestamp ( current_setting ('PKG_LIST_SELECTPERIOADA.vDataOraIni', true),'dd.mm.yyyy hh24:mi');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectperioada_setparams</obj_name>
  <obj_hashval>cb8ff107ba60cfebfb8b4c4a0381a83d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectperioada_setparams(pdupadata numeric, pdataini character varying, pdatafin character varying, panlunaini numeric, panlunafin numeric, popt1 numeric, popt2 numeric, pallx numeric, pcodjob1 numeric, pdataoraini character varying, pdataorafin character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  vDataS date;
  vDataF date;
BEGIN
  --Adina 03 august 2020
  perform set_config('PKG_LIST_SELECTPERIOADA.vDupaData', COALESCE(pDupaData,1)::varchar, false);
  perform set_config('PKG_LIST_SELECTPERIOADA.vDataIni', pDataIni, false);
  perform set_config('PKG_LIST_SELECTPERIOADA.vDataFin', pDataFin, false);
  perform set_config('PKG_LIST_SELECTPERIOADA.vAnLunaIni', pAnLunaIni::varchar, false);
  perform set_config('PKG_LIST_SELECTPERIOADA.vAnLunaFin', pAnLunaFin::varchar, false);
  IF  COALESCE(pCodJob1, 0) &gt; 0
  THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(pCodJob1, current_setting('PKG_LIST_SELECTPERIOADA.vDataIni', true), current_setting('PKG_LIST_SELECTPERIOADA.vDataFin', true),
      current_setting('PKG_LIST_SELECTPERIOADA.vAnLunaIni', true)::numeric, current_setting('PKG_LIST_SELECTPERIOADA.vAnLunaFin', true)::numeric);
  END IF;
  perform set_config('PKG_LIST_SELECTPERIOADA.vOpt1', COALESCE(pOpt1,1)::varchar, false);
  perform set_config('PKG_LIST_SELECTPERIOADA.vOpt2', COALESCE(pOpt2,1)::varchar, false);
  perform set_config('PKG_LIST_SELECTPERIOADA.vAllX', COALESCE(pAllX,1)::varchar, false);
  perform set_config('PKG_LIST_SELECTPERIOADA.vDataOraIni', pDataOraIni, false);
  perform set_config('PKG_LIST_SELECTPERIOADA.vDataOraFin', pDataOraFin, false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscad_centralizat</obj_name>
  <obj_hashval>bfa6789a88202e7ef9a31b62866e9a87</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscad_centralizat(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_LIST_SELECTSCAD.vCentralizat', true)::numeric);
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscad_dataini</obj_name>
  <obj_hashval>736c1be765181d1dd0f565e38554cb22</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscad_dataini(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  to_date( (current_setting('PKG_LIST_SELECTSCAD.vDataIni', true)), 'DD.MM.YYYY');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscad_datascad</obj_name>
  <obj_hashval>4b2bdf7102b3c0fcfb41f8882c7808a8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscad_datascad(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  to_date( (current_setting('PKG_LIST_SELECTSCAD.vDataScad', true)), 'DD.MM.YYYY');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscad_datavfin</obj_name>
  <obj_hashval>11d1e8a418b0fb040ced37c579659b52</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscad_datavfin(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_LIST_SELECTSCAD.vdataVScad', true)::character varying);
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscad_datavini</obj_name>
  <obj_hashval>72e292fe179cddd04a4e354f9c179edc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscad_datavini(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_LIST_SELECTSCAD.vDataVINI', true)::character varying);
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscad_extra2</obj_name>
  <obj_hashval>6fde4fb9fa89c53af7f78dc4867e5823</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscad_extra2(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_LIST_SELECTSCAD.vExtra2', true)::boolean);
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscad_extra3</obj_name>
  <obj_hashval>c3985b68b78ee56f99dddac05e8cbaf2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscad_extra3(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_LIST_SELECTSCAD.vExtra3', true)::boolean);
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscad_farapret</obj_name>
  <obj_hashval>9a0a2b270d6f832686d93460b175addf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscad_farapret(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_LIST_SELECTSCAD.vFaraPret', true)::boolean);
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscad_fararezinventar</obj_name>
  <obj_hashval>88dca141b25e76c9a231f62de8e366b9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscad_fararezinventar(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_LIST_SELECTSCAD.vFaraRezInv', true)::boolean);
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscad_lunafin</obj_name>
  <obj_hashval>664dbafa13419b22c73436f4ceb2042f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscad_lunafin(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_LIST_SELECTSCAD.vLunaFIN', true)::numeric);
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscad_lunaini</obj_name>
  <obj_hashval>da6251d2045db2664afed852b1185505</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscad_lunaini(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_LIST_SELECTSCAD.vLunaINI', true)::NUMERIC);
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscad_pervanz</obj_name>
  <obj_hashval>86717dea1b8f50473f992fbcb275077f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscad_pervanz(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_LIST_SELECTSCAD.vPerVanz', true)::boolean);
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscad_setimana</obj_name>
  <obj_hashval>a3cd0458c44fef59c1f3c6f5c41b942e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscad_setimana(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_LIST_SELECTSCAD.vSetimana', true)::numeric);
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscad_setparams</obj_name>
  <obj_hashval>4dcb11f88eded788a916331d36bda2ee</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscad_setparams(ptoategest integer, ptoateioart integer, pfarapret integer, pdataini character varying, pdatascad character varying, plunaini numeric, plunafin numeric, pcentralizat numeric, pextra1 integer, pextra2 integer, ptipnecesar numeric, ppervanz integer, pdatavini character varying, pdatavscad character varying, pfararezinv integer, pcodjob1 numeric, psetimana numeric, pmod numeric, pextra3 integer)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xALS NUMERIC;
  xALF NUMERIC;
BEGIN
  --Adina iulie 2020
  perform set_config('PKG_LIST_SELECTSCAD.vToateGest'  , Coalesce( pToateGest, 1)::varchar , false);
  perform set_config('PKG_LIST_SELECTSCAD.vToateIoart' , Coalesce( pToateIoart, 1)::varchar, false);
  perform set_config('PKG_LIST_SELECTSCAD.vFaraPret'   , Coalesce( pFaraPret, 0)::varchar  , false);
  perform set_config('PKG_LIST_SELECTSCAD.vExtra1'     , Coalesce( pExtra1, 0)::varchar    , false);
  perform set_config('PKG_LIST_SELECTSCAD.vExtra2'     , Coalesce( pExtra2, 0)::varchar    , false);
  perform set_config('PKG_LIST_SELECTSCAD.vExtra3'     , Coalesce( pExtra3, 0)::varchar    , false);
  perform set_config('PKG_LIST_SELECTSCAD.vPerVanz'    , Coalesce( pFaraRezInv, 0)::varchar, false);
  perform set_config('PKG_LIST_SELECTSCAD.vFaraRezInv' , Coalesce( pFaraRezInv, 0)::varchar, false);
  perform set_config('PKG_LIST_SELECTSCAD.vDataIni'    ,pDataIni                           , false);
  perform set_config('PKG_LIST_SELECTSCAD.vDataScad'   ,pDataScad                          , false);
  perform set_config('PKG_LIST_SELECTSCAD.vLunaIni'    ,pLunaIni::varchar                  , false);
  perform set_config('PKG_LIST_SELECTSCAD.vLunaFin'    ,pLunaFin::varchar                  , false);
  perform set_config('PKG_LIST_SELECTSCAD.vCentralizat',pCentralizat::varchar              , false);
  perform set_config('PKG_LIST_SELECTSCAD.vTipNecesar' ,Coalesce( pTipNecesar, 0)::varchar , false);
  perform set_config('PKG_LIST_SELECTSCAD.vDataVIni'   ,pDataVIni                          , false);
  perform set_config('PKG_LIST_SELECTSCAD.vDataVScad'  ,pDataVScad                         , false);

  IF  COALESCE( pCodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC( pCodJob1, (current_setting('PKG_LIST_SELECTSCAD.vDataIni', true))::varchar,
      (current_setting('PKG_LIST_SELECTSCAD.vDataScad', true))::varchar, xALS, xALF);
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC( pCodJob1, (current_setting('PKG_LIST_SELECTSCAD.vDataVIni', true))::varchar,
      (current_setting('PKG_LIST_SELECTSCAD.vDataVScad', true))::varchar, xALS, xALF);
  END IF;

  perform set_config('PKG_LIST_SELECTSCAD.vSetimana',COALESCE( pSetimana, 0)::varchar, false);
  perform set_config('PKG_LIST_SELECTSCAD.vMod'     ,COALESCE( pMod,0)::varchar      , false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscad_setparamsxxx</obj_name>
  <obj_hashval>2d635eee351f075f23ea7378b1d1fcbf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscad_setparamsxxx(ptoategest numeric, ptoateioart numeric, pfarapret numeric, pdataini character varying, pdatascad character varying, plunaini numeric, plunafin numeric, pcentralizat numeric, pextra1 numeric, pextra2 numeric, ptipnecesar numeric, ppervanz numeric, pdatavini character varying, pdatavscad character varying, pfararezinv numeric, pcodjob1 numeric, psetimana numeric, pmod numeric, pextra3 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xALS NUMERIC;
  xALF NUMERIC;
BEGIN
  --Adina iulie 2020
  perform set_config('PKG_LIST_SELECTSCAD.vToateGest', Coalesce( trunc(pToateGest), 1)::varchar, false);
  perform set_config('PKG_LIST_SELECTSCAD.vToateIoart', Coalesce( trunc(pToateIoart), 1)::varchar, false);
  perform set_config('PKG_LIST_SELECTSCAD.vFaraPret', Coalesce( trunc(pFaraPret), 0)::varchar, false);
  perform set_config('PKG_LIST_SELECTSCAD.vExtra1', Coalesce( trunc(pExtra1), 0)::varchar, false);
  perform set_config('PKG_LIST_SELECTSCAD.vExtra2', Coalesce( trunc(pExtra2), 0)::varchar, false);
  perform set_config('PKG_LIST_SELECTSCAD.vExtra3', Coalesce( trunc(pExtra3), 0)::varchar, false);
  perform set_config('PKG_LIST_SELECTSCAD.vPerVanz', Coalesce( trunc(pFaraRezInv), 0)::varchar, false);
  perform set_config('PKG_LIST_SELECTSCAD.vFaraRezInv', Coalesce( trunc(pFaraRezInv), 0)::varchar, false);
  perform set_config('PKG_LIST_SELECTSCAD.vDataIni',pDataIni, false);
  perform set_config('PKG_LIST_SELECTSCAD.vDataScad',pDataScad, false);
  perform set_config('PKG_LIST_SELECTSCAD.vLunaIni',pLunaIni::varchar, false);
  perform set_config('PKG_LIST_SELECTSCAD.vLunaFin',pLunaFin::varchar, false);
  perform set_config('PKG_LIST_SELECTSCAD.vCentralizat',pCentralizat::varchar, false);
  perform set_config('PKG_LIST_SELECTSCAD.vTipNecesar',Coalesce( pTipNecesar, 0)::varchar, false);
  perform set_config('PKG_LIST_SELECTSCAD.vDataVIni',pDataVIni,false);
  perform set_config('PKG_LIST_SELECTSCAD.vDataVScad',pDataVScad,false);
  IF  COALESCE( pCodJob1, 0) &gt; 0
  THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC( pCodJob1, (current_setting('PKG_LIST_SELECTSCAD.vDataIni', true))::varchar,
      (current_setting('PKG_LIST_SELECTSCAD.vDataScad', true))::varchar, xALS, xALF);
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC( pCodJob1, (current_setting('PKG_LIST_SELECTSCAD.vDataVIni', true))::varchar,
      (current_setting('PKG_LIST_SELECTSCAD.vDataVScad', true))::varchar, xALS, xALF);
  END IF;
  perform set_config('PKG_LIST_SELECTSCAD.vSetimana',COALESCE( pSetimana, 0)::varchar, false);
  perform set_config('PKG_LIST_SELECTSCAD.vMod',COALESCE( pMod,0)::varchar, false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscad_tipnecesar</obj_name>
  <obj_hashval>b15634f4b836d7554f34c81790230cd4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscad_tipnecesar(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_LIST_SELECTSCAD.vTipNecesar', true)::numeric);
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscad_toategest</obj_name>
  <obj_hashval>3c98f1045658f0b24f10cebaf2a683ca</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscad_toategest(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_LIST_SELECTSCAD.vToateGest', true)::boolean);
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscad_toateioart</obj_name>
  <obj_hashval>d8e9ae2a9af1b054d49cc41b8070a168</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscad_toateioart(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_LIST_SELECTSCAD.vToateIoart', true)::boolean);
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscadentar_calcadaosdoc</obj_name>
  <obj_hashval>055ceed840776af7112764f1dbe9647b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscadentar_calcadaosdoc()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.09.2020
  return current_setting ('PKG_LIST_SELECTSCADENTAR.g_AdaosDoc', true) :: boolean;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscadentar_calcdisctermen</obj_name>
  <obj_hashval>63243e0a1556f2fefdbc85da6e6a79cc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscadentar_calcdisctermen()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.09.2020
  return current_setting ('PKG_LIST_SELECTSCADENTAR.g_DiscTermen', true)::boolean;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscadentar_cond_subunit</obj_name>
  <obj_hashval>7fabf591025e7929b259b7035074aaa1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscadentar_cond_subunit(ptabla character varying DEFAULT NULL::character varying, pcoloana character varying DEFAULT 'SUBUNITATEA'::character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vSubunit numeric;
BEGIN
  --Stef 08.08.2022
  IF current_setting('PKG_LIST_SELECTSCADENTAR.g_CumulatFirma', true)::boolean THEN
    vSubunit := 0;
  END IF;
  RETURN PKG_LIST_BASE_UTILS_COND_SUBUNIT(pTabla, pColoana, NULL, vSubunit);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscadentar_cutranzincurs</obj_name>
  <obj_hashval>f18af372048e1f3f45937239614b9da1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscadentar_cutranzincurs()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.09.2020
  return current_setting ('PKG_LIST_SELECTSCADENTAR.g_TranzInCurs', true)::boolean;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscadentar_dataref</obj_name>
  <obj_hashval>ccfc625377274e83ee288167fc7032f6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscadentar_dataref()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.09.2020
  return to_date(current_setting ('PKG_LIST_SELECTSCADENTAR.g_data_ref', true),'dd.mm.yyyy');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscadentar_datarest</obj_name>
  <obj_hashval>8b2fac407d306f5a3054529a819521fa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscadentar_datarest()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.09.2020
  return to_date(current_setting ('PKG_LIST_SELECTSCADENTAR.g_data_rest', true),'dd.mm.yyyy');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscadentar_filtrudata</obj_name>
  <obj_hashval>19fa1fa96cc677a2e2c96d8b5fa12a52</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscadentar_filtrudata(slistacamp character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sDataRest VARCHAR := current_setting ('PKG_LIST_SELECTSCADENTAR.g_data_rest', true);
BEGIN
  --Stef 08.08.2022
  IF PKG_LIST_SELECTSCADENTAR_TipCalculRest() = 0
  THEN RETURN  '';
  ELSE RETURN ' AND COALESCE('||sListaCamp||',To_Date('''||sDataRest||''',''dd.mm.yyyy'')) &lt;= To_Date('''||sDataRest||''',''dd.mm.yyyy'') ';
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscadentar_inlei</obj_name>
  <obj_hashval>22c51be067a3afadd86c8ec456d28266</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscadentar_inlei()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.09.2020
  return current_setting ('PKG_LIST_SELECTSCADENTAR.g_Lei', true)::boolean;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscadentar_setparams</obj_name>
  <obj_hashval>760a501c81a9e6fc227986d4d1eebbf2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscadentar_setparams(p_dataref character varying, p_tranzincurs numeric DEFAULT 0, p_tcursfirma numeric DEFAULT 0, p_lei numeric DEFAULT 0, p_adaosdoc numeric DEFAULT 0, p_disctermen numeric DEFAULT 0, p_toateclasele numeric DEFAULT 1, p_totipart numeric DEFAULT 1, p_tipintarziere numeric DEFAULT 0, p_tipcalculrest numeric DEFAULT 0, p_datarest character varying DEFAULT NULL::character varying, p_tipperioada numeric DEFAULT 0, p_valsapt numeric DEFAULT 0, v_listid numeric DEFAULT 0, v_codjob1 numeric DEFAULT 0, p_cumulatfirma numeric DEFAULT 0, p_dettranzincurs numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  g_data_ref  DATE;
  g_data_rest DATE;
  g_TMPOk     BOOLEAN := TRUE;
BEGIN
  --Florin 17.05.2023 - sinc. Oracle (16.05.2023)
  --Stef 06.09.2022
  if UPPER(p_DataRef) IN ('SYSDATE', 'CURRENT_DATE')
  then g_data_ref    := current_date;
  else g_data_ref    := To_Date(p_DataRef ,'dd.mm.yyyy');
  end if;

  if UPPER(p_DataRest) IN ('SYSDATE', 'CURRENT_DATE')
  then g_data_rest   := current_date;
  else g_data_rest   := To_Date(p_DataRest,'dd.mm.yyyy');
  end if;
  IF (V_CODJOB1 &gt; 0) and (fnc_getvalconstantalucru('EDITVARJOB') &lt;&gt; '1') THEN
    SELECT adata INTO g_data_ref FROM PKG_ORA_LISTS_SET_DATA_DINAMIC(v_CodJob1, g_data_ref);
    g_data_rest   := g_data_ref;
  END IF;

  perform set_config('PKG_LIST_SELECTSCADENTAR.g_data_ref'      , To_char(g_data_ref ,'dd.mm.yyyy')                 , false);
  perform set_config('PKG_LIST_SELECTSCADENTAR.g_data_rest'     , To_char(g_data_rest,'dd.mm.yyyy')                 , false);
  perform set_config('PKG_LIST_SELECTSCADENTAR.g_CumulatFirma'  , (Coalesce(trunc(p_CumulatFirma ), 0) = 1)::varchar, false);
  perform set_config('PKG_LIST_SELECTSCADENTAR.g_TranzInCurs'   , (Coalesce(trunc(p_TranzInCurs  ), 0) = 1)::varchar, false);
  perform set_config('PKG_LIST_SELECTSCADENTAR.g_TCursFirma'    , (Coalesce(trunc(p_TCursFirma),    0) = 1)::varchar, false);
  perform set_config('PKG_LIST_SELECTSCADENTAR.g_Lei'           , (Coalesce(trunc(p_Lei),           0) = 1)::varchar, false);
  perform set_config('PKG_LIST_SELECTSCADENTAR.g_AdaosDoc'      , (Coalesce(trunc(p_AdaosDoc),      0) = 1)::varchar, false);
  perform set_config('PKG_LIST_SELECTSCADENTAR.g_DiscTermen'    , (Coalesce(trunc(p_DiscTermen),    0) = 1)::varchar, false);
  perform set_config('PKG_LIST_SELECTSCADENTAR.g_ToateClasele'  , (Coalesce(trunc(p_ToateClasele),  1) = 1)::varchar, false);
  perform set_config('PKG_LIST_SELECTSCADENTAR.g_TotiPart'      , (Coalesce(trunc(p_TotiPart),      0) = 1)::varchar, false);
  perform set_config('PKG_LIST_SELECTSCADENTAR.g_ValSapt'       , (Coalesce(trunc(p_ValSapt),       0) = 1)::varchar, false);
  perform set_config('PKG_LIST_SELECTSCADENTAR.g_TipIntarziere' , (Coalesce(trunc(p_TipIntarziere), 0))::varchar    , false);
  perform set_config('PKG_LIST_SELECTSCADENTAR.g_TipCalculRest' , (Coalesce(trunc(p_TipCalculRest), 0))::varchar    , false);
  perform set_config('PKG_LIST_SELECTSCADENTAR.g_TipPerioada'   , (Coalesce(trunc(p_TipPerioada),   0))::varchar    , false);
  perform set_config('PKG_LIST_SELECTSCADENTAR.g_DetTranzInCurs', (Coalesce(trunc(p_DetTranzInCurs ), 0) = 1)::varchar, false);

  CASE
    WHEN COALESCE(v_ListId, 0) IN (5, 250) THEN PERFORM PKG_LIST_BASE_SCADENTARCL_UmpleTmp(v_ListId);
    WHEN COALESCE(v_ListId, 0) IN (6, 251) THEN PERFORM PKG_LIST_BASE_SCADENTARF_UmpleTmp(v_ListId);
    ELSE g_TMPOk := FALSE;
  END CASE;
  perform set_config('PKG_LIST_SELECTSCADENTAR.g_TMPOk'        , g_TMPOk::varchar                                  , false);

  IF NOT g_TMPOk THEN
    perform set_config('PKG_LIST_SELECTSCADENTAR.g_ValSapt',(False)::varchar,false);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscadentar_tipcalculrest</obj_name>
  <obj_hashval>85288b0389dadbe137c95991e52b291d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscadentar_tipcalculrest()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.09.2020
  return current_setting ('PKG_LIST_SELECTSCADENTAR.g_TipCalculRest', true)::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscadentar_tipintarziere</obj_name>
  <obj_hashval>f166fd4273b7e7b6419c9f22a4a143b8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscadentar_tipintarziere()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.09.2020
  return current_setting ('PKG_LIST_SELECTSCADENTAR.g_TipIntarziere', true)::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscadentar_tipperioada</obj_name>
  <obj_hashval>a78102624f5550813f64f85479730047</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscadentar_tipperioada()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.09.2020
  return current_setting ('PKG_LIST_SELECTSCADENTAR.g_TipPerioada', true)::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscadentar_tmpok</obj_name>
  <obj_hashval>404af3b17f70a20db26ed180e68d3b8f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscadentar_tmpok()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.09.2020
  return current_setting ('PKG_LIST_SELECTSCADENTAR.g_TMPOk', true)::boolean;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscadentar_toateclasele</obj_name>
  <obj_hashval>fbd92939e1cf4c3efa906579630649e5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscadentar_toateclasele()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.09.2020
  return current_setting ('PKG_LIST_SELECTSCADENTAR.g_ToateClasele', true)::boolean;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscadentar_toateclaselenumber</obj_name>
  <obj_hashval>00d07201b85e8f5a265368d0a2ea9e87</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscadentar_toateclaselenumber(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 10 august 2020
  IF current_setting('PKG_LIST_SELECTSCADENTAR.g_ToateClasele', true)::boolean
  THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    WME_Result :=  0;
    RETURN;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscadentar_toateclaselenumber</obj_name>
  <obj_hashval>b5293c83b380898fb87f0165a86932ed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscadentar_toateclaselenumber()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Bogdan 10.09.2020
  IF pkg_list_selectscadentar_toateclasele()  THEN
    return  1;
  ELSE
    return  0;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscadentar_totipart</obj_name>
  <obj_hashval>2e3a758e3da28b06d555ef466c79706f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscadentar_totipart()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.09.2020
  return current_setting ('PKG_LIST_SELECTSCADENTAR.g_TotiPart', true)::boolean;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscadentar_totipartnumber</obj_name>
  <obj_hashval>a4999c95a992c6c0534fe62b91b0dca0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscadentar_totipartnumber()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Bogdan 10.09.2020
  IF pkg_list_selectscadentar_totipart()  THEN
    return  1;
  ELSE
    return  0;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscadentar_totipartnumber</obj_name>
  <obj_hashval>5a0f7c2e0bea19e5d474860e4b7f36c4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscadentar_totipartnumber(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 10 august 2020
  IF current_setting('PKG_LIST_SELECTSCADENTAR.g_TotiPart', true)::boolean
  THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    WME_Result :=  0;
    RETURN;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_areserii</obj_name>
  <obj_hashval>3f8012c20201c5684387b90cd13b86fb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_areserii(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  --Adina iulie 2020
WME_Result :=  (current_setting('PKG_LIST_SELFISAMAG.p_areSerii',true));
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_calculeaza_pmp</obj_name>
  <obj_hashval>a7660823e69eee0005a411be78e70355</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_calculeaza_pmp(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  --Adina iulie 2020
WME_Result :=  (current_setting('PKG_LIST_SELFISAMAG.p_calcPMP',true));
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_exclneconform</obj_name>
  <obj_hashval>af612897f093a7c40f42609a55b4edac</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_exclneconform(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  (current_setting('PKG_LIST_SELFISAMAG.p_ExclNeconform',true));
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_getdatafin</obj_name>
  <obj_hashval>ea2000a65f00790d6837bb5019c96c8d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_getdatafin()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN to_date( (current_setting('PKG_LIST_SELFISAMAG.p_dataFin',true)), 'dd.mm.yyyy');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_getdataini</obj_name>
  <obj_hashval>cf7ad7c05de19f82a63f6ccba6a7081e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_getdataini()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN to_date( (current_setting('PKG_LIST_SELFISAMAG.p_dataIni',true)), 'dd.mm.yyyy');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_getdataref</obj_name>
  <obj_hashval>ace6319665480e4643800408cdc5e2fe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_getdataref()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN to_date( (current_setting('PKG_LIST_SELFISAMAG.p_DataRef',true)), 'dd.mm.yyyy');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_getdatastoc</obj_name>
  <obj_hashval>c005e955e7262ebbd9c04e74bc73cd58</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_getdatastoc()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN to_date( (current_setting('PKG_LIST_SELFISAMAG.p_dataStoc',true)), 'dd.mm.yyyy');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_getinterval</obj_name>
  <obj_hashval>8dbbba1c728db03f7d286da37c165468</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_getinterval()
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN ' to_date(''' || (current_setting('PKG_LIST_SELFISAMAG.p_dataIni',true)) || ''',''dd/mm/yyyy'') AND to_date(''' || (current_setting('PKG_LIST_SELFISAMAG.p_dataFin',true)) || ''',''dd/mm/yyyy'') ';
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_getinterval</obj_name>
  <obj_hashval>dd45b7217e246e5930fa16dda594b28b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_getinterval(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  ' to_date(''' || (current_setting('PKG_LIST_SELFISAMAG.p_dataIni',true)) || ''',''dd/mm/yyyy'') AND to_date(''' || (current_setting('PKG_LIST_SELFISAMAG.p_dataFin',true)) || ''',''dd/mm/yyyy'') ';
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_getnumtoatecont</obj_name>
  <obj_hashval>7639932a1a5dfdff3f3c53a5d37b755a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_getnumtoatecont(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  iResult numeric := 0;
begin
  IF (current_setting('PKG_LIST_SELFISAMAG.p_flgTipCont',true)) THEN
    iResult := 1;
  END IF;

  WME_Result :=  iResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_getnumtoategest</obj_name>
  <obj_hashval>2840e62edb8fdbff574e71c9ab3be8ff</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_getnumtoategest(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  iResult numeric := 0;
begin
  IF (current_setting('PKG_LIST_SELFISAMAG.p_flgGest',true)) THEN
    iResult := 1;
  END IF;

  WME_Result :=  iResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_getp_areserii</obj_name>
  <obj_hashval>0fa5cb30b8c31877b283af4e64ce0e46</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_getp_areserii(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_SELFISAMAG.P_areSerii',true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_getp_calcpmp</obj_name>
  <obj_hashval>8a6792c025831d4e07fed9bdb78fc28e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_getp_calcpmp(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_SELFISAMAG.p_CalcPMP',true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_getp_datafin</obj_name>
  <obj_hashval>729a9ebb967565e99c6cd48d9553d233</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_getp_datafin(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_SELFISAMAG.p_dataFin',true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_getp_dataini</obj_name>
  <obj_hashval>20e3bcaaf883f041470af35e4df151ca</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_getp_dataini(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_SELFISAMAG.p_dataIni',true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_getp_dataref</obj_name>
  <obj_hashval>f1b14691801f89c5fecdbdb27649d60a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_getp_dataref(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_SELFISAMAG.p_DataRef',true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_getp_datastoc</obj_name>
  <obj_hashval>e94b95f194d64edd67a29fd96bf53ff7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_getp_datastoc(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_SELFISAMAG.p_dataStoc',true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_getp_flgart</obj_name>
  <obj_hashval>8c7c8f93b344ff554c1f5e719fc5b066</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_getp_flgart(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_SELFISAMAG.p_flgArt',true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_getp_flggest</obj_name>
  <obj_hashval>0ff214d2c41e8ec6087476f56a4f7c74</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_getp_flggest(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_SELFISAMAG.p_flgGest',true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_getp_flgtipcont</obj_name>
  <obj_hashval>242169262f6252fd5ca5d78cdfb03420</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_getp_flgtipcont(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_SELFISAMAG.p_flgTipCont',true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_getp_listid</obj_name>
  <obj_hashval>504118243b70ec58bafd1881ab25c874</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_getp_listid(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_LIST_SELFISAMAG.p_ListID',true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_getp_rezum1</obj_name>
  <obj_hashval>fdcb9877fe3f6e20068d63f9bf5b73c7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_getp_rezum1(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_SELFISAMAG.p_RezUM1',true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_getp_stoc0</obj_name>
  <obj_hashval>5477db86a6ba42c346494db6f3eba3b2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_getp_stoc0(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_SELFISAMAG.p_Stoc0',true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_getp_stoclazi</obj_name>
  <obj_hashval>0ee8977712c15adad46958227694fa76</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_getp_stoclazi(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_SELFISAMAG.p_StoclaZi',true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_inclnedes</obj_name>
  <obj_hashval>1f6c335823e1b8aa0ff78ad4887156cc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_inclnedes(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
  BEGIN
    WME_Result :=  (current_setting('PKG_LIST_SELFISAMAG.p_Nedes',true));
      RETURN;
  END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_isallgest</obj_name>
  <obj_hashval>7546b8518dd6a3d085008693109ea341</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_isallgest(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_LIST_SELFISAMAG.p_flgGest',true));
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_isalltipcont</obj_name>
  <obj_hashval>d186e29fcdb3fb67e55c6e9e60ed39b9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_isalltipcont(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_LIST_SELFISAMAG.p_flgTipCont',true));
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_istoateart</obj_name>
  <obj_hashval>5a62239f8e7b5f6cdaf1598d0d0d711d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_istoateart(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  iResult numeric := 0;
begin
  IF (current_setting('PKG_LIST_SELFISAMAG.p_flgArt',true)) THEN
    iResult := 1;
  END IF;

  WME_Result :=  iResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_listid</obj_name>
  <obj_hashval>6ef51b2eea7775977473f75168e90596</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_listid(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 1.09.2020
  WME_Result :=  current_setting('PKG_LIST_SELFISAMAG.p_ListID',true)::numeric;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_p_areserii</obj_name>
  <obj_hashval>34a6bf40c48853f480d8a55304cd4696</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_p_areserii(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_SELFISAMAG.P_areSerii',true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_p_calcpmp</obj_name>
  <obj_hashval>5ea1a3506272fa310223b9b6c61a1e3b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_p_calcpmp(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_SELFISAMAG.p_CalcPMP',true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_p_datafin</obj_name>
  <obj_hashval>c84cc6434f1bb9c4f956ed999457eea8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_p_datafin(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_SELFISAMAG.p_dataFin',true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_p_dataini</obj_name>
  <obj_hashval>d138c3eda92d787a0bce648004caa524</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_p_dataini(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_SELFISAMAG.p_dataIni',true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_p_dataref</obj_name>
  <obj_hashval>8257785a1dc85d622c44a2a2cc9d29f1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_p_dataref(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_SELFISAMAG.p_DataRef',true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_p_datastoc</obj_name>
  <obj_hashval>dfbdb69a4aacd905d1eae459cd97f969</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_p_datastoc(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_SELFISAMAG.p_dataStoc',true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_p_flgart</obj_name>
  <obj_hashval>0e745d70351540588cc09db6a4348ba5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_p_flgart(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_SELFISAMAG.p_flgArt',true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_p_flggest</obj_name>
  <obj_hashval>7dc6da05a640705c98e0f2054ede9e33</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_p_flggest(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_SELFISAMAG.p_flgGest',true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_p_flgtipcont</obj_name>
  <obj_hashval>d7c0bc198968e7335e1c49699ae22add</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_p_flgtipcont(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_SELFISAMAG.p_flgTipCont',true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_p_stoc0</obj_name>
  <obj_hashval>955203ea89e5f5f73f807b6d6b19c8b2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_p_stoc0(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_SELFISAMAG.p_Stoc0',true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_p_stoclazi</obj_name>
  <obj_hashval>c1aaa1c72feadcf722eacf7268e48b90</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_p_stoclazi(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_SELFISAMAG.p_StoclaZi',true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_rezum1</obj_name>
  <obj_hashval>da6a1f27a7ccd895bcf4b489ffe6f68a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_rezum1(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_LIST_SELFISAMAG.p_RezUM1',true));
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_setallparams</obj_name>
  <obj_hashval>ac5017fead94a282bdfcb5276b6b5d7c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_setallparams(v_dataini character varying, v_datafin character varying, v_datastoc character varying, v_flggest numeric, v_flgtipcont numeric, v_flgart numeric, v_stoclazi numeric DEFAULT 0, v_areserii numeric DEFAULT 0, v_calcpmp numeric DEFAULT 0, v_dataref character varying DEFAULT NULL::character varying, v_stoc0 numeric DEFAULT 0, v_codjob1 numeric DEFAULT 0, v_rezum1 numeric DEFAULT 0, v_listid numeric DEFAULT 0, v_exclneconform numeric DEFAULT 0, v_nedes numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
  p_dataIni  VARCHAR(15);
  p_dataFin  VARCHAR(15);
  p_dataStoc VARCHAR(15);
  p_DataRef  VARCHAR(15);
BEGIN
  --Stef 27.11.2024
  p_dataIni   := v_dataini;
  p_dataFin   := v_dataFin;
  p_dataStoc  := v_DataStoc;
  p_DataRef   := v_DataRef;

  IF  COALESCE( v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC( V_CODJOB1,p_dataIni,p_dataFin, xLunaAnIni,xLunaAnFin);
    p_DataStoc  := p_DataFin;
    p_DataRef   := p_DataFin;
  END IF;
  PERFORM PKG_ORA_LISTS_SET_INTERVAL_LISTARE(TO_DATE(p_dataIni,'DD.MM.YYYY'),TO_DATE(p_dataFin,'DD.MM.YYYY'));

  PERFORM set_config('PKG_LIST_SELFISAMAG.p_dataIni'      ,p_dataIni                                  ,false);
  PERFORM set_config('PKG_LIST_SELFISAMAG.p_dataFin'      ,p_dataFin                                  ,false);
  PERFORM set_config('PKG_LIST_SELFISAMAG.p_dataStoc'     ,p_dataStoc                                 ,false);
  PERFORM set_config('PKG_LIST_SELFISAMAG.p_DataRef'      ,p_DataRef                                  ,false);
  PERFORM set_config('PKG_LIST_SELFISAMAG.p_flgGest'      ,(COALESCE(v_flgGest,0)       = 1)::varchar, false);
  PERFORM set_config('PKG_LIST_SELFISAMAG.p_flgTipCont'   ,(COALESCE(v_flgTipCont,0)    = 1)::varchar, false);
  PERFORM set_config('PKG_LIST_SELFISAMAG.p_flgArt'       ,(COALESCE(v_flgArt,0)        = 1)::varchar, false);
  PERFORM set_config('PKG_LIST_SELFISAMAG.p_stocLaZi'     ,(COALESCE(v_StocLaZi,0)      = 0)::varchar, false);
  PERFORM set_config('PKG_LIST_SELFISAMAG.p_areSerii'     ,(COALESCE(v_areSerii,0)      = 1)::varchar, false);
  PERFORM set_config('PKG_LIST_SELFISAMAG.p_CalcPMP'      ,(COALESCE(v_CalcPMP,0)       = 1)::varchar, false);
  PERFORM set_config('PKG_LIST_SELFISAMAG.p_Stoc0'        ,(COALESCE(v_Stoc0,0)         = 1)::varchar, false);
  PERFORM set_config('PKG_LIST_SELFISAMAG.p_TipStocIni'   , COALESCE(v_Stoc0,0)             ::varchar, false);
  PERFORM set_config('PKG_LIST_SELFISAMAG.p_RezUM1'       ,(COALESCE(v_RezUM1,0)        = 1)::varchar, false);
  PERFORM set_config('PKG_LIST_SELFISAMAG.p_ListID'       , COALESCE(v_ListID,0)            ::varchar, false);
  PERFORM set_config('PKG_LIST_SELFISAMAG.p_ExclNeconform',(COALESCE(v_ExclNeconform,0) = 1)::varchar, false);
  PERFORM set_config('PKG_LIST_SELFISAMAG.p_Nedes'        ,(COALESCE(v_Nedes,0)         = 1)::varchar, false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_setp_areserii</obj_name>
  <obj_hashval>f485e94e2c04a2267c32fd0eab8c6a2d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_setp_areserii(ap_areserii boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_SELFISAMAG.P_areSerii',aP_areSerii,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_setp_calcpmp</obj_name>
  <obj_hashval>f10e7512c616b666457d82f28c91d812</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_setp_calcpmp(ap_calcpmp boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_SELFISAMAG.p_CalcPMP',ap_CalcPMP,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_setp_datafin</obj_name>
  <obj_hashval>e7868e981052c7a4813bd0fbfaf3722c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_setp_datafin(ap_datafin character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_SELFISAMAG.p_dataFin',ap_dataFin,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_setp_dataini</obj_name>
  <obj_hashval>ccc34230c79b8920721d500e379b1f0e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_setp_dataini(ap_dataini character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_SELFISAMAG.p_dataIni',ap_dataIni,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_setp_dataref</obj_name>
  <obj_hashval>51f4f66911c354da5266d88385b15b9a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_setp_dataref(ap_dataref character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_SELFISAMAG.p_DataRef',ap_DataRef,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_setp_datastoc</obj_name>
  <obj_hashval>06b7edabe6fcfd135c51a0b35ff264b6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_setp_datastoc(ap_datastoc character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_SELFISAMAG.p_dataStoc',ap_dataStoc,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_setp_flgart</obj_name>
  <obj_hashval>af5bd7eab7a778d76fc53014a1b1907c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_setp_flgart(ap_flgart boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_SELFISAMAG.p_flgArt',ap_flgArt,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_setp_rezum1</obj_name>
  <obj_hashval>786c03770b97b4251cb11857752e2165</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_setp_rezum1(ap_rezum1 boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_SELFISAMAG.p_RezUM1',ap_RezUM1,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_setp_stoc0</obj_name>
  <obj_hashval>e3e10f6acf37e3fb1449ddd05c702c7b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_setp_stoc0(ap_stoc0 boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_SELFISAMAG.p_Stoc0',ap_Stoc0,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_stoclazi</obj_name>
  <obj_hashval>ac8952caecddea462b74b3f64cf04a16</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_stoclazi(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_LIST_SELFISAMAG.p_StoclaZi',true));
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisapers_anlunafin</obj_name>
  <obj_hashval>710bd671b90f0a00d00fd6e7b94e7366</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisapers_anlunafin(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  current_setting('PKG_LIST_SELFISAPERS.vAnLunaFin', true)::numeric;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisapers_anlunaini</obj_name>
  <obj_hashval>b3179a5d5de577201e20f87896d0a442</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisapers_anlunaini(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  current_setting('PKG_LIST_SELFISAPERS.vAnLunaIni', true)::numeric;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisapers_gettipcont</obj_name>
  <obj_hashval>caacdc87b2dd37c034f5771fc8b64e84</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisapers_gettipcont()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sSelect varchar;
BEGIN
  --Adina 25 august 2020 - neterminata
  sSelect := '
  WITH RECURSIVE aa(iCont) AS (
    SELECT 2 iCont
    UNION ALL
    SELECT aa.iCont+1 FROM aa WHERE aa.iCont&lt;=12  ),
  crs_io AS
  (
    SELECT  DISTINCT CODIOPERS,
            CASE x.icont
               WHEN 2 THEN CONTAVANSDECONT
               WHEN 3 THEN CONTIMPUTATII
               WHEN 4 THEN CONTGARANTII
               WHEN 5 THEN CONTALTERETINERI
               WHEN 6 THEN CONTAVANS
               WHEN 7 THEN CONTLIKI
               WHEN 8 THEN CONTNERIDICATE
               WHEN 9 THEN CONTBOALA
               WHEN 10 THEN CONTPARTSAL
               WHEN 11 THEN CONTNATURA
               WHEN 12 THEN CONTECHIPAMENT
               WHEN 13 THEN CONTIMPOZIT
             END  CODCONT,
             CASE x.icont
               WHEN 2 THEN 1
               ELSE 0
           END  AVANSDECONT
    FROM  iopers1 io1
          CROSS JOIN (SELECT aa.iCont FROM aa ) x
  )
  SELECT  DISTINCT nc.codcont, coalesce(nc.simbol,'''') || '' - '' || coalesce(nc.den_cont,'''') DENUMIRE, crs_io.AVANSDECONT
  FROM   crs_io
        INNER JOIN ncont nc ON  nc.codcont = crs_io.codcont
  WHERE crs_io.codCont &lt;&gt; 0';

END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisapers_isallmon</obj_name>
  <obj_hashval>94d6064262dfdc01c49b9f1119730f50</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisapers_isallmon()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  return  current_setting('PKG_LIST_SELFISAPERS.vAllMon', true)::boolean;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisapers_isalltipc</obj_name>
  <obj_hashval>6fe9125be8ec481a7d13f7c0ced9fbbe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisapers_isalltipc()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  return  current_setting('PKG_LIST_SELFISAPERS.vAllTipC', true)::boolean;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisapers_isalltipcn</obj_name>
  <obj_hashval>b2d3e9ffddd3797aab4b094dc950c193</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisapers_isalltipcn()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 25 august 2020
  return current_setting('PKG_LIST_SELFISAPERS.vAllTipC', true)::boolean ;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisapers_issubunit</obj_name>
  <obj_hashval>e84a064f088585c144c25b1799d72949</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisapers_issubunit()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  return current_setting('PKG_LIST_SELFISAPERS.vSubunit', true)::boolean
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisapers_setparams</obj_name>
  <obj_hashval>0e4aafdd0a627dd130cd5e7ec1e211ae</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisapers_setparams(p_allmon numeric DEFAULT 1, p_alltipc numeric DEFAULT 1, p_anlunaini numeric DEFAULT NULL::numeric, p_anlunafin numeric DEFAULT NULL::numeric, p_codpers numeric DEFAULT 0, p_lei numeric DEFAULT 0, p_subunit numeric DEFAULT 1, v_codjob1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  dDataS date;
  dDataF date;
BEGIN
  --Adina 25 august 2020
  PERFORM set_config('PKG_LIST_SELFISAPERS.vAllMon'   ,(Coalesce(p_AllMon , 1) = 1)::varchar,false);
  PERFORM set_config('PKG_LIST_SELFISAPERS.vAllTipC'  ,(Coalesce(p_AllTipC, 1) = 1)::varchar,false);
  PERFORM set_config('PKG_LIST_SELFISAPERS.vAnLunaIni',(p_AnLunaIni)::varchar,false);
  PERFORM set_config('PKG_LIST_SELFISAPERS.vAnLunaFin',(p_AnLunaFin)::varchar,false);
  PERFORM set_config('PKG_LIST_SELFISAPERS.vCodPers'  ,(Coalesce(p_CodPers, 0))::varchar    ,false);
  PERFORM set_config('PKG_LIST_SELFISAPERS.vLei'      ,(Coalesce(p_Lei    , 0))::varchar    ,false);
  PERFORM set_config('PKG_LIST_SELFISAPERS.vSubunit'  ,(Coalesce(p_Subunit, 0) = 1)::varchar,false);

  IF  Coalesce(v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, dDataS, dDataF, current_setting('PKG_LIST_SELFISAPERS.vAnLunaIni', true)::numeric, current_setting('PKG_LIST_SELFISAPERS.vAnLunaFin', true)::numeric);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selinties_setparams</obj_name>
  <obj_hashval>b19ee4a471a894f62ccc746bdb303b21</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selinties_setparams(bobj numeric, pdupadata numeric, plista numeric, pum numeric, pdatas character varying, pdataf character varying, pextra1 numeric, pextra2 numeric, pextra3 numeric, pextra4 numeric, patrib1 numeric, v_codjob1 numeric, pseriifaracant numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
  sDataS     varchar;
  sDataF     varchar;
  vDataS     DATE;
  vDataF     DATE;
BEGIN
  --Florin 29.07.2020 -- probleme cu DataS / DataF
  --Florin 10.08.2020 -- adaugat vLista
  PERFORM set_config('PKG_LIST_SELINTIES.vToateArt'     , (Coalesce(bOBJ, 1) = 1)     ::varchar, false);
  PERFORM set_config('PKG_LIST_SELINTIES.vDupaData'     , (Coalesce(pDupaData, 0) = 1)::varchar, false);
  PERFORM set_config('PKG_LIST_SELINTIES.vExtra1'       , Coalesce(pExtra1, 0)        ::varchar, false);
  PERFORM set_config('PKG_LIST_SELINTIES.vExtra2'       , Coalesce(pExtra2, 0)        ::varchar, false);
  PERFORM set_config('PKG_LIST_SELINTIES.vExtra3'       , Coalesce(pExtra3, 0)        ::varchar, false);
  PERFORM set_config('PKG_LIST_SELINTIES.vExtra4'       , Coalesce(pExtra4, 0)        ::varchar, false);
  PERFORM set_config('PKG_LIST_SELINTIES.vUM'           , Coalesce(pUM, 0)            ::varchar, false);
  PERFORM set_config('PKG_LIST_SELINTIES.vLista'        , Coalesce(pLista, 0)         ::varchar, false);
  PERFORM set_config('PKG_LIST_SELINTIES.vAtrib1'       , Coalesce(pAtrib1, 0)        ::varchar, false);
  PERFORM set_config('PKG_LIST_SELINTIES.vSeriiFaraCant', pSeriiFaraCant              ::varchar, false);
  PERFORM set_config('PKG_LIST_SELINTIES.vDataS'        , pDataS                      ::varchar, false);
  PERFORM set_config('PKG_LIST_SELINTIES.vDataF'        , pdataF                      ::varchar, false);

  vDataS = fnc_current_setting_date('PKG_LIST_SELINTIES.vDataS');
  vDataF = fnc_current_setting_date('PKG_LIST_SELINTIES.vDataF');
  xLunaAnIni := EXTRACT(YEAR FROM vDataS) * 12 + EXTRACT(MONTH FROM vDataS);
  xLunaAnFin := EXTRACT(YEAR FROM vDataF) * 12 + EXTRACT(MONTH FROM vDataF);

  IF COALESCE(v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, vDataS, vDataF, xLunaAnIni, xLunaAnFin);
  END IF;

  sDataS := 'TO_DATE(''' ||  To_char(vDataS,'dd.mm.yyyy') || ''',''dd.mm.yyyy'')';
  sDataF := 'TO_DATE(''' ||  To_char(vDataF,'dd.mm.yyyy') || ''',''dd.mm.yyyy'')';

  IF pDupaData = 1 AND vDataS = vDataF THEN
    PERFORM set_config('PKG_LIST_SELINTIES.vPerioada', '= '|| sDataS, false);
  ELSIF pDupaData = 1 THEN
    PERFORM set_config('PKG_LIST_SELINTIES.vPerioada', 'BETWEEN ' || sDataS || ' AND ' || sDataF, false);
  ELSIF xLunaAnIni = xLunaAnFin THEN
    PERFORM set_config('PKG_LIST_SELINTIES.vPerioada', '= '|| xLunaAnIni::VARCHAR, false);
  ELSE
    PERFORM set_config('PKG_LIST_SELINTIES.vPerioada', 'BETWEEN '|| xLunaAnIni::VARCHAR || ' AND ' || xLunaAnFin::VARCHAR, false);
  END IF;

  PERFORM PKG_ORA_LISTS_SET_INTERVAL_LISTARE(vDataS, vDataF);

  IF plista = 3 THEN
    PERFORM PKG_LIST_BASE_IESIRI_BAGA_DINAMIC_COLS();
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_sellivrari_setparams</obj_name>
  <obj_hashval>d2cf7c55feaf8ca86a054334bac8a47e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_sellivrari_setparams(ptipdata numeric, pdatas character varying, pdataf character varying, pallgest numeric, pallart numeric, palldoc numeric, pum numeric, pextra1 numeric, pextra2 numeric, pextra3 numeric, pextra4 numeric, v_codjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
  sDataS     varchar;
  sDataF     varchar;
  vDataS     DATE;
  vDataF     DATE;
BEGIN
  --Florin 14.08.2020
  PERFORM set_config('PKG_LIST_SELLIVRARI.vToateGest', pallgest ::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELLIVRARI.vToateArt' , pallart  ::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELLIVRARI.vToateDoc' , palldoc  ::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELLIVRARI.vTipData'  , pTipData::varchar , FALSE);
  PERFORM set_config('PKG_LIST_SELLIVRARI.vDataS'    , pDataS            , FALSE);
  PERFORM set_config('PKG_LIST_SELLIVRARI.vDataF'    , pDataF            , FALSE);
  PERFORM set_config('PKG_LIST_SELLIVRARI.vUM'       , Coalesce(pUM, 0)::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELLIVRARI.vExtra1'   ,pExtra1::varchar          , FALSE);
  PERFORM set_config('PKG_LIST_SELLIVRARI.vExtra2'   ,pExtra2::varchar          , FALSE);
  PERFORM set_config('PKG_LIST_SELLIVRARI.vExtra3'   ,pExtra3::varchar          , FALSE);
  PERFORM set_config('PKG_LIST_SELLIVRARI.vExtra4'   ,pExtra4::varchar          , FALSE);
  vDataS = fnc_current_setting_date('PKG_LIST_SELLIVRARI.vDataS');
  vDataF = fnc_current_setting_date('PKG_LIST_SELLIVRARI.vDataF');
  xLunaAnIni := EXTRACT(YEAR FROM vDataS) * 12 + EXTRACT(MONTH FROM vDataS);
  xLunaAnFin := EXTRACT(YEAR FROM vDataF) * 12 + EXTRACT(MONTH FROM vDataF);

  IF COALESCE(v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, vDataS, vDataF, xLunaAnIni, xLunaAnFin);
  END IF;

  sDataS := 'TO_DATE(''' ||  To_char(vDataS,'dd.mm.yyyy') || ''',''dd.mm.yyyy'')';
  sDataF := 'TO_DATE(''' ||  To_char(vDataF,'dd.mm.yyyy') || ''',''dd.mm.yyyy'')';

  IF pTipData = 2 AND xLunaAnIni = xLunaAnFin THEN
    PERFORM set_config('PKG_LIST_SELLIVRARI.vPerioada', '= '|| xLunaAnIni, FALSE);
  ELSIF pTipData = 2 THEN
    PERFORM set_config('PKG_LIST_SELLIVRARI.vPerioada', 'BETWEEN ' || xLunaAnIni::VARCHAR || ' AND ' || xLunaAnFin::varchar, FALSE);
  ELSIF vDataS = vDataF THEN
    PERFORM set_config('PKG_LIST_SELLIVRARI.vPerioada', '= '|| sDataS, FALSE);
  ELSE
    PERFORM set_config('PKG_LIST_SELLIVRARI.vPerioada', 'BETWEEN '|| sDataS || ' AND ' || sDataF, FALSE);
  END IF;

  PERFORM PKG_ORA_LISTS_SET_INTERVAL_LISTARE(vDataS, vDataF);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selpart_setparam</obj_name>
  <obj_hashval>6cca16e74115f5b0f8e32a368a6ce92d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selpart_setparam(pallpart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_SELPART.gAllPart',pAllPart::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selpartart_anlunafin</obj_name>
  <obj_hashval>857a3ce15a1e1f862debc232a7a5a8b0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selpartart_anlunafin()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 08.09.2020
  return current_setting ('PKG_LIST_SELPARTART.gAnLunaFin', true) ::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selpartart_anlunaini</obj_name>
  <obj_hashval>b275a811046d312c2cdcdd2ea9e247ba</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selpartart_anlunaini()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 08.09.2020
  return current_setting ('PKG_LIST_SELPARTART.gAnLunaIni', true) ::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selpartart_isallart</obj_name>
  <obj_hashval>48b4a842de723b28c5e950b2afe2c7ec</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selpartart_isallart()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 08.09.2020
  RETURN current_setting ('PKG_LIST_SELPARTART.gAllArt', true)::numeric = 1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selpartart_isallpart</obj_name>
  <obj_hashval>e5385537641f9717ba707072a421dcb5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selpartart_isallpart()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 08.09.2020
  return current_setting ('PKG_LIST_SELPARTART.gAllPart', true)::numeric = 1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selpartart_setparam</obj_name>
  <obj_hashval>e3fd4ecf04a26f7b6a060e7b2bf7659a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selpartart_setparam(panlunaini numeric, panlunafin numeric, pallpart numeric, pallart numeric, pextra1 numeric DEFAULT 0, pextra2 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config ('PKG_LIST_SELPARTART.gAnLunaIni',pAnLunaIni::varchar,false);
  perform set_config ('PKG_LIST_SELPARTART.gAnLunaFin',pAnLunaFin::varchar,false);
  perform set_config ('PKG_LIST_SELPARTART.gAllPart'  ,Coalesce(pAllPart, 1)::varchar,false);
  perform set_config ('PKG_LIST_SELPARTART.gAllArt'   ,Coalesce(pAllArt,  1)::varchar,false);
  perform set_config ('PKG_LIST_SELPARTART.gExtra1'   ,Coalesce(pExtra1,  0)::varchar,false);
  perform set_config ('PKG_LIST_SELPARTART.gExtra2'   ,Coalesce(pExtra2,  0)::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selperagent_dataini</obj_name>
  <obj_hashval>3d9b2d1eae5f9547fd681aa3ed191a4f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selperagent_dataini()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.09.2020
  return to_date(current_setting ('PKG_LIST_SELPERAGENT.vDataIni', true),'dd.mm.yyyy');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selperagent_dupadata</obj_name>
  <obj_hashval>8e74e64c96f601bd65fc88c622d6fbf9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selperagent_dupadata()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.09.2020
  return current_setting ('PKG_LIST_SELPERAGENT.vDupaData', true)::numeric = 1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selperagent_lunaanfin</obj_name>
  <obj_hashval>d334b13f3ed6d7c564a91ef8258ae506</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selperagent_lunaanfin()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.09.2020
  return current_setting ('PKG_LIST_SELPERAGENT.vLunaAnFin', true)::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selperagent_setparams</obj_name>
  <obj_hashval>ba6f745fccefbd258ef8a4b34831f390</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selperagent_setparams(pdupadata numeric DEFAULT 1, pdataini character varying DEFAULT NULL::character varying, pdatafin character varying DEFAULT NULL::character varying, plunaanini numeric DEFAULT 0, plunaanfin numeric DEFAULT 0, pallagent numeric DEFAULT 1, v_codjob1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  vDataIni    date;
  vDataFin    date;
  sDataIni    varchar(10);
  sDataFin    varchar(10);
  vLunaAnIni  numeric;
  vLunaAnFin  numeric;
begin
  --Bogdan 10.09.2020
  perform set_config ('PKG_LIST_SELPERAGENT.vAllAgent',coalesce(pAllAgent,1)::varchar,false);
  perform set_config ('PKG_LIST_SELPERAGENT.vDupaData',coalesce(pDupaData,1)::varchar,false);

  vDataIni   := to_date(pDataIni,'dd.mm.yyyy');
  vDataFin   := to_date(pDataFin,'dd.mm.yyyy');
  vLunaAnIni := COALESCE (pLunaAnIni, 0);
  vLunaAnFin := COALESCE (pLunaAnFin, 0);

  IF COALESCE (v_CodJob1, 0) &gt; 0 THEN
    SELECT PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.adataini, PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.adatafin,
      PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.alunaanini , PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.alunaanfin
    from PKG_ORA_LISTS_SET_INTERVAL_DINAMIC (V_CODJOB1, vDataIni , vDataFin , vLunaAnIni, vLunaAnFin) into vDataIni , vDataFin , vLunaAnIni, vLunaAnFin;
  END IF;

  PERFORM PKG_ORA_LISTS_SET_INTERVAL_LISTARE (vDataIni , vDataFin);

  sDataIni   := to_char(vDataIni,'dd.mm.yyyy');
  sDataFin   := to_char(vDataFin,'dd.mm.yyyy');

  perform set_config ('PKG_LIST_SELPERAGENT.vDataIni',sDataIni,false);
  perform set_config ('PKG_LIST_SELPERAGENT.vDataIni',sDataFin,false);
  perform set_config ('PKG_LIST_SELPERAGENT.vLunaAnIni',vLunaAnIni ::varchar,false);
  perform set_config ('PKG_LIST_SELPERAGENT.vLunaAnFin',vLunaAnFin ::varchar,false);

end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selperagent_totiagentii</obj_name>
  <obj_hashval>06e823e58dedd6029148a501c8fa4d70</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selperagent_totiagentii()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.09.2020
  return current_setting ('PKG_LIST_SELPERAGENT.vAllAgent', true)::numeric = 1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selperart_setparams</obj_name>
  <obj_hashval>4859a4240b0dcf9a945a9dba5f1627cc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selperart_setparams(pdupadata numeric DEFAULT 1, pdataini character varying DEFAULT NULL::character varying, pdatafin character varying DEFAULT NULL::character varying, plunaanini numeric DEFAULT 0, plunaanfin numeric DEFAULT 0, pfiltruart numeric DEFAULT 0, pextra1 numeric DEFAULT 0, v_codjob1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 05 septembrie 2020
  perform set_config('PKG_LIST_SELPERART.vFiltruArt', (trunc(COALESCE(pFiltruArt, 0)))::varchar,  false);
  perform set_config('PKG_LIST_SELPERART.vDupaData' , (trunc(COALESCE(pDupaData,1)) = 1)::varchar,false);
  perform set_config('PKG_LIST_SELPERART.vDataIni'  , pDataIni,false);
  perform set_config('PKG_LIST_SELPERART.vDataFin'  , pDataFin,false);
  perform set_config('PKG_LIST_SELPERART.vLunaAnIni', (trunc(COALESCE(pLunaAnIni, 0)))::varchar,false);
  perform set_config('PKG_LIST_SELPERART.vLunaAnFin', (trunc(COALESCE(pLunaAnFin, 0)))::varchar,false);
  perform set_config('PKG_LIST_SELPERART.vExtra1'   , (trunc(COALESCE(pExtra1,0)) = 0)::varchar,false);

  IF  COALESCE(v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, current_setting('PKG_LIST_SELPERART.vDataIni', true), current_setting('PKG_LIST_SELPERART.vDataFin', true), current_setting('PKG_LIST_SELPERART.vLunaAnIni', true)::numeric, current_setting('PKG_LIST_SELPERART.vLunaAnFin', true)::numeric);
  END IF;

  PERFORM PKG_ORA_LISTS_SET_INTERVAL_LISTARE(to_date(current_setting('PKG_LIST_SELPERART.vDataIni', true),'dd.mm.yyyy'), to_date(current_setting('PKG_LIST_SELPERART.vDataFin', true),'dd.mm.yyyy'));
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selsitart_setparams</obj_name>
  <obj_hashval>0a0b5167cb0f457a71f8dd015c2e873f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selsitart_setparams(pfaradata numeric, pdatas character varying, pdataf character varying, ptoateart numeric, ptotipart numeric, ptoatedoc numeric, v_codjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
  sDataS     varchar := pDataS;
  sDataF     varchar := pDataF;
BEGIN
  --Florin 11.09.2020
  IF COALESCE(v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, sDataS, sDataF, xLunaAnIni, xLunaAnFin);
  END IF;

  IF pFaraData = 0 AND sDataS = sDataF THEN
    PERFORM set_config('PKG_LIST_SELSITART.vPerioada', ' = TO_DATE('''||sDataS||''',''DD.MM.YYYY'')', FALSE);
  ELSIF pFaraData = 0 THEN
    PERFORM set_config('PKG_LIST_SELSITART.vPerioada', ' BETWEEN TO_DATE('''||sDataS||''',''DD.MM.YYYY'') AND TO_DATE('''||sDataF||''',''DD.MM.YYYY'')', FALSE);
  ELSE
    PERFORM set_config('PKG_LIST_SELSITART.vPerioada', '', FALSE);
  END IF;

  PERFORM set_config('PKG_LIST_SELSITART.vToateArt', (COALESCE(pToateArt, 1) = 1)::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELSITART.vTotiPart', (COALESCE(pTotiPart, 1) = 1)::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELSITART.vToateDoc', (COALESCE(pToateDoc, 1) = 1)::varchar, FALSE);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_seltras_getdatafin</obj_name>
  <obj_hashval>6add6ee89b4fc16a1c0927c29dd3eab6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_seltras_getdatafin()
 RETURNS date
 LANGUAGE sql
AS $function$
  -- Stef 12.06.2023
  SELECT to_date(current_setting('PKG_LIST_SELTRAS.p_dataFin', true), 'dd.mm.yyyy');
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_seltras_isalltipcont</obj_name>
  <obj_hashval>62b069955e746bbded4a5c470dabeb4b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_seltras_isalltipcont()
 RETURNS boolean
 LANGUAGE sql
AS $function$
  -- Stef 12.06.2023
  SELECT current_setting('PKG_LIST_SELTRAS.p_flgTipCont', true)::BOOLEAN;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_seltras_issicentralizat</obj_name>
  <obj_hashval>66e666c9968a14a02100c6b246f9a9d5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_seltras_issicentralizat()
 RETURNS boolean
 LANGUAGE sql
AS $function$
  -- Stef 12.06.2023
  SELECT current_setting('PKG_LIST_SELTRAS.p_flgSICentr', true)::BOOLEAN;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_seltras_setallparams</obj_name>
  <obj_hashval>10aa36c7e0503e0b3d906dcfe19cd7f2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_seltras_setallparams(v_dataini character varying, v_datafin character varying, v_flggest integer, v_flgtipcont integer, v_flgsicentr integer, v_codjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni   NUMERIC;
  xLunaAnFin   NUMERIC;

  p_dataIni    DATE;
  p_dataFin    DATE;
  p_flgGest    BOOLEAN;
  p_flgTipCont BOOLEAN;
  p_flgSICentr BOOLEAN;
BEGIN
  --Florin 10.01.2025 - fixat 64406
  -- Stef 12.06.2023
  p_dataIni    := To_Date(v_dataini,'dd.mm.yyyy');
  p_dataFin    := To_Date(v_dataFin,'dd.mm.yyyy');
  p_flgGest    := v_flgGest    = 1;
  p_flgTipCont := v_flgTipCont = 1;
  p_flgSICentr := v_flgSICentr = 1;
  if Coalesce(v_CodJob1,0) &gt; 0 then
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1,p_dataIni,p_dataFin,xLunaAnIni,xLunaAnFin);
  end if;
  PERFORM PKG_ORA_LISTS_SET_INTERVAL_LISTARE(p_dataIni,p_dataFin);

  perform set_config('PKG_LIST_SELTRAS.p_dataIni'   , To_Char(p_dataIni,'dd.mm.yyyy'), false);
  perform set_config('PKG_LIST_SELTRAS.p_dataFin'   , To_Char(p_dataFin,'dd.mm.yyyy'), false);
  perform set_config('PKG_LIST_SELTRAS.p_flgGest'   , p_flgGest::varchar             , false);
  perform set_config('PKG_LIST_SELTRAS.p_flgTipCont', p_flgTipCont::varchar          , false);
  perform set_config('PKG_LIST_SELTRAS.p_flgSICentr', p_flgSICentr::varchar          , false);

  UPDATE TMP_MANEVRA_LISTE
  SET valoare1 = nullif(valoare1, ''),
     valoare2 = nullif(valoare2, ''),
     valoare3 = nullif(valoare3, '');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selurmdocpart_setparams</obj_name>
  <obj_hashval>b36524faaca7e2c36162bd1a07e36302</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selurmdocpart_setparams(p_codpart numeric, p_nrdoc numeric, p_datadoc character varying, pcodjob1 numeric, pdatas character varying, pdataf character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  vDataS       date;
  vDataF       date;
  aTipInterval numeric(1,0) := 0;
  ALISTID      numeric(2,0) := 0;
  xLunaAnIni   NUMERIC;
  xLunaAnFin   NUMERIC;
  sDataS       varchar := pDataS;
  sDataF       varchar := pDataF;
  vDataDoc     varchar;
begin
  --Bogdan 02.09.2020
  vDataS     := To_Date(sDataS,'dd.mm.yyyy');
  vDataF     := To_Date(sDataF,'dd.mm.yyyy');
  xLunaAnIni := Extract( Year FROM vDataS) * 12 + Extract( Month FROM vDataS);
  xLunaAnFin := Extract( Year FROM vDataF) * 12 + Extract( Month FROM vDataS);

  IF  COALESCE(pCodJob1, 0) &gt; 0 THEN
    select PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.adataini,PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.adatafin,
           PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.alunaanini, PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.alunaanfin
    from PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(pCodJob1, sDataS, sDataF, xLunaAnIni, xLunaAnFin) into vDataS,vDataF,xLunaAnIni,xLunaAnFin ;
  END IF;

  perform set_config('PKG_LIST_SELURMDOCPART.vDataS',to_char(vDataS,'dd.mm.yyyy' ),false);
  perform set_config('PKG_LIST_SELURMDOCPART.vDataF',to_char(vDataF,'dd.mm.yyyy' ),false);

  IF  COALESCE(pCodJob1, 0) &gt; 0 THEN
    aTipInterval := 1;
  END IF;

  IF  ATIPINTERVAL = 0 THEN
    vDataDoc :=p_DataDoc;
  ELSE
    SELECT TO_CHAR(CURRENT_TIMESTAMP, 'DD.MM.YYYY') INTO vDataDoc
    FROM JOBLISTE1
    WHERE CODJOB1 = COALESCE(pCodJob1, 0);
  END IF;

  perform set_config('PKG_LIST_SELURMDOCPART.vDataDoc', vDataDoc          ,false);
  perform set_config('PKG_LIST_SELURMDOCPART.vCodPart', p_CodPArt::varchar,false);
  perform set_config('PKG_LIST_SELURMDOCPART.vNrDoc'  , p_NrDoc::varchar  ,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selurmofe_dataini</obj_name>
  <obj_hashval>584abcceade8453baea0c16d7f37a91b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selurmofe_dataini()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 09.09.2020
  return to_date(current_setting ('PKG_LIST_SELURMOFE.vDataIni', true),'dd.mm.yyyy');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selurmofe_setparams</obj_name>
  <obj_hashval>447ec234af3d403252691e418ff328fa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selurmofe_setparams(pdataini character varying DEFAULT NULL::character varying, pdatafin character varying DEFAULT NULL::character varying, ptotipart numeric DEFAULT 1, v_codjob1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
  vDataIni   DATE;
  vDataFin   DATE;
begin
  --Bogdan 09.09.2020
  perform set_config ('PKG_LIST_SELURMOFE.vTotiPart',coalesce(pTotiPart,1)::varchar,false);

  vDataIni     := To_Date(pDataIni,'dd.mm.yyyy');
  vDataFin     := To_Date(pDataFin,'dd.mm.yyyy');

  IF COALESCE (v_CodJob1, 0) &gt; 0 then
    select PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.adataini, PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.adatafin
      from PKG_ORA_LISTS_SET_INTERVAL_DINAMIC (V_CODJOB1, vDataIni , vDataFin , xLunaAnIni, xLunaAnFin) into vDataIni , vDataFin;
  END IF;

  perform set_config ('PKG_LIST_SELURMOFE.vDataIni',to_char(vDataIni, 'dd.mm.yyyy'),false);
  perform set_config ('PKG_LIST_SELURMOFE.vDataFin',to_char(vDataFin, 'dd.mm.yyyy'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selutilaje_setparams</obj_name>
  <obj_hashval>8863b14b3d241c374cdf9c8a93175f88</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selutilaje_setparams(pallutilaje numeric, pallinterventii numeric, pextra1 numeric, pperdatainterv numeric, palltiputilaje numeric, pdataini character varying, pdatafin character varying, v_codjob1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
BEGIN
  --Florin 26.07.2022 - 55020
  --Adina 16 septembrie 2020
  perform set_config('PKG_LIST_SELUTILAJE.gAllInterventii',( COALESCE(pAllInterventii,1) = 1)::varchar ,false);
  perform set_config('PKG_LIST_SELUTILAJE.gAllUtilaje'    ,( COALESCE(pAllUtilaje,1) = 1)::varchar ,false);
  perform set_config('PKG_LIST_SELUTILAJE.gAllTipUtilaje' ,( COALESCE(pAllTipUtilaje,1) = 1)::varchar ,false);
  perform set_config('PKG_LIST_SELUTILAJE.gExtra1',        ( COALESCE(pExtra1,0) = 1)::varchar         ,false);
  perform set_config('PKG_LIST_SELUTILAJE.gPerDataInterv', (trunc(COALESCE(pPerDataInterv,0)))::varchar,false);
  perform set_config('PKG_LIST_SELUTILAJE.gDataIni',(pDataIni)::varchar,false);
  perform set_config('PKG_LIST_SELUTILAJE.gDataFin',(pDataFin)::varchar,false);
  IF  Coalesce(v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, current_setting('PKG_LIST_SELUTILAJE.gDataIni', true), current_setting('PKG_LIST_SELUTILAJE.gDataFin', true), xLunaAnIni, xLunaAnFin);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_add_config_dinamic_cols</obj_name>
  <obj_hashval>ac6d8ead0df83d6730a96552d089b8db</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_add_config_dinamic_cols(alistid numeric, alistver numeric, prefix character varying, maxim numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  IDX    numeric;
  COD    numeric;
  OLDCOD numeric;
  ACOL   varchar;
  CNT    numeric;
BEGIN
  --Adina 23.02.2021
  FOR IDX IN 2..MAXIM LOOP
    ACOL := PREFIX||IDX;
    SELECT COUNT(*) INTO CNT FROM WINMADMIN.LISTCOLS WHERE UPPER(FIELDNAME) = UPPER(ACOL) AND
                                                           LISTID = ALISTID AND
                                                           LISTVER = ALISTVER;
    IF CNT = 0 THEN
      COD := (SELECT wme_result FROM WINMADMIN.PKG_LIST_UTILS_GET_SEQ_NEXTVAL(NULL,'WINMADMIN','SEQ_LISTCOLS_CODLISTCOLS'));
      begin
        SELECT CODLISTCOLS into OLDCOD FROM WINMADMIN.LISTCOLS WHERE LISTID = ALISTID AND LISTVER = ALISTVER AND UPPER(FIELDNAME) = UPPER(PREFIX)||1;
      exception
        when others then null;
      end;

      INSERT INTO WINMADMIN.LISTCOLS(
        CODLISTCOLS,LISTID,LISTVER,FIELDNR,FIELDNAME,VISIBLE,TOTAL,SEPARATOR,ALIGNMENT,
        COLOR,DECIMALPLACES,WIDTH,CHARWIDTH,STYLES,RIGHTLINE,BOTTOMLINE,FONTNAME,FONTSTYLE,FONTSIZE,FONTCOLOR,
        NUMERICFIELD,CALCULATA,CALCFIELDNAME,CALCEXPRESIE,USERCOLUMN,ALIAS,FIELDTYPE,FIELDSIZE,DISPLAY,OBS,SOLDCOL)
      SELECT
        COD,LISTID,LISTVER,-1,ACOL,'F',TOTAL,SEPARATOR,ALIGNMENT,
        COLOR,DECIMALPLACES,WIDTH,CHARWIDTH,STYLES,RIGHTLINE,BOTTOMLINE,FONTNAME,FONTSTYLE,FONTSIZE,FONTCOLOR,
        NUMERICFIELD,CALCULATA,CALCFIELDNAME,CALCEXPRESIE,USERCOLUMN,ALIAS,FIELDTYPE,FIELDSIZE,DISPLAY,OBS,SOLDCOL
      FROM WINMADMIN.LISTCOLS
      WHERE LISTID = ALISTID AND LISTVER = ALISTVER AND UPPER(FIELDNAME) = UPPER(PREFIX)||1;

      INSERT INTO WINMADMIN.LISTTITS(
        CODLISTTITS, LISTID, LISTVER,
        TITLENR, ALIGNMENT,CAPTION,COLOR,FONTNAME,FONTSTYLE, FONTSIZE,FONTCOLOR,RIGHTLINE,BOTTOMLINE,PARENT)
      SELECT
        (SELECT wme_result FROM WINMADMIN.PKG_LIST_UTILS_GET_SEQ_NEXTVAL(NULL,'WINMADMIN','SEQ_LISTTITS_CODLISTTITS') ),
        LISTID, LISTVER,
        TITLENR, ALIGNMENT,CAPTION,COLOR,FONTNAME,FONTSTYLE, FONTSIZE,FONTCOLOR,RIGHTLINE,BOTTOMLINE,COD
      FROM WinMAdmin.ListTits lt
      WHERE lt.Parent = OLDCOD and lt.ListID = aListID and lt.ListVer = aListver;
    END IF;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_adunacoloanele</obj_name>
  <obj_hashval>c597521785b8f7b57c12389495bebd44</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_adunacoloanele()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sTab         varchar;
  sAlias       varchar;
  g_tableSpec  varchar;
  tmp          varchar;
  PanaLaSpatiu varchar;
  b            integer;
  cnt          numeric := 0;
    sOwner       varchar;
begin
  --Bogdan 08.11.2023 - 59872 : Meniu liste proprii - view mare - config
  DELETE FROM tmp_list_cols;
  g_tableSpec := TRIM(both ' ' from current_setting('PKG_LIST_STRUCT.g_tableSpec', true));
  IF  length(g_tableSpec) &gt; 0  THEN
    SELECT COUNT( *) INTO cnt FROM tmp_list_cols;
    IF  cnt = 0 THEN
      tmp := upper(g_tableSpec) || ',';
      WHILE StrPos(tmp,',') &gt; 1 loop
      sOwner := null;
        b := Strpos(tmp,' ');
        sTab   := trim( both ' ' from substring(tmp,1,b));
        if(Strpos(sTab,'.') &gt; 0) then
          sOwner := trim(both ' ' from substring(sTab,1,Strpos(sTab,'.')-1));
          sTab   := trim(both ' ' from substring(sTab,Strpos(sTab,'.')+1,length(sTab)));
        end if;
        tmp := trim( both ' ' from substring(tmp,b+1,length(tmp)));
        b := Strpos(tmp,',');
        sAlias := trim( both ' ' from substring(tmp,1,b-1));
        tmp := TRIM( both ' ' from substring(tmp,b+1,length(tmp)));
        perform pkg_list_struct_updatetmp(sTab,sAlias, sOwner);
      END LOOP;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_adunacoloanelexview</obj_name>
  <obj_hashval>efc37f450de42582f2a2c70bcfd015a2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_adunacoloanelexview(pviewname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  --Florin 21.06.2023 - sinc. Oracle (19.06.2023)
  sJoinsTbl view_joins.joinuri%type;
  sViewName view_joins.viewname%type;
  sIdCustomTable varchar(20);
  idCustomTable NUMERIC(10);
  b NUMERIC;
  sJoinTblFromCustomTbl winmadmin.maketeproprii.tblmaster%type;
BEGIN
   --Florin 18.07.2023 - sinc. Oracle
   sViewName := upper(pViewName);
   DELETE FROM tmp_list_cols;
   begin
     select vj.joinuri into sJoinsTbl from view_joins vj where vj.viewname = '' || sViewName || '';
   exception
     WHEN OTHERS THEN sJoinsTbl := null;
   end;
   if coalesce(instr(sViewName, 'CUSTOMFORMDB_'),0) &gt; 0 then
      sViewName := trim(replace(sViewName,  'CUSTOMFORMDB_', ''));
      b := coalesce(instr(sViewName, '_VIEW'),0);
      sIdCustomTable := Substr(sViewName, 1, (b-1)::integer);
      if length(sIdCustomTable) &gt; 0 then
        begin
           idCustomTable := to_number( sIdCustomTable );
           select mp.tblmaster into sJoinTblFromCustomTbl from winmadmin.maketeproprii mp where mp.iddocument =  idCustomTable;
         exception
            when data_exception then sJoinTblFromCustomTbl := null;
         end;
      end if;
      if sJoinTblFromCustomTbl is not null then
        sJoinTblFromCustomTbl := sJoinTblFromCustomTbl || ' CustM ';
        if sJoinsTbl is null then sJoinsTbl := sJoinTblFromCustomTbl;
                             else sJoinsTbl := sJoinsTbl || ', ' || sJoinTblFromCustomTbl;
        end if;
      end if;
   end if;

   if sJoinsTbl is not null then
     PERFORM pkg_list_struct_SetTableSpec(sJoinsTbl);
     PERFORM pkg_list_struct_AdunaColoanele();
   end if;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_colexists</obj_name>
  <obj_hashval>653dc4aec5de850435fe07f8ad1814c7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_colexists(INOUT wme_result numeric, INOUT tabname character varying, INOUT colname character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult numeric;
begin
  SELECT COUNT( 1) INTO sResult FROM information_schema.COLUMNS WHERE table_name = Lower( TabName) AND  column_name = Lower( ColName);
  WME_Result :=  sResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_droptbl</obj_name>
  <obj_hashval>f722d1154b192727c185f3765124c6ab</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_droptbl(tmpname character varying, do1 integer DEFAULT 1, do2 integer DEFAULT 1, do3 integer DEFAULT 1, do4 integer DEFAULT 1)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Exista numeric;
begin

  IF (Do1 = 1) THEN
    SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT into Exista FROM PKG_LIST_STRUCT_TmpExists(NULL, tmpName);
    if (Exista &gt; 0)   THEN
      BEGIN
        EXECUTE 'TRUNCATE TABLE ' || tmpName;
        EXECUTE 'DROP TABLE ' || tmpName;
      EXCEPTION WHEN OTHERS THEN NULL; END;
    END IF;
  END IF;

  IF (Do2 = 1) THEN
    SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT into Exista FROM PKG_LIST_STRUCT_TmpExists(NULL, 'W' || tmpName);
    if (Exista &gt; 0)   THEN
      BEGIN
        EXECUTE 'TRUNCATE TABLE W' || tmpName;
        EXECUTE 'DROP TABLE W' || tmpName;
      EXCEPTION WHEN OTHERS THEN NULL; END;
    END IF;
  END IF;

  IF (Do3 = 1) THEN
    SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT into Exista FROM PKG_LIST_STRUCT_TmpExists(NULL, tmpName || 'PIV');
    if (Exista &gt; 0)   THEN
      BEGIN
        EXECUTE 'TRUNCATE TABLE ' || tmpName || 'PIV';
        EXECUTE 'DROP TABLE ' || tmpName || 'PIV';
      EXCEPTION WHEN OTHERS THEN NULL; END;
    END IF;
  END IF;

  IF (Do4 = 1) THEN
    SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT into Exista FROM PKG_LIST_STRUCT_TmpExists(NULL, 'W' || tmpName || 'PIV');
    if (Exista &gt; 0)   THEN
      BEGIN
        EXECUTE 'TRUNCATE TABLE W' || tmpName || 'PIV';
        EXECUTE 'DROP TABLE W' || tmpName || 'PIV';
      EXCEPTION WHEN OTHERS THEN NULL; END;
    END IF;
  END IF;

end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_g_tablespec</obj_name>
  <obj_hashval>8a136bbf943559d68baf373f84f4142a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_g_tablespec(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_LIST_STRUCT.g_TableSpec', true));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_g_tablespecrezerva</obj_name>
  <obj_hashval>c388b91ed33e0e7d0a1cbb34adf16a1e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_g_tablespecrezerva(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_LIST_STRUCT.g_TableSpecRezerva', true));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_g_tmpname</obj_name>
  <obj_hashval>545edc325d4a3eaa2cc65fe967b8f6df</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_g_tmpname(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_LIST_STRUCT.g_tmpName', true));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_generatepiv</obj_name>
  <obj_hashval>83f0718cb13ebe9134273d3fc1cad55c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_generatepiv(tmpname character varying, cmd character varying, username character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  S    varchar;
  Tmp  varchar;
  sDML varchar;
BEGIN
  --Florin 11.01.2022
  --Stef   24.03.2022 - CREATE TEMPORARY (scosGLOBAL fiindca e obsolete si apare/incurca in loguri de BD)
  Tmp := TmpName || 'PIV';
  IF  (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(NULL, tmp)) = 1 THEN
    EXECUTE 'TRUNCATE TABLE ' || tmp;
    EXECUTE 'DROP TABLE ' || tmp;
  END IF;

  sDML := 'CREATE TEMPORARY TABLE ' || tmp || ' ON COMMIT PRESERVE ROWS AS (SELECT * FROM ' || tmpName || ' WHERE 1=0)';
  EXECUTE sDML;
  sDML := (SELECT wme_result FROM pkg_list_struct_getDMLGrant(NULL, tmp, UserName));
  EXECUTE sDML;
  EXECUTE CMD;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_generatetmp</obj_name>
  <obj_hashval>acd00dfd55fec2fb4287c9ae1dbe4188</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_generatetmp(tmpname character varying, listcols character varying, username character varying, pluscol1 character varying, pluscol2 character varying, pluscol3 character varying, pluscol4 character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  XlistCols varchar;
  sDDL      varchar := 'CREATE TEMPORARY TABLE ';
  sDML      varchar;
BEGIN
  --Florin 31.05.2023 - fixat 58473
  --Stef   24.03.2022 - CREATE TEMPORARY (scosGLOBAL fiindca e obsolete si apare/incurca in loguri de BD)
  IF  (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(NULL, tmpName)) = 1 THEN
    EXECUTE 'TRUNCATE TABLE ' || tmpName;
    EXECUTE 'DROP TABLE ' || tmpName;
  END IF;

  XlistCols := COALESCE(listCols, '') || COALESCE(plusCol1, '') || COALESCE(plusCol2, '') || COALESCE(plusCol3, '') || COALESCE(plusCol4, '');
  XlistCols := replace( XlistCols, 'V2(', 'VARCHAR(');
  XlistCols := replace( XlistCols, 'N(', 'NUMERIC(');
  XlistCols := replace( XlistCols, 'varchar2(', 'VARCHAR(');
  XlistCols := replace( XlistCols, 'number(', 'NUMERIC(');
  sDDL := sDDL || tmpName || '(';
  sDDL := sDDL || XlistCols || ' ,UNITAR NUMERIC(20) DEFAULT 1 ' || ') ON COMMIT PRESERVE ROWS';
  perform set_config('PKG_LIST_STRUCT.g_TableSpec','',false);
  EXECUTE sDDL;
  perform set_config('PKG_LIST_STRUCT.g_tmpname',tmpName,false);
--SELECT pkg_list_struct_getdmlgrant.WME_RESULT into sDML FROM pkg_list_struct_getdmlgrant(NULL, tmpName, UserName) ;
--EXECUTE sDML;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_getdmlgrant</obj_name>
  <obj_hashval>d323623d5627f3261155a99ad9bd4326</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_getdmlgrant(INOUT wme_result character varying, INOUT tmpname character varying, INOUT username character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult varchar := 'GRANT DELETE, INSERT, UPDATE, SELECT ON ';
begin
  sResult    := sResult || tmpName || ' TO ' || UserName;
  WME_Result :=  sResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_getg_tablespec</obj_name>
  <obj_hashval>be8cfd9be47f336f62caecbe8d1e00f6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_getg_tablespec(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_LIST_STRUCT.g_TableSpec', true));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_getg_tablespecrezerva</obj_name>
  <obj_hashval>04d7d728540c7178ac6825a1bbc5a6ef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_getg_tablespecrezerva(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_LIST_STRUCT.g_TableSpecRezerva', true));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_getg_tmpname</obj_name>
  <obj_hashval>9ead9e79859085a2a364b2263f218e61</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_getg_tmpname(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_LIST_STRUCT.g_tmpName', true));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_gettimestamp</obj_name>
  <obj_hashval>a5a74283abcd3f26949156ad5bfe6b15</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_gettimestamp(INOUT wme_result character varying, INOUT aobject character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  tResult varchar;
BEGIN
  WME_Result := 'x';
  RETURN;
  --?????? nu exista in pg data crearii obiectelor
--  BEGIN
--    SELECT to_char( created, 'dd.mm.yyyy hh24.mi.ss') INTO tResult FROM user_objects WHERE object_name = upper( aObject);
--  EXCEPTION WHEN NO_DATA_FOUND THEN
--    WME_Result :=  'x';
--    RETURN;
--  END;
--
--  WME_Result :=  tResult;
--  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_getv_idxparamlista</obj_name>
  <obj_hashval>4a0b478f0d72b3a0e3af569eafded11c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_getv_idxparamlista(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_LIST_STRUCT.v_IdxParamLista', true)),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_getv_idxsupltab</obj_name>
  <obj_hashval>f9176103b08dc7abeb239ea01115d7de</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_getv_idxsupltab(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_LIST_STRUCT.v_IdxSuplTab', true)),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_savelista</obj_name>
  <obj_hashval>b6e5ad5fee9160c3aea9375dffac3199</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_savelista(INOUT wme_result numeric, INOUT asavetable character varying, INOUT alisttable character varying, INOUT susername character varying, INOUT icodfirma numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  iResult     numeric;
  sSkemaPivot varchar;
  sSkemaGrant varchar;
begin
  iResult := (SELECT PKG_LIST_STRUCT_tmpExists.WME_RESULT FROM PKG_LIST_STRUCT_tmpExists(NULL, upper( aSaveTable)));
  IF  iResult &lt;&gt; 0 THEN
    WME_Result :=  iResult;
    RETURN;
  END IF;
  sSkemaGrant := sUserName;
  sSkemaPivot := winmadmin.pkg_userfirme.GetSkemaPivot( iCodFirma);
  IF  sSkemaPivot &lt;&gt; '?' THEN
    sSkemaGrant := sSkemaGrant || ',' || sSkemaPivot;
  END IF;
  EXECUTE 'CREATE TABLE ' || aSaveTable || ' AS SELECT * FROM ' || aListTable;
  EXECUTE 'GRANT SELECT ON  ' || aSaveTable || ' TO ' || sSkemaGrant;
  PERFORM winmadmin.pkg_userfirme.ActualizareTabConsolidare( (current_setting('PKG_GLOBALS.FIRMANAME', true)), aSaveTable);
  WME_Result :=  iResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_setg_tablespec</obj_name>
  <obj_hashval>bb9144a7d23facf50fa5c5d3f6afa297</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_setg_tablespec(ag_tablespec character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_STRUCT.g_TableSpec',ag_TableSpec,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_setg_tablespecrezerva</obj_name>
  <obj_hashval>5a8d98b2e8daf00442a4ba721456cd49</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_setg_tablespecrezerva(ag_tablespecrezerva character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_STRUCT.g_TableSpecRezerva',ag_TableSpecRezerva,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_setg_tmpname</obj_name>
  <obj_hashval>d7f391e81cb5e6407a3281bdcf0dd23a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_setg_tmpname(ag_tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_STRUCT.g_tmpName',ag_tmpName,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_settablespec</obj_name>
  <obj_hashval>c6ae881995429693f4c4b4ebef4575ab</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_settablespec(p_tablespec character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_STRUCT.g_TableSpec',p_tableSpec,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_settablespecfromrezerva</obj_name>
  <obj_hashval>afd6bab56012197d0d1593b535e7896a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_settablespecfromrezerva()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_STRUCT.g_TableSpec',(current_setting('PKG_LIST_STRUCT.g_TableSpecRezerva', true)),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_settablespecrezerva</obj_name>
  <obj_hashval>7a2d39c43819fc49a947eb43b499ba54</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_settablespecrezerva(p_tablespec character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_STRUCT.g_TableSpecRezerva',current_setting('PKG_LIST_STRUCT.g_TableSpec', True),false);
  perform set_config('PKG_LIST_STRUCT.g_TableSpec',p_tableSpec,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_setv_idxparamlista</obj_name>
  <obj_hashval>02e260b886ec18a3e06147bbfcef2f82</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_setv_idxparamlista(av_idxparamlista numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_STRUCT.v_IdxParamLista',to_char(av_IdxParamLista,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_tmpexists</obj_name>
  <obj_hashval>2d0eed74d7b347fc18d1cf09c89d05d7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_tmpexists(INOUT wme_result numeric, INOUT tmpname character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  --STEF 25.02.2021
  WME_Result := fnc_tmpexists(tmpname);
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_updatetmp</obj_name>
  <obj_hashval>2fd91fc06c7ca7a28d1253fbd309312c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_updatetmp(ptab character varying, palias character varying, powner character varying DEFAULT NULL::character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  countc NUMERIC;
  skemaName VARCHAR;
begin
  --Bogdan 08.11.2023 - corectie sincronizare
  --Florin 07.11.2023 = sinc. Oracle
  --Florin 09.09.2020 - adaugat coloane din tmp
 skemaName := case when powner is null then lower(current_setting('PKG_GLOBALS.FIRMANAME', true)) else lower(powner) end;
 IF substring(ptab, 1, 3) = 'TMP' THEN
    INSERT INTO tmp_list_cols ( tabla, coloana, tipcol, lungime )
    SELECT ptab, pAlias || '.' || a.COLUMN_NAME, a.DATA_TYPE, Coalesce(a.numeric_precision, a.character_maximum_length)
    FROM information_schema.columns a
    WHERE a.TABLE_NAME = lower(pTab)
    ORDER BY a.ORDINAL_POSITION;
  ELSE
    INSERT INTO tmp_list_cols ( tabla, coloana, tipcol, lungime )
    SELECT ptab, pAlias || '.' || a.COLUMN_NAME, a.DATA_TYPE, Coalesce(a.numeric_precision, a.character_maximum_length)
    FROM information_schema.columns a
    WHERE a.TABLE_NAME = lower(pTab)
    and table_schema = skemaName
    ORDER BY a.ORDINAL_POSITION;
  end if;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_v_idxparamlista</obj_name>
  <obj_hashval>5399731647f168b322651660e1a7de1b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_v_idxparamlista(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_LIST_STRUCT.v_IdxParamLista', true)),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_v_idxsupltab</obj_name>
  <obj_hashval>13bae15780d63342f2d69c1c364339a5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_v_idxsupltab(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_LIST_STRUCT.v_IdxSuplTab', true)),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_utilfisacont_get_baza</obj_name>
  <obj_hashval>b0deb9a5f3acda5263188b8457a37829</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_utilfisacont_get_baza(ptipbaza numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
declare
  retVal varchar ;
begin
  -- BogdanL 27.07.2020
  retVal :=  CASE
     WHEN  pTipBaza = current_setting('PKG_LIST_UTILFISACONT.TBJCONST'   , true)::numeric THEN 'CONST1'
     WHEN  pTipBaza = current_setting('PKG_LIST_UTILFISACONT.TBJART'     , true)::numeric THEN 'NARTOBJ'
     WHEN  pTipBaza IN (current_setting('PKG_LIST_UTILFISACONT.TBJPART'  , true)::numeric, current_setting('PKG_LIST_UTILFISACONT.TBJAVANS', true)::numeric, current_setting('PKG_LIST_UTILFISACONT.TBJRETURAVANS', true)::numeric, current_setting('PKG_LIST_UTILFISACONT.TBJVAMA', true)::numeric) THEN 'NPART'
     WHEN  pTipBaza = current_setting('PKG_LIST_UTILFISACONT.TBJPERS'    , true)::numeric THEN 'NPERS'
     WHEN  pTipBaza = current_setting('PKG_LIST_UTILFISACONT.TBJBANK'    , true)::numeric THEN 'NBANK'
     WHEN  pTipBaza = current_setting('PKG_LIST_UTILFISACONT.TBJFILIAL'  , true)::numeric THEN 'NSUBUNIT'
     WHEN  pTipBaza = current_setting('PKG_LIST_UTILFISACONT.TBJCONT'    , true)::numeric THEN 'NCONT'
     WHEN  pTipBaza = current_setting('PKG_LIST_UTILFISACONT.TBJINKIDERI', true)::numeric THEN 'INCHIDERI'
     WHEN  pTipBaza = current_setting('PKG_LIST_UTILFISACONT.TBJCMD1'    , true)::numeric THEN 'COMANDA1'
   END ;

  return retVal;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_utilfisacont_get_descr</obj_name>
  <obj_hashval>76905cde541d6ebf1b4fb9d8da09150e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_utilfisacont_get_descr(ptipcont numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
declare
  vResult varchar ;
begin
  --BogdanL 27.07.2020
vResult :=  CASE
         WHEN  pTipCont = current_setting('PKG_LIST_UTILFISACONT.TCJCONST' , true)::numeric THEN 'CONST1'
         WHEN  pTipCont = current_setting('PKG_LIST_UTILFISACONT.TCJTVA'   , true)::numeric THEN 'NTVA1'
         WHEN  pTipCont = current_setting('PKG_LIST_UTILFISACONT.TCJIOART' , true)::numeric THEN 'IOART1'
         WHEN  pTipCont = current_setting('PKG_LIST_UTILFISACONT.TCJIOPART', true)::numeric THEN 'IOPART1'
         WHEN  pTipCont = current_setting('PKG_LIST_UTILFISACONT.TCJIOPERS', true)::numeric THEN 'IOPERS1'
         WHEN  pTipCont = current_setting('PKG_LIST_UTILFISACONT.TCJIOBANK', true)::numeric THEN 'IOBANK1'
         WHEN  pTipCont = current_setting('PKG_LIST_UTILFISACONT.TCJFILIAL', true)::numeric THEN 'IOFILIAL1'
         WHEN  pTipCont = current_setting('PKG_LIST_UTILFISACONT.TCJCONT'  , true)::numeric THEN 'NCONT'
         WHEN  pTipCont = current_setting('PKG_LIST_UTILFISACONT.TCJTAXE'  , true)::numeric THEN 'NTAXE1'
         WHEN  pTipCont = current_setting('PKG_LIST_UTILFISACONT.TCJNGEST1', true)::numeric THEN 'NGEST1'
       END ;
return vResult;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_utilfisacont_getobsdocjurnal</obj_name>
  <obj_hashval>2dcc3977e272ca85363b85060f8080fa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_utilfisacont_getobsdocjurnal(acodjurnal numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  Rez varchar;
begin
  --BogdaL 29.07.2020
  BEGIN
    SELECT case
      WHEN j.tipdoc IN (1, 2, 3, 4, 5, 6, 7, 9)         THEN ( SELECT i.obs FROM intrari i  where  i.codintr = j.coddoc)
       WHEN j.tipdoc IN (14, 15, 16, 19, 20, 23, 24, 26) THEN ( SELECT i.obs FROM iesiri i   where  i.codies = j.coddoc)
       WHEN j.tipdoc IN (25)                             THEN ( SELECT c.obs FROM contract c WHERE c.codcontract = j.coddoc)
       WHEN j.tipdoc IN (29, 30, 31, 33)                 THEN ( SELECT t1.obs
                                                               FROM trezor1 t1
                                                               INNER JOIN trezor t ON  t.codtrezor = t1.codtrezor
                                                              LEFT JOIN general g ON  g.coddoc = t1.codtrezor1 AND  g.tipdoc = t.codtrezor
                                                             WHERE
                                                                 t1.codtrezor = j.coddoc and  t1.codtrezor1 = j.indexlocal )
       WHEN j.tipdoc IN (35)                             THEN ( SELECT nc.obs
                                                               FROM nc1
                                                               INNER JOIN nc ON  nc.codnc = nc1.codnc
                                                              where
                                                                nc.codnc = j.coddoc AND  j.indexlocal = nc1.codnc1 )

       end INTO Rez
    FROM jurnal j
    where    j.codjurnal = aCodJurnal;

    EXCEPTION WHEN others THEN
      Rez := null;
  END;

  return  Rez;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_localitati_sp_deleterecord</obj_name>
  <obj_hashval>bd095e599ad48ee5fc7b77566f2c2d50</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_localitati_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_LOCALITATI_SP_LOCKRECORD( RecId);
  DELETE FROM NLOCALIT WHERE codlocalit = RecId;
  PERFORM NotifyModif( 2, RecId, 'NLOCALIT');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_localitati_sp_gotorecord</obj_name>
  <obj_hashval>e94d268e3a3ca72f18e50b973dace6f2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_localitati_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Laura 22.09.2021 - sinc Oracle (21.09.2021)
  INSERT INTO TMP_NLOCALIT(codlocalit, den_localit, tip, codjudet, obs, CODTARA, DENSUP, SIRUTA, CODZONA, LATITUDINE, LONGITUDINE, CODPOSTAL)
  (
  SELECT codlocalit, den_localit, tip, codjudet, obs, CODTARA, DENSUP, SIRUTA, codzona, LATITUDINE, LONGITUDINE, CODPOSTAL
  FROM NLOCALIT WHERE codlocalit = RecId
  );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_localitati_sp_insertrecord</obj_name>
  <obj_hashval>1ae78af6f4bb56db1a1262d943881e4f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_localitati_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NLOCALIT (codlocalit) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_localitati_sp_lockrecord</obj_name>
  <obj_hashval>9654fe93a801f42e510fc18905666bf1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_localitati_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT codlocalit INTO Tmp FROM NLOCALIT WHERE codlocalit = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_localitati_sp_postrecords</obj_name>
  <obj_hashval>96208dc52d561908dae31a363d10c4cd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_localitati_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vRecNo NUMERIC := 0;
  vAn    NUMERIC := 0;
  vLuna  NUMERIC := 0;
  vCod   numeric;
begin
  --Laura 22.09.2021 - sinc Oracle (21.09.2021)
  IF  Operation = 0 THEN
    SELECT codlocalit INTO RecId FROM TMP_NLOCALIT;

    UPDATE NLOCALIT
    SET
    (den_localit, tip, codjudet, obs, CODTARA, DENSUP, SIRUTA, Codzona, LATITUDINE, LONGITUDINE, CODPOSTAL)
    =
    (
    SELECT den_localit, tip, COALESCE( codjudet, 0), obs, COALESCE( CODTARA, 0), DENSUP, SIRUTA, COALESCE( codzona, 0), LATITUDINE, LONGITUDINE, CODPOSTAL
    FROM TMP_NLOCALIT
    )
    WHERE
     codlocalit = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_NLOCALIT_CODLOCALIT') INTO RecId;

    INSERT INTO NLOCALIT(codlocalit, den_localit, tip, codjudet, obs, CODTARA, DENSUP, SIRUTA, Codzona, LATITUDINE, LONGITUDINE, CODPOSTAL)
    (
    SELECT RecId, den_localit, tip, COALESCE( codjudet, 0), obs, COALESCE( CODTARA, 0), DENSUP, SIRUTA, COALESCE( codzona, 0), LATITUDINE, LONGITUDINE, CODPOSTAL
    FROM TMP_NLOCALIT
    );
  END IF;

  PERFORM NotifyModif( Operation, RecId, 'NLOCALIT');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_locmunca_preparetmp_oregantt1</obj_name>
  <obj_hashval>c63d95b379ac0c6704b30049709638f5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_locmunca_preparetmp_oregantt1(adata1 character varying, adata2 character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
  DECLARE
V      record;
W      record;
DataMin     Date;
DataMax      Date;
OreMatrita   double precision;
OreMasina    double precision;
  BEGIN
DataMin   := TO_DATE(aData1    , 'DD.MM.YYYY');
DataMax   := TO_DATE(aData2    , 'DD.MM.YYYY');

perform umple_tmp_zile(DataMin, DataMax);
Delete from TMP_OREGANTT1;
INSERT INTO TMP_OREGANTT1
WITH
  Recs as
   ( SELECT L.CodLoc CodLM, D.Ziua as Data from Tmp_Zile D, LocMunca L),
  OLM1 as
   (SELECT L.CodLoc CodLM, L1.CodLoc1 CodLM1, coalesce(L1.ORE, G.Ore) Ore
    FROM LocMunca L
    inner join LocMunca1 L1 on L1.CodLoc = L.CodLoc
    inner join ( Select CodGest, coalesce(NrSchimburi, 0) * coalesce(OreSchimb, 0) Ore from NGEST) G on G.CodGest = L1.CodGest)
  Select to_char(Data,'iw')::numeric Sapt, Data, CodLM, CodLM1, Ore, OreIni CateLM1
  from
  (
  select Recs.CodLM, OLM1.CodLM1, Recs.Data, coalesce(OreLM.Ore, OLM1.Ore) Ore, coalesce(OreLM.Ore, OLM1.Ore) OreIni,
         OLM1.Ore OreDef, Case when OreLM.Ore = OLM1.Ore then null else OreLM.Ore end OreExcept
  from Recs
       left join OLM1 on OLM1.CodLM = Recs.CodLM
       left join OreLM on OreLM.DataLM = Recs.Data and OreLM.Codlm1 = OLM1.CodLM1
  ) X;

 --asta e tabela care va modifica TMP_OREGANTT
  for V in (
      select * from LocMunca2 where DataStart between DataMin and DataMax
                              or  DataStop between DataMin and DataMax
                              or  (DataStart &lt; DataMin and DataStop &gt; DataMax)
  ) loop
    -------------------
    if v.datastart = v.datastop then
      OreMatrita := Coalesce(v.Orestart,0) + Coalesce(v.orestop,0);
      OreMasina  :=  OreMatrita + Round(((Coalesce(v.minuneon,0)+Coalesce(v.minuneoff,0))/60)::numeric,2);
      update TMP_OREGANTT1 set ORE = ORE + OreMatrita where DATA = v.datastart and CODLM1 = v.codloc1;
      update TMP_OREGANTT1 set ORE = ORE - OreMasina  where DATA = v.datastart and CODLM1 = v.codloc1asoc;
    else
      OreMatrita := Coalesce(v.Orestart,0);
      OreMasina  :=  OreMatrita + Round((Coalesce(v.minuneon,0)/60)::numeric,2);
      update TMP_OREGANTT1 set ORE = ORE + OreMatrita where DATA = v.datastart and CODLM1 = v.codloc1;
      update TMP_OREGANTT1 set ORE = ORE - OreMasina  where DATA = v.datastart and CODLM1 = v.codloc1asoc;
      OreMatrita := Coalesce(v.orestop,0);
      OreMasina  :=  OreMatrita + Round((Coalesce(v.minuneoff,0)/60)::numeric,2);
      update TMP_OREGANTT1 set ORE = ORE + OreMatrita where DATA = v.datastop and CODLM1 = v.codloc1;
      update TMP_OREGANTT1 set ORE = ORE - OreMasina  where DATA = v.datastop and CODLM1 = v.codloc1asoc;
      for w in ( select * from TMP_OREGANTT1
                 where CodLM1 = v.codloc1asoc and Data between v.datastart + 1 and v.Datastop - 1) loop
        OreMasina  :=  Coalesce(w.ORE,0);
        update TMP_OREGANTT1 set ORE = 0          where DATA = w.data and CODLM1 = v.codloc1asoc;
        update TMP_OREGANTT1 set ORE = OreMasina  where DATA = w.data and CODLM1 = v.codloc1;
      end loop;
    end if;
    -------------------
  end loop;
  END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_locmunca_savegantt</obj_name>
  <obj_hashval>0266b52f58a74d17a76dd692a891eefa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_locmunca_savegantt()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  RecId numeric;
BEGIN
  --Adina 09.07.2021
  FOR V_Rec IN (SELECT * FROM TMP_GANTT WHERE CodGantt &gt; 0) LOOP
    UPDATE Gantt
    SET
      CODCMDPRODMAN = V_REC.CODCMDPRODMAN,
      CODCOMANDA1   = V_REC.CODCOMANDA1,
      DSTART        = V_REC.DSTART,
      NSTART        = V_REC.NSTART,
      OStart        = V_REC.OSTART,
      OStop         = V_REC.OSTOP,
      Directie      = V_REC.Directie,
      Prioritate    = V_REC.Prioritate,
      BLOCAT        = V_REC.BLOCAT,
      ORDINE        = V_REC.ORDINE,
      CANT          = V_REC.CANT
    WHERE
     CodGANTT = V_REC.CodGANTT;

    DELETE FROM Gantt1 G1 WHERE G1.CodGantt = V_REC.Codgantt and  NOT  EXISTS (SELECT CodGantt1 FROM TMP_Gantt1 TG1 WHERE TG1.CodGantt1 = G1.CodGantt1);
  END LOOP;

  FOR V_Rec IN (SELECT * FROM TMP_GANTT WHERE CodGantt &lt; 0) LOOP
    RecId := NEXTVAL('SEQ_GANTT');
    UPDATE TMP_Gantt1 SET CodGantt = RecId WHERE CodGantt = v_rec.CodGantt;

    INSERT INTO Gantt(CODGANTT, CODCMDPRODMAN, CODCOMANDA1, DSTART, NSTART, OSTART, OSTOP, Directie, ORDINE, Blocat, Prioritate, CANT)
    VALUES(RecId, V_REC.CODCMDPRODMAN, V_REC.CODCOMANDA1, V_REC.DSTART, V_REC.NSTART, V_REC.OSTART, V_REC.OSTOP, V_REC.Directie, V_REC.ORDINE, V_REC.Blocat, V_REC.Prioritate, V_REC.CANT);
  END LOOP;

  FOR V_Rec IN (SELECT * FROM TMP_GANTT1 WHERE CodGantt1 &gt; 0) LOOP
    UPDATE Gantt1
    SET
      Deplasare = V_REC.Deplasare,
      CANT      = V_REC.CANT
    WHERE
     CodGANTT1 = V_REC.CodGANTT1;
  END LOOP;

  FOR V_Rec IN (SELECT * FROM TMP_GANTT1 WHERE CodGantt1 &lt; 0) LOOP
    RecId := NEXTVAL('SEQ_GANTT1');
    INSERT INTO Gantt1(CODGANTT1, CODGANTT, Deplasare, CANT)
    VALUES(RecId, V_REC.CODGANTT, V_REC.Deplasare, V_REC.CANT);
  END LOOP;

  DELETE FROM TMP_GANTT;
  DELETE FROM TMP_GANTT1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mail_sendmail</obj_name>
  <obj_hashval>96a14ebda32f021e4203f126824dc338</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mail_sendmail(url_wmeservice character varying, servermail character varying, serverport character varying, mesaj character varying, fromaddress character varying, parola character varying, username character varying, subject character varying, toaddress character varying, attachment character varying, attachtable character varying, attachmenttype character varying)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
declare
 aStatus varchar;
aContent varchar;
attachtableInfo varchar := '';

begin
perform http_set_curlopt('CURLOPT_CONNECTTIMEOUT', '15');
perform http_set_curlopt('CURLOPT_TIMEOUT', '15');


  attachtableinfo := '"AttachTable":{
                                       "DataBaseType":"PG",
                                       "DBName":"'         || current_database()        ||'",
                                       "ServerIP":"'       || host(inet_server_addr())  ||'",
                                       "ServerPort":"'     || inet_server_port()        ||'",
                                       "TableName":"'      || attachtable               ||'",
                                       "AttachmentType":"' || AttachmentType            ||'"
                                     }';



SELECT status, content into astatus, aContent
FROM http_post(URL_WMESERVICE,
'{
  "ServerMail":"'  || ServerMail  ||'",
  "Port":"'        || ServerPort  ||'",
  "Message":"'     || Mesaj       || '",
  "FromAddress":"' || FromAddress || '",
  "UserName":"'    || UserName    || '",
  "Password":"'    || parola      ||'",
  "PasswordEncrypted":"D",

  "Subject":"'     || Mesaj       ||'",
  "Attachment":"'  || Attachment  ||'", ' ||
  attachtableinfo  || ',

  "ToAddress":"'   || ToAddress   || '"
}',

 'application/x-www-form-urlencoded');
 --delete from x;
 --insert into x(view_name) values (aContent);
 if instrb(aContent, '"ok"') &gt; 0 then
  return 1;
 else
  return 0;
 end if;

end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mail_sendmail_by_service</obj_name>
  <obj_hashval>99b8ff81de352e2081feae9eed14910f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mail_sendmail_by_service(servermail character varying, serverport character varying, fromaddress character varying, username character varying, parola character varying, subject character varying, toaddress character varying, mesaj character varying)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
declare
 aStatus varchar;
aContent varchar;
URL_WMESERVICE varchar;

begin
perform http_set_curlopt('CURLOPT_CONNECTTIMEOUT', '15');
perform http_set_curlopt('CURLOPT_TIMEOUT', '15');


 URL_WMESERVICE   := 'http://' ||
                      fnc_GetValConstanta('IPWebServiceSMS', getANLUCRU(), getLUNALUCRU())  || ':' ||
                      fnc_GetValConstanta('PortWebServiceSMS', getANLUCRU(), getLUNALUCRU()) ||
                     '/root/WMEServer/SendMail';





SELECT status, content into astatus, aContent
FROM http_post(URL_WMESERVICE,
'{
  "ServerMail":"'  || ServerMail  ||'",
  "Port":"'        || ServerPort  ||'",
  "Message":"'     || Mesaj       || '",
  "FromAddress":"' || FromAddress || '",
  "UserName":"'    || UserName    || '",
  "Password":"'    || parola      ||'",
  "Subject":"'     || Mesaj       ||'",
  "ToAddress":"'   || ToAddress   || '"
}',

 'application/x-www-form-urlencoded');
 --delete from x;
 --insert into x(view_name) values (aContent);
 if instrb(aContent, '"ok"') &gt; 0 then
  return 1;
 else
  return 0;
 end if;

end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mail_solvealerta</obj_name>
  <obj_hashval>059189f061fa2d1552784cdcbae41588</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mail_solvealerta(url_wmeservice character varying, dbhost character varying, dbport character varying, codalerta numeric, skema character varying)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
declare
 aStatus varchar;
aContent varchar;
AlertaInfo varchar := '';

begin
perform http_set_curlopt('CURLOPT_CONNECTTIMEOUT', '0');
perform http_set_curlopt('CURLOPT_TIMEOUT', '0');


  AlertaInfo := '"AlertaInfo":{
                                       "DataBaseType":"PG",
                                       "DBName":"'         || current_database()        ||'",
                                       "ServerIP":"'       || DBHost                    ||'",
                                       "ServerPort":"'     || DBPort                    ||'",
                                       "CodAlerta":"'      || CodAlerta::varchar        ||'",
                                       "Skema":"'          || skema                     ||'"
                                     }';



SELECT status, content into astatus, aContent
FROM http_post(URL_WMESERVICE,
'{ ' ||   AlertaInfo  || '}',

 'application/x-www-form-urlencoded');
 --delete from x;
 --insert into x(view_name) values (aContent);
 if instrb(aContent, '"ok"') &gt; 0 then
  return 1;
 else
  return 0;
 end if;

end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mail_utils_dothejob</obj_name>
  <obj_hashval>7a1203eee7e08562cb11d1d23d7197a1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mail_utils_dothejob(amailid numeric, faracommit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
V_REC RECORD;
userid_ numeric;
err_num numeric;
err_msg varchar;
gUserMail varchar;
gPassMail varchar;
gPort NUMERIC;
gServerMail varchar;
gDomain varchar;
gAuthType NUMERIC;
gClientID             varchar(200);
  gClientSecret       varchar(200);
  gAuthEndPoint       varchar(200);
  gAccesTokenEndPoint varchar(200);
  gRefreshToken       varchar(2000);
  gLogOutEndPoint     varchar(200);
  gScopes             varchar(300);
  gOAuth2             NUMERIC;
BEGIN
  --Florin 18.03.2025 - sinc. Oracle
FOR v_rec IN
(
SELECT SENDER, RECIPIENTS, SUBJECT, MESSAGE, MSG, DOMAIN, PORT, HOST, USERID, CodFirma, CodServer
FROM mailuri
WHERE
   codmail = aMailID
)
LOOP
BEGIN
PERFORM PKG_USERFIRME_GET_USER_CREDENTIAL_ext( v_rec.USERID, v_rec.CodServer, v_rec.CodFirma, gUserMail, gPassMail, gPort, gServerMail, gDomain, gAuthType,
  gClientID,
  gClientSecret,
  gAuthEndPoint,
  gAccesTokenEndPoint,
  gLogOutEndPoint,
  gScopes);
PERFORM pkg_mail_SetCustomParams( v_rec.Host, gPort, gDomain, gAuthType, gUserMail, gPassMail);
PERFORM pkg_mail_Send_mail( v_rec.Sender, v_rec.Recipients, v_rec.Subject, Coalesce( v_rec.msg, v_rec.Message), aMailID);
EXCEPTION WHEN OTHERS THEN
err_num := SQLCODE;
err_msg := SQLERRM;
UPDATE mailuri m
SET
m.eroare = err_msg
WHERE
 m.codmail = aMailID
;
SELECT userid
INTO userid_
FROM mailuri
WHERE
   codmail = aMailID;
INSERT INTO winmadmin.mesaje
(
codmesaj, text, from_user, skemafirma, data, tip_mesaj, dataafis
)
VALUES
(
WINMADMIN.SEQ_MESAJE_CODMESAJ.NEXTVAL, 'Eroare la trimitere eMail:' || v_rec.RECIPIENTS, 'SendMail', user, CURRENT_TIMESTAMP, 0, CURRENT_TIMESTAMP
);
INSERT INTO winmadmin.mesaje1
(
codmesaj1, codmesaj, to_user, sters, citit
)
VALUES
(
winmadmin.seq_mesaje1_codmesaj1.nextval, winmadmin.seq_mesaje_codmesaj.currval, (SELECT PKG_USERFIRME_GETUSERNAME.WME_RESULT FROM PKG_USERFIRME_GETUSERNAME(NULL, USERID_)), 0, 0
);
IF  FaraCommit &lt;&gt; 1
THEN
--&lt;sstcommit&gt;
END IF;
END;
END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mail_utils_postdocumente</obj_name>
  <obj_hashval>055d339605f0925087f5696b99087348</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mail_utils_postdocumente(acoddoc numeric, atipdoc numeric, aowner character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
BEGIN
  --Florin 19.09.2024 - corectii
EXECUTE 'delete from ' || aOwner || '.documente d where d.coddoc = ' || aCodDoc || ' and d.tipdoc = ' || aTipDoc;
EXECUTE 'insert into ' || aOwner || '.documente(coddocument,coddoc,tipdoc,filename,doc,obs,userid,datacreare) ' || 'select ' || aOwner || 'nextval(''seq_documente_coddocument''), coddoc,tipdoc,filename,doc,obs,GETUSERID(),current_date ' || 'from tmp_documente ';
--&lt;sstcommit&gt;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mail_utils_postrecord_mail</obj_name>
  <obj_hashval>7d13897d74db4f7a01e92f85e0c77d5d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mail_utils_postrecord_mail()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  iCodMail numeric;
  aUserID  numeric;
BEGIN
  --Florin 20.12.2022 - sinc. Oracle
  --Adina 20.03.2021
  iCodMail := NEXTVAL('SEQ_MAILURI_CODMAIL');
  --SELECT NEXTVAL('SEQ_MAILURI_CODMAIL') INTO iCodMail;

  aUserID := current_setting('PKG_GLOBALS.USERID', true)::numeric;

  INSERT INTO mailuri(CODMAIL, SENDER, RECIPIENTS, SUBJECT, MESSAGE, MSG, USERID, DATA, EROARE, WEBSERVER, status, host, port, domain, Codfirma, CodServer, coddoc, coddoc1, tipdoc)
  SELECT iCodMail, SENDER, RECIPIENTS, SUBJECT, MESSAGE, MSG, aUserID, CURRENT_TIMESTAMP, EROARE, WEBSERVER, 0, host, port, domain, current_setting('PKG_GLOBALS.CODFIRMA', true)::numeric, CodServer, coddoc, coddoc1, tipdoc
  FROM tmp_mailuri;

  INSERT INTO mailuri1(CODMAIL1, CODMAIL, FileName, ATTACHFILE)
  SELECT NEXTVAL('SEQ_MAILURI1_CODMAIL1'), iCodMail, FileName, ATTACHFILE
  FROM tmp_mailuri1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mail_utils_prepare_mail</obj_name>
  <obj_hashval>82c5789a477298dcb674a47b450b9b07</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mail_utils_prepare_mail(icodserver numeric, zileafter numeric, instant numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aJobName   varchar;
  iCodMail   numeric;
  aUserID    numeric;
  err_cde    numeric;
  err_msg    varchar;
  DataMail   date;
  aWEBSERVER numeric;
BEGIN
  --Adina 20.03.2021 - sinc.Oracle - oricum nu e folosita ac.functie
  SELECT NEXTVAL('SEQ_MAILURI_CODMAIL') INTO iCodMail;

  IF  COALESCE( instant, 0) = 0 THEN
    aUserID := 0;
  ELSE
    aUserID := (SELECT pkg_globals_GETUSERID.WME_RESULT FROM pkg_globals_GETUSERID(NULL,NULL));
  END IF;

  select COALESCE(WEBSERVER, 0) into aWEBSERVER from tmp_mailuri;

  INSERT INTO mailuri(CODMAIL, SENDER, RECIPIENTS, SUBJECT, MESSAGE, MSG, USERID, DATA, EROARE,WEBSERVER, status, host, port, domain, Codfirma, CodServer, coddoc, coddoc1, tipdoc)
  SELECT iCodMail,
         Replace( CASE WHEN  Instr( SENDER, '@') = 0 THEN SENDER || '@' || DOMAIN ELSE SENDER END , '@' || Domain || '@' || Domain, '@' || Domain),
         RECIPIENTS, SUBJECT, MESSAGE, COALESCE( MSG, Message), aUserID, CURRENT_TIMESTAMP, EROARE,WEBSERVER, 0, host, port, domain,
         (SELECT pkg_globals_GETCODFIRMA.WME_RESULT FROM pkg_globals_GETCODFIRMA(NULL,NULL)),
         iCodServer, coddoc, coddoc1, tipdoc
  FROM tmp_mailuri;

  INSERT INTO mailuri1(CODMAIL1, CODMAIL, FileName, ATTACHFILE)
  SELECT NEXTVAL('SEQ_MAILURI1_CODMAIL1'), iCodMail, FileName, ATTACHFILE FROM tmp_mailuri1;

  INSERT INTO mailuridocs(codmaildoc, codmail, coddoc1, coddoc, tipdoc, codagenda)
  SELECT NEXTVAL('SEQ_MAILURIDOCS_CODMAILDOC'), iCodMail, coddoc1, coddoc, tipdoc, codagenda FROM tmp_mailuridocs;

  if aWEBSERVER = 0 then
    IF  COALESCE( instant, 0) = 0 THEN
      aJobName := 'Mail' || (SELECT pkg_globals_GETCODFIRMA.WME_RESULT FROM pkg_globals_GETCODFIRMA(NULL,NULL)) || '_' || iCodMail;
      BEGIN
        DataMail := CURRENT_TIMESTAMP + ZileAfter;
        PERFORM dbms_scheduler.create_job( job_name =&gt; aJobName, job_type =&gt; 'STORED_PROCEDURE', job_action =&gt; 'pkg_mail_utils.DoTheJob', start_date =&gt; DataMail, comments =&gt; 'eMail by Oracle', auto_drop =&gt; true, number_of_arguments =&gt; 1);
        PERFORM dbms_scheduler.set_job_argument_value( job_name =&gt; aJobName, argument_position =&gt; 1, argument_value =&gt; iCodMail);
        PERFORM dbms_scheduler.enable( aJobName);
      EXCEPTION WHEN OTHERS THEN
        err_cde := SQLCODE;
        err_msg := SQLERRM;
        UPDATE mailuri
        SET
        eroare = err_cde || '-' || err_msg
        WHERE
         codmail = iCodMail;
      END;
    ELSIF COALESCE( instant, 0) = 1 THEN
      PERFORM PKG_MAIL_UTILS_DoTheJob( iCodMail,NULL);
    END IF;
  END IF;

--  IF  COALESCE( instant, 0) = 0 THEN
--    aUserID := 0;
--  ELSE
--    aUserID := (SELECT pkg_globals_GETUSERID.WME_RESULT FROM pkg_globals_GETUSERID(NULL,NULL));
--  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mail_utils_testsendemail</obj_name>
  <obj_hashval>3783ddc554e553d7245784d5e2ba6771</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mail_utils_testsendemail()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
PERFORM pkg_globals_sETCODFIRMA( 6389);
PERFORM pkg_globals_SETUSERID( 1266);
DELETE FROM TMP_MAILURI1;
INSERT INTO TMP_MAILURI
(
SENDER, RECIPIENTS, SUBJECT, HOST, PORT, DOMAIN, MESSAGE
)
VALUES
(
'miki@winmentor.ro', 'miki@winmentor.ro', 'WinMENTOR Enterprise', 'mail.winmentor.ro', 25, 'winmentor.ro', 'xxxxxxxxxxxxx'
);
--&lt;sstcommit&gt;
PERFORM pkg_mail_utils_prepare_mail( 0, 1,NULL);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mail_utils_testusermail</obj_name>
  <obj_hashval>16e19c073b4ca4586ae1961f5d75feaf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mail_utils_testusermail(INOUT wme_result character varying, INOUT acoduser numeric, INOUT acodgrup numeric, INOUT acodfirma numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
smtp_host varchar;
smtp_port numeric;
smtp_domain varchar;
authType numeric;
usern varchar;
pass varchar;
email varchar;
aResult varchar;
begin
PERFORM winmadmin.pkg_userfirme.get_user_credential( iCodUser =&gt; aCodUser, iCodGrup =&gt; aCodGrup, iCodFirma =&gt; aCodFirma, aID1 =&gt; usern, aID2 =&gt; pass, iPort =&gt; smtp_port, aServMail =&gt; smtp_host, aDomeniuMail =&gt; smtp_domain, iAuthType =&gt; authType);
PERFORM pkg_mail_SetCustomParams( smtp_host, smtp_port, smtp_domain, AuthType, usern, pass);
aResult := (SELECT pkg_mail_test_mail_data.WME_RESULT FROM pkg_mail_test_mail_data(NULL,NULL));
WME_Result :=  aResult;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mascaserart_sp_deleterecord</obj_name>
  <obj_hashval>5903d2bd6af529493a063603cc7234e4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mascaserart_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_MASCASERART_SP_LOCKRECORD( RecId);
  DELETE FROM MASCASERART1 WHERE CodMasca = RecId;
  DELETE FROM MASCASERART  WHERE CodMasca = RecId;
  PERFORM NotifyModif( 2, RecId, 'MASCASERART');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mascaserart_sp_gotorecord</obj_name>
  <obj_hashval>ee041a1766f54442706934b96191d840</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mascaserart_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_MASCASERART(CodMasca, Masca)
  SELECT CodMasca, Masca FROM MASCASERART WHERE CodMasca = RecId;

  INSERT INTO TMP_MASCASERART1(CODMASCA1, CODMASCA, DENELEMENT, VALORI, ELEMENT, LUNGIME, FILL)
  SELECT CODMASCA1, CODMASCA, DENELEMENT, VALORI, ELEMENT, LUNGIME, FILL
  FROM MASCASERART1 WHERE CodMasca = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mascaserart_sp_lockrecord</obj_name>
  <obj_hashval>fc314d89775e2a11180a90183e8e3eb8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mascaserart_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodMasca INTO Tmp FROM MASCASERART WHERE CodMasca = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mascaserart_sp_postrecords</obj_name>
  <obj_hashval>00e960369cc4a4bf6d53ff476347bc0c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mascaserart_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  IF  Operation = 0 THEN
    SELECT CodMasca INTO RecId FROM TMP_MASCASERART;

    UPDATE MASCASERART
    SET
    Masca = (SELECT Masca FROM TMP_MASCASERART)
    WHERE CodMasca = RecId;

    DELETE FROM MASCASERART1 WHERE CodMasca = RecId and CodMasca1 NOT IN (SELECT CodMasca1 FROM TMP_MASCASERART1);

    FOR v_rec IN (SELECT * FROM TMP_MASCASERART1 WHERE CodMasca1 &gt; 0) LOOP
      UPDATE MASCASERART1
      SET
      DENELEMENT = V_REC.DENELEMENT,
      VALORI     = V_REC.VALORI,
      ELEMENT    = V_REC.ELEMENT,
      LUNGIME    = V_REC.LUNGIME,
      FILL       = V_REC.FILL
      WHERE
       CodMasca1 = v_rec.CodMasca1;
    END LOOP;

    INSERT INTO MASCASERART1(CODMASCA1, CODMASCA, DENELEMENT, VALORI, ELEMENT, LUNGIME, FILL)
    SELECT NEXTVAL('SEQ_MASCASERART1_CODMASCA1'), RECID, DENELEMENT, VALORI, ELEMENT, LUNGIME, FILL
    FROM TMP_MASCASERART1 WHERE CodMasca1 &lt; 0;
  ELSE
    SELECT NEXTVAL('SEQ_MASCASERART_CODMASCA') INTO RecId;

    INSERT INTO MASCASERART(CODMASCA, MASCA)
    SELECT RECID, MASCA FROM TMP_MASCASERART;

    INSERT INTO MASCASERART1(CODMASCA1, CODMASCA, DENELEMENT, VALORI, ELEMENT, LUNGIME, FILL)
    SELECT NEXTVAL('SEQ_MASCASERART1_CODMASCA1'), RecId, DENELEMENT, VALORI, ELEMENT, LUNGIME, FILL
    FROM Tmp_MascaSerArt1;
  END IF;

  PERFORM NotifyModif( Operation, RecId, 'MASCASERART');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_medex_listaactuala</obj_name>
  <obj_hashval>0b3e3dfbcc2534547847ef264c54a9ca</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_medex_listaactuala(INOUT wme_result numeric, INOUT datastart date)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  datamin date;
  datamax date;
  oData   date;
  aResult numeric;
  aCount  numeric;
begin
  SELECT count(codmedex) INTO aCount FROM medex;

  IF  aCount = 0 THEN
    aResult := 0;
  ELSE
    BEGIN
      oData := to_date('01.' || coalesce((current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric)::varchar,'') || '.' || coalesce((current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric)::varchar,''), 'dd.mm.yyyy');
      SELECT max(m.datalista) INTO datamin FROM medex m WHERE odata &gt;= m.datalista;
    EXCEPTION WHEN others THEN
      datamin := to_date('01.01.1000', 'dd.mm.yyyy');
    END;

    BEGIN
      oData := to_date((Last_day(to_date('01.' || coalesce((current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric)::varchar,'') || '.' || coalesce((current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric)::varchar,''), 'dd.mm.yyyy')))::varchar || '.' || coalesce((current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric)::varchar,'') || '.' || coalesce((current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric)::varchar,''), 'dd.mm.yyyy');
      SELECT min(m.datalista) INTO datamax FROM medex m WHERE odata &lt; m.datalista;
    EXCEPTION WHEN others THEN
      datamax := to_date('31.12.9999', 'dd.mm.yyyy');
    END;

    IF  datastart &lt; datamax and  datastart &gt;= datamin THEN
      aResult := 1;
    ELSE
      aResult := 0;
    END IF;
  END IF;

  WME_Result :=  aResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_medex_med1valid</obj_name>
  <obj_hashval>1261115045a34d5682e4964db6ad1926</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_medex_med1valid(INOUT wme_result numeric, INOUT acodmedex1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  eBun  numeric;
  datas numeric;
  dataf numeric;
begin
  eBun := 0;
  SELECT extract( YEAR FROM M1.VALIDDELA) * 12 + extract( MONTH FROM M1.VALIDDELA)
  INTO datas
  FROM medex1 M1
  WHERE codmedex1 = aCodMedex1;

  SELECT extract( YEAR FROM M1.VALIDPANALA) * 12 + extract( MONTH FROM M1.VALIDPANALA)
  INTO dataf
  FROM medex1 M1
  WHERE codmedex1 = aCodMedex1;

  IF  current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric * 12 + current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric &lt;= dataf and  current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric * 12 + current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric &gt;= datas
  THEN
    eBun := 1;
  ELSE
    eBun := 0;
  END IF;

  WME_Result :=  eBun;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_medex_med2valid</obj_name>
  <obj_hashval>9a8adaa6a9a006cdc4698ef18ba2ef7e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_medex_med2valid(INOUT wme_result numeric, INOUT acodmedex2 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  eBun  numeric;
  datas numeric;
  dataf numeric;
begin
  eBun := 0;
  SELECT extract( YEAR FROM M2.VALIDDELA) * 12 + extract( MONTH FROM M2.VALIDDELA)
  INTO datas
  FROM medex2 M2
  WHERE codmedex2 = aCodMedex2;

  SELECT extract( YEAR FROM M2.VALIDPANALA) * 12 + extract( MONTH FROM M2.VALIDPANALA)
  INTO dataf
  FROM medex2 M2
  WHERE codmedex2 = aCodMedex2;

  IF  current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric * 12 + current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric &lt;= dataf and  current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric * 12 + current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric &gt;= datas
  THEN
    eBun := 1;
  ELSE
    eBun := 0;
  END IF;

  WME_Result :=  eBun;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_medex_sp_deleterecord</obj_name>
  <obj_hashval>a0a133131dfa179845de8f6de08eef92</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_medex_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_MEDEX_SP_LOCKRECORD(RecId);
  DELETE FROM MEDEX_TARI WHERE CodMedex = RecId;
  DELETE FROM MEDEX2     WHERE CodMedex = RecId;
  DELETE FROM MEDEX1     WHERE CodMedex = RecId;
  DELETE FROM MEDEX      WHERE CodMedex = RecId;
  PERFORM NotifyModif(2, RECID, 'MEDEX');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_medex_sp_gotorecord</obj_name>
  <obj_hashval>7b1d55b923cc51fcfe2f86e03b21141a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_medex_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_MEDEX(CodMedex, DataLista, Obs)
  (SELECT CodMedex, DataLista, Obs FROM MEDEX WHERE CodMedex = RecId);

  INSERT INTO TMP_MEDEX_TARI(CODMEDEXT, CODMEDEX, COD, TARA)
  SELECT CODMEDEXT, CODMEDEX, COD, TARA FROM MEDEX_TARI WHERE CodMedex = RecId;

  INSERT INTO TMP_MEDEX1(CODMEDEX1, CODMEDEX, CODCIM, DENUMIRE, PREZENTARE, NARCOTIC, FRACTIONAL, SPECIAL, AREBIOECHIVALENT, CANT, PRETAM, PRETRID, PRESCRIERE, VALIDDELA, VALIDPANALA, DCI, CONC, FORMAFARM, PRODUCATOR, TARA, GRUPA)
  SELECT CODMEDEX1, CODMEDEX, CODCIM, DENUMIRE, PREZENTARE, NARCOTIC, FRACTIONAL, SPECIAL, AREBIOECHIVALENT, CANT, PRETAM, PRETRID, PRESCRIERE, VALIDDELA, VALIDPANALA, DCI, CONC, FORMAFARM, PRODUCATOR, TARA, GRUPA
  FROM MEDEX1 WHERE CodMedex = RecId;

  INSERT INTO TMP_MEDEX2(CODMEDEX2, CODMEDEX, TIPCOMPENS, CODCIM, CODBOALA, PRETAM, PRETAMUT, COPLATA, COPLATA90, PRETRID, PRETREF, LEGISPECIALE, APROBARE, VALPESTE, SPECIALITATE, INSULINA, DCI, GRUPA, VALIDDELA, VALIDPANALA, nhpCode)
  SELECT CODMEDEX2, CODMEDEX, TIPCOMPENS, CODCIM, CODBOALA, PRETAM, PRETAMUT, COPLATA, COPLATA90, PRETRID, PRETREF, LEGISPECIALE, APROBARE, VALPESTE, SPECIALITATE, INSULINA, DCI, GRUPA, VALIDDELA, VALIDPANALA, nhpCode
  FROM MEDEX2 WHERE CodMedex = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_medex_sp_postrecords</obj_name>
  <obj_hashval>d6af1d5b3450b192d96d489e9d1adb02</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_medex_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  IF  Operation = 0 THEN
    SELECT CodMedex INTO RecId FROM TMP_MEDEX;

    UPDATE MEDEX
    SET
    (DataLista, Obs) = (SELECT DataLista, Obs FROM TMP_MEDEX)
    WHERE CodMedex = RecId;

    DELETE FROM MEDEX1 C1
    WHERE C1.CodMedex = RecId and  NOT  EXISTS (SELECT TMP.CodMedex1 FROM TMP_MEDEX1 TMP WHERE TMP.CodMedex1 = C1.CodMedex1);

    INSERT INTO MEDEX1(CODMEDEX1, CODMEDEX, CODCIM, DENUMIRE, PREZENTARE, NARCOTIC, FRACTIONAL, SPECIAL, AREBIOECHIVALENT, CANT, PRETAM, PRETRID, PRESCRIERE, VALIDDELA, VALIDPANALA, DCI, CONC, FORMAFARM, PRODUCATOR, TARA, GRUPA)
    SELECT NEXTVAL('SEQ_MEDEX1_CODMEDEX1'), RecId, CODCIM, DENUMIRE, PREZENTARE, NARCOTIC, FRACTIONAL, SPECIAL, AREBIOECHIVALENT, CANT, PRETAM, PRETRID, PRESCRIERE, VALIDDELA, VALIDPANALA, DCI, CONC, FORMAFARM, PRODUCATOR, TARA, GRUPA
    FROM TMP_MEDEX1 WHERE CodMedex1 &lt; 0;

    FOR v_rec IN (SELECT * FROM TMP_MEDEX1 WHERE COALESCE(CodMedex1, -1) &gt; 0 ORDER BY CodMedex1) LOOP
      UPDATE MEDEX1
      SET
      CODCIM           = v_Rec.Codcim,
      DENUMIRE         = v_rec.DENUMIRE,
      PREZENTARE       = v_Rec.Prezentare,
      NARCOTIC         = v_Rec.Narcotic,
      FRACTIONAL       = v_rec.FRACTIONAL,
      SPECIAL          = v_Rec.SPECIAL,
      AREBIOECHIVALENT = v_rec.AREBIOECHIVALENT,
      CANT             = v_Rec.CANT,
      PRETAM           = v_Rec.Pretam,
      PRETRID          = v_rec.PRETRID,
      PRESCRIERE       = v_Rec.PRESCRIERE,
      VALIDDELA        = v_rec.VALIDDELA,
      VALIDPANALA      = v_Rec.VALIDPANALA,
      DCI              = v_Rec.DCI,
      CONC             = v_Rec.CONC,
      FORMAFARM        = FORMAFARM,
      PRODUCATOR       = v_Rec.PRODUCATOR,
      TARA             = v_rec.TARA,
      GRUPA            = v_Rec.GRUPA
      WHERE
       CodMedex1 = v_rec.CodMedex1;
    END LOOP;

    DELETE FROM MEDEX2 C2 WHERE C2.CodMedex = RecId and  NOT  EXISTS (SELECT TMP.CodMedex2 FROM TMP_MEDEX2 TMP WHERE TMP.CodMedex2 = C2.CodMedex2);

    INSERT INTO MEDEX2(CODMEDEX2, CODMEDEX, TIPCOMPENS, CODCIM, CODBOALA, PRETAM, PRETAMUT, COPLATA, COPLATA90, PRETRID, PRETREF, LEGISPECIALE, APROBARE, VALPESTE, SPECIALITATE, INSULINA, DCI, GRUPA, VALIDDELA, VALIDPANALA, nhpCode)
    SELECT NEXTVAL('SEQ_MEDEX2_CODMEDEX2'), RecId, TIPCOMPENS, CODCIM, CODBOALA, PRETAM, PRETAMUT, COPLATA, COPLATA90, PRETRID, PRETREF, LEGISPECIALE, APROBARE, VALPESTE, SPECIALITATE, INSULINA, DCI, GRUPA, VALIDDELA, VALIDPANALA, nhpCode
    FROM TMP_MEDEX2 WHERE CodMedex2 &lt; 0;

    FOR v_rec IN (SELECT * FROM TMP_MEDEX2 WHERE COALESCE(CodMedex2, -1) &gt; 0 ORDER BY CodMedex2) LOOP
      UPDATE MEDEX2
      SET
      TIPCOMPENS   = v_rec.TIPCOMPENS,
      CODCIM       = v_rec.CODCIM,
      CODBOALA     = v_Rec.CODBOALA,
      PRETAM       = v_Rec.PRETAM,
      PRETAMUT     = v_rec.PRETAMUT,
      COPLATA      = v_rec.COPLATA,
      COPLATA90    = v_rec.COPLATA90,
      PRETRID      = v_Rec.PRETRID,
      PRETREF      = v_rec.PRETREF,
      LEGISPECIALE = v_rec.LEGISPECIALE,
      APROBARE     = v_Rec.APROBARE,
      VALPESTE     = v_Rec.VALPESTE,
      SPECIALITATE = v_Rec.SPECIALITATE,
      INSULINA     = v_Rec.INSULINA,
      DCI          = v_Rec.DCI,
      GRUPA        = v_Rec.GRUPA,
      VALIDDELA    = v_Rec.VALIDDELA,
      VALIDPANALA  = v_Rec.VALIDPANALA,
      nhpCode      = v_rec.nhpcode
      WHERE
       CodMedex2 = v_rec.CodMedex2;
    END LOOP;

    DELETE FROM MEDEX_TARI T WHERE T.CodMedex = RecId and  NOT  EXISTS (SELECT TMP.CodMedexT FROM TMP_MEDEX_TARI TMP WHERE TMP.CodMedexT = T.CodMedexT);

    INSERT INTO MEDEX_TARI(CODMEDEXT, CODMEDEX, COD, TARA)
    SELECT NEXTVAL('SEQ_MEDEXT_CODMEDEXT'), RecId, COD, TARA FROM TMP_MEDEX_TARI WHERE CodMedexT &lt; 0;

    FOR v_rec IN (SELECT * FROM TMP_MEDEX_TARI WHERE COALESCE(CodMedexT, -1) &gt; 0 ORDER BY CodMedexT) LOOP
      UPDATE MEDEX_TARI
      SET
      COD  = v_Rec.Cod,
      TARA = v_Rec.Tara
      WHERE
       CodMedexT = v_rec.CodMedexT;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_MEDEX_CODMEDEX') INTO RecId;

    INSERT INTO MEDEX(CodMedex, DataLista, Obs)
    (SELECT RecId, DataLista, Obs FROM TMP_MEDEX);

    INSERT INTO MEDEX1(CODMEDEX1, CODMEDEX, CODCIM, DENUMIRE, PREZENTARE, NARCOTIC, FRACTIONAL, SPECIAL, AREBIOECHIVALENT, CANT, PRETAM, PRETRID, PRESCRIERE, VALIDDELA, VALIDPANALA, DCI, CONC, FORMAFARM, PRODUCATOR, TARA, GRUPA)
    SELECT NEXTVAL('SEQ_MEDEX1_CODMEDEX1'), RecId, CODCIM, DENUMIRE, PREZENTARE, NARCOTIC, FRACTIONAL, SPECIAL, AREBIOECHIVALENT, CANT, PRETAM, PRETRID, PRESCRIERE, VALIDDELA, VALIDPANALA, DCI, CONC, FORMAFARM, PRODUCATOR, TARA, GRUPA
    FROM TMP_MEDEX1;

    INSERT INTO MEDEX2(CODMEDEX2, CODMEDEX, TIPCOMPENS, CODCIM, CODBOALA, PRETAM, PRETAMUT, COPLATA, COPLATA90, PRETRID, PRETREF, LEGISPECIALE, APROBARE, VALPESTE, SPECIALITATE, INSULINA, DCI, GRUPA, VALIDDELA, VALIDPANALA, nhpCode)
    SELECT NEXTVAL('SEQ_MEDEX2_CODMEDEX2'), RecId, TIPCOMPENS, CODCIM, CODBOALA, PRETAM, PRETAMUT, COPLATA, COPLATA90, PRETRID, PRETREF, LEGISPECIALE, APROBARE, VALPESTE, SPECIALITATE, INSULINA, DCI, GRUPA, VALIDDELA, VALIDPANALA, nhpCode
    FROM TMP_MEDEX2;

    INSERT INTO MEDEX_TARI(CODMEDEXT, CODMEDEX, COD, TARA)
    SELECT NEXTVAL('SEQ_MEDEXT_CODMEDEXT'), RecId, COD, TARA
    FROM TMP_MEDEX_TARI;
  END IF;

  PERFORM NotifyModif(OPERATION, RECID, 'MEDEX');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_menudash_sp_deleterecord</obj_name>
  <obj_hashval>73241183118c9891b1e19eb0f0dc895e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_menudash_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  CP      numeric;
  aListID numeric;
begin
  PERFORM PKG_MENUDASH_SP_LOCKRECORD( RecId);
  SELECT listid INTO aListId FROM menuDash WHERE CodMenuDash = recid;
  DELETE FROM MENUDash WHERE CodMenuDash = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_menudash_sp_gotorecord</obj_name>
  <obj_hashval>3f46a3639335d0a39a2f758703a641c1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_menudash_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_MENUDash(CodMenuDash, Caption, Modul, Menu, Prog, Uni, listid)
  (SELECT CodMenuDash, Caption, Modul, Menu, Prog, Uni, listid FROM MENUDash WHERE CodMenuDash = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_menudash_sp_insertrecord</obj_name>
  <obj_hashval>46bf2b30ddfeaadf764027c711200ad8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_menudash_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_MENUDash (CodMenuDash) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_menudash_sp_lockrecord</obj_name>
  <obj_hashval>2a82d9b781e2e073359165a677270bfb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_menudash_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodMenuDash INTO Tmp FROM MENUDash WHERE CodMenuDash = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_menudash_sp_postrecords</obj_name>
  <obj_hashval>e0cb177b94debb39f7cf61c16dc6d1dc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_menudash_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  CP      numeric;
  aListID numeric := 0;
  cnt     numeric;
begin
  IF  Operation = 0 THEN
    SELECT CodMenuDash INTO RecId FROM TMP_MENUDash;

    UPDATE MENUDash
    SET
    (Caption, Modul, Menu, Prog, Uni, listid) = (SELECT Caption, Modul, Menu, Prog, Uni, listid FROM TMP_MENUDash)
    WHERE CodMenuDash = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_MENUDASH_CODMENUDASH') INTO RecId;

    INSERT INTO MENUDash(CodMenuDash, Caption, Modul, Menu, Prog, Uni, listid)
    (SELECT RecId, Caption, Modul, Menu, Prog, Uni, listid FROM TMP_MENUDash);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_menudate_sp_deleterecord</obj_name>
  <obj_hashval>78b4714c4b2c2c029164a595ab2d2b96</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_menudate_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM MENUDATE1 WHERE CODMENUDATE = RECID;
  DELETE FROM MENUDATE  WHERE CODMENUDATE = RECID;
  PERFORM NotifyModif( 2, RECID, 'MENUDATE');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_menudate_sp_gotorecord</obj_name>
  <obj_hashval>eb434f8f32681782cb171963a612bafd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_menudate_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_MENUDATE(CODMENUDATE, DEN_MENU, USERID, Nrbuton)
  SELECT CODMENUDATE, DEN_MENU, USERID, nrbuton FROM MENUDATE WHERE CODMENUDATE = RECID;

  INSERT INTO TMP_MENUDATE1(CODMENUDATE1, CODMENUDATE, DEN_MENU, ACTION, Indexlocal)
  SELECT CODMENUDATE1, CODMENUDATE, DEN_MENU, ACTION, indexlocal FROM MENUDATE1 WHERE CODMENUDATE = RECID ORDER BY indexlocal ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_menudate_sp_insertrecord</obj_name>
  <obj_hashval>67fbf42e5ec1370677f34f3b7edad456</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_menudate_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_MENUDATE(CODMENUDATE)   VALUES(0);
  INSERT INTO TMP_MENUDATE1(CODMENUDATE1) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_menudate_sp_lockrecord</obj_name>
  <obj_hashval>a42d2f43c83bdfdd4e1e11bdaeb84bf1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_menudate_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMP numeric;
begin
  SELECT CODMENUDATE INTO TMP FROM MENUDATE WHERE CODMENUDATE = RECID FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_menudate_sp_postrecords</obj_name>
  <obj_hashval>a71bd38c565a9c589337de61b4c19fcc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_menudate_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  IF  OPERATION = 0 THEN
    SELECT CODMENUDATE INTO RECID FROM TMP_MENUDATE;

    UPDATE MENUDATE M
    SET
    (M.DEN_MENU, M.USERID, M.NRBUTON) = (SELECT T.DEN_MENU, T.USERID, T.NRBUTON FROM TMP_MENUDATE T)
    WHERE
     M.CODMENUDATE = RECID;

    DELETE FROM MENUDATE1 M1
    WHERE M1.CODMENUDATE = RECID AND  NOT  EXISTS (SELECT T1.CODMENUDATE FROM TMP_MENUDATE1 T1 WHERE M1.CODMENUDATE1 = T1.CODMENUDATE1);

    FOR V_REC IN (SELECT * FROM TMP_MENUDATE1) LOOP
      UPDATE MENUDATE1 M1
      SET
      M1.DEN_MENU   = V_REC.DEN_MENU,
      M1.ACTION     = V_REC.ACTION,
      M1.INDEXLOCAL = V_REC.INDEXLOCAL
      WHERE
       M1.CODMENUDATE1 = V_REC.CODMENUDATE1;
    END LOOP;

    INSERT INTO MENUDATE1(CODMENUDATE1, CODMENUDATE, DEN_MENU, ACTION, INDEXLOCAL)
    SELECT NEXTVAL('SEQ_MENUDATE1_CODMENUDATE1'), RECID, DEN_MENU, ACTION, INDEXLOCAL FROM TMP_MENUDATE1 WHERE CODMENUDATE1 &lt; 0;
  ELSE
    SELECT NEXTVAL('SEQ_MENUDATE_CODMENUDATE') INTO RECID;

    INSERT INTO MENUDATE(CODMENUDATE, DEN_MENU, USERID, NRBUTON)
    SELECT RECID, DEN_MENU, (SELECT PKG_GLOBALS_GETUSERID.WME_RESULT FROM PKG_GLOBALS_GETUSERID(NULL,NULL)), NRBUTON FROM TMP_MENUDATE;

    INSERT INTO MENUDATE1(CODMENUDATE1, CODMENUDATE, DEN_MENU, ACTION, INDEXLOCAL)
    SELECT NEXTVAL('SEQ_MENUDATE1_CODMENUDATE1'), RECID, DEN_MENU, ACTION, INDEXLOCAL FROM TMP_MENUDATE1;
  END IF;

  PERFORM NotifyModif( OPERATION, RECID, 'MENUDATE');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mese_sp_gotorecord</obj_name>
  <obj_hashval>5fabb478127fe8266975f25620fde2fc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mese_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 09.04.2024 - fixat 61609
  --Florin 19.05.2022
  INSERT INTO TMP_MESE(CODMASA, CODSALA, INDEXLOCAL, NUMARLOCURI, TEXTAFISARE, FORMA, WIDTH, HEIGHT, MODPLATAIMPLICIT, PROTOCOL)
  SELECT CODMASA, CODSALA, INDEXLOCAL, NUMARLOCURI, TEXTAFISARE, FORMA, WIDTH, HEIGHT, MODPLATAIMPLICIT, PROTOCOL FROM MESE WHERE CODMASA = RecId;

  UPDATE TMP_MESE M SET DENSALA = (SELECT DENUMIRE FROM SALI S WHERE S.CODSALA = M.CODSALA);

  INSERT INTO TMP_MESE1 (CODMASA1, CODMASA, CODOSPATAR, OSPATAR)
  SELECT CODMASA1,
         CODMASA,
         CODOSPATAR,
         NUME || ' ' || PRENUME
  FROM
    MESE1 M1,
    OSPATARI O,
    NPERS P
  WHERE
    CODMASA = RECID
    AND M1.CODOSPATAR = O.COD
    AND O.CODPERS = P.CODPERS ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mese_sp_postrecords</obj_name>
  <obj_hashval>7f42745ed6bbe57c5e9b041cc3cc445e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mese_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_rec record;
BEGIN
  --Florin 09.04.2024 - fixat 61609
  --Florin 19.05.2022
  IF  Operation = 0 THEN
    SELECT CODMASA INTO RecId FROM TMP_MESE;

    UPDATE MESE
    SET
    (CODSALA, INDEXLOCAL, NUMARLOCURI, TEXTAFISARE, FORMA, MODPLATAIMPLICIT, PROTOCOL) = (SELECT CODSALA, INDEXLOCAL, NUMARLOCURI, TEXTAFISARE, FORMA, MODPLATAIMPLICIT, PROTOCOL FROM TMP_MESE)
    WHERE
     CODMASA = RECID;
  ELSE
    SELECT NEXTVAL('SEQ_MESE_CODMASA') INTO RECID;

    INSERT INTO MESE(CODMASA, CODSALA, INDEXLOCAL, NUMARLOCURI, TEXTAFISARE, FORMA, MODPLATAIMPLICIT, PROTOCOL)
    SELECT RECID, CODSALA, INDEXLOCAL, NUMARLOCURI, TEXTAFISARE, FORMA, MODPLATAIMPLICIT, PROTOCOL FROM TMP_MESE;
  END IF;

   DELETE FROM MESE1 WHERE CODMASA = RECID AND CODMASA1 NOT IN (SELECT CODMASA1 FROM TMP_MESE1);

    FOR V_REC IN (SELECT * FROM  TMP_MESE1) LOOP
      IF V_REC.CODMASA1 &lt; 0 THEN
        INSERT INTO MESE1 (CODMASA1, CODMASA, CODOSPATAR)
        VALUES (nextval('SEQ_MESE1_CODMASA1'), RECID, V_REC.CODOSPATAR);
      ELSE
        UPDATE MESE1
        SET
          CODOSPATAR = V_REC.CODOSPATAR
        WHERE
          CODMASA1 = V_REC.CODMASA1;
      END IF;
    END LOOP;

  PERFORM NotifyModif( OPERATION, RECID, 'MESE');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mfclasif_sp_deleterecord</obj_name>
  <obj_hashval>b55221a25f7bc49405c5d8dda40725d0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mfclasif_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_MFCLASIF_SP_LOCKRECORD( RecId);
  DELETE FROM MFCLASIF WHERE CodClasif = RecId;
  PERFORM NotifyModif( 2, RECID, 'MFCLASIF');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mfclasif_sp_insertrecord</obj_name>
  <obj_hashval>6054d1d24da13150c36332a687df12a9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mfclasif_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_MFCLASIF (CodClasif) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mfclasif_sp_lockrecord</obj_name>
  <obj_hashval>b2a8deb6f4b6ea306dbd1f9f6b291750</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mfclasif_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodClasif INTO Tmp FROM MFCLASIF WHERE CodClasif = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mfclasif_sp_postrecords</obj_name>
  <obj_hashval>c74d843ad0be9a87e9dec14b8e8d8b9e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mfclasif_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    SELECT CODCLASIF INTO RECID FROM TMP_MFCLASIF;

    UPDATE MFCLASIF
    SET
    (DENUMIRE, SIMBOL, DURATA, DURATAF, DURATAG) = (SELECT DENUMIRE, SIMBOL, DURATA, DURATAF, DURATAG FROM TMP_MFCLASIF)
    WHERE CodClasif = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_MFCLASIF_CODCLASIF') INTO RECID;

    INSERT INTO MFCLASIF(CODCLASIF, SIMBOL, DENUMIRE, DURATA, DURATAF, DURATAG)
    (SELECT RecId, SIMBOL, DENUMIRE, DURATA, DURATAF, DURATAG FROM TMP_MFCLASIF);
  END IF;

  PERFORM NotifyModif( OPERATION, RECID, 'MFCLASIF');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mifix_casare</obj_name>
  <obj_hashval>5412927ceefed86971a0791fc6df0028</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mifix_casare(acodmifix1 numeric, acodies numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  UPDATE mifix1 SET stare = 3 WHERE codmifix1 = acodmifix1;

  FOR v_rec IN
  (
  SELECT l.datalivr, NIR.GEST, NS.PRET, i.NRDOC, i.PREFIXDOC, l1.CANT, i1.CODIES1, I.TIPDOC, MFIX1.CODMIFIX, mfix1.anstart, mfix1.lunastart
  FROM nirstoc ns
      INNER JOIN livr1   l1    ON  l1.codnirstoc    = ns.codnirstoc
      INNER JOIN iesiri1 i1    ON  i1.codies1       = l1.codies1
      INNER JOIN iesiri  i     ON  i.codies         = i1.codies
      INNER JOIN livr    l     ON  l.codies         = i.codies and  l1.codlivr = l.codlivr
      INNER JOIN mifix1  mfix1 ON  mfix1.CODNIRSTOC = ns.codnirstoc
      INNER JOIN nir           ON  nir.codnir       = ns.codnir
  WHERE
     mfix1.codmifix1 = acodMifix1 and  i.codies = aCodIes
  )
  LOOP
    INSERT INTO FISAMF(CODFISAMF, CODMIFIX, CODOPERATIE, DATAOPERATIE, GESTSURSA, GESTDEST, PRETI, PRETE, PREFIXDOC, NRDOC, CANT, OBS, CODDOC1, TIPDOC)
    VALUES(NEXTVAL('SEQ_FISAMF_CODFISAMF'), V_rec.CODMIFIX, 4, V_REC.DATALIVR, V_REC.GEST, V_REC.GEST, V_REC.PRET, V_REC.PRET, V_REC.PREFIXDOC, V_REC.NRDOC, V_REC.CANT, '', V_REC.CODIES1, V_REC.TIPDOC);

    UPDATE jurnal1 SET dirty = 1 WHERE coddoc = v_rec.codmifix and  tipdoc = 36 and  an * 12 + luna &gt;= v_rec.anstart * 12 + v_rec.lunastart;
    EXIT ;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mifix_casarefaracommit</obj_name>
  <obj_hashval>8378e6627e8f92ae1d4d6a87edacf3ef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mifix_casarefaracommit(acodmifix1 numeric, acodies numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Florin 05.04.2024 - fixat 61566
  update mifix1 set stare = 3 where codmifix1 = acodmifix1;
  for v_rec in (select l.datalivr, NIR.GEST, NS.PRET, i.NRDOC, i.PREFIXDOC, l1.CANT, i1.CODIES1, I.TIPDOC, MFIX1.CODMIFIX,
                       mfix1.anstart, mfix1.lunastart
                from nirstoc ns
                     inner join livr1 l1 on l1.codnirstoc = ns.codnirstoc
                     inner join iesiri1 i1 on i1.codies1 = l1.codies1
                     inner join iesiri i on i.codies = i1.codies
                     inner join livr l on l.codies = i.codies and l1.codlivr = l.codlivr
                     INNER JOIN mifix1 mfix1 ON mfix1.CODNIRSTOC = ns.codnirstoc
                     inner join nir on nir.codnir = ns.codnir
                where mfix1.codmifix1 = acodMifix1 and i.codies = aCodIes) loop
    INSERT INTO FISAMF (
      CODFISAMF,
      CODMIFIX,
      CODOPERATIE,
      DATAOPERATIE,
      GESTSURSA,
      GESTDEST,
      PRETI,
      PRETE,
      PREFIXDOC,
      NRDOC,
      CANT,
      OBS,
      CODDOC1,
      TIPDOC)
    VALUES(
      NEXTVAL('SEQ_FISAMF_CODFISAMF'),
      V_rec.CODMIFIX,
      4,
      V_REC.DATALIVR,
      V_REC.GEST,
      V_REC.GEST,
      V_REC.PRET,
      V_REC.PRET,
      V_REC.PREFIXDOC,
      V_REC.NRDOC,
      V_REC.CANT,
      '',
      V_REC.CODIES1,
      V_REC.TIPDOC
      );
    update jurnal1 set dirty = 1 where coddoc = v_rec.codmifix and tipdoc = 36 and an*12+luna &gt;= v_rec.anstart*12+v_rec.lunastart;
    EXIT;
  end loop;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mifix_ct_monitor</obj_name>
  <obj_hashval>63bdbc00b934e28bc9abaa3a36fec369</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mifix_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_MIFIX.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_15';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mifix_empty_mifix_temptables</obj_name>
  <obj_hashval>1a0b0ab1b89af36d46496fd5222efad3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mifix_empty_mifix_temptables()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM tmp_mastermifix;
  DELETE FROM tmp_mifix;
  DELETE FROM tmp_mifixtransf;
  DELETE FROM tmp_fisamf;
  DELETE FROM tmp_jurnal;
  DELETE FROM tmp_jurnal1;
  DELETE FROM tmp_rulaj;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mifix_genmastermifixdinreevaluare</obj_name>
  <obj_hashval>446516ed2efafcb5f3d1b1c98d995637</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mifix_genmastermifixdinreevaluare(acodnirstoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodFiu numeric;
begin
  BEGIN
    SELECT codnirstoc INTO aCodFiu FROM nirstoc WHERE codnirstocparinte = aCodNirStoc;
  EXCEPTION WHEN others THEN
    aCodFiu := 0;
  END;

  IF  aCodFiu &gt; 0 THEN
    INSERT INTO mastermifix(codnirstoc, codclasif, duratan, duratanf, duratang, codanaliza)
    SELECT aCodFiu, codclasif, duratan, duratanf, duratang, codanaliza FROM mastermifix WHERE codnirstoc = aCodNirStoc;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mifix_getct_monitor</obj_name>
  <obj_hashval>b913ec35fa85f0f34f6d2213d19ce050</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mifix_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_MIFIX.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_15';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mifix_getinfomfimb</obj_name>
  <obj_hashval>a09f71791c8a52a9996464b13089e2db</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mifix_getinfomfimb(acodmifiximb numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vINFOMFIMB varchar := '';
begin
  --Florin 25.01.2022 - fixat 52758
  --Bogdan 15.09.2020
  IF COALESCE (aCodMifixImb, 0) &lt;&gt; 0 THEN
    SELECT coalesce (MF.NRINVENTAR::varchar,'') || ' ' || coalesce (O.DENUMIRE,'')
    INTO vINFOMFIMB
    FROM (SELECT  DISTINCT   CODMIFIX,
          LAST_VALUE (CODNIRSTOC) OVER ( partition by CODMIFIX
                           ORDER BY ANSTART * 12 + LUNASTART
                          range between unbounded preceding and unbounded following) CODNIRSTOC
        FROM MIFIX1
        WHERE
          CODMIFIX = aCodMifixImb) M1
      INNER JOIN MIFIX                 MF ON MF.CODMIFIX   = M1.CODMIFIX
      INNER JOIN NIRSTOC               NS ON NS.CODNIRSTOC = M1.CODNIRSTOC
      INNER JOIN NARTOBJ               O  ON O.CODOBIECT   = NS.CODOBIECT;
  END IF;

  return vINFOMFIMB;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mifix_getnrinventarns</obj_name>
  <obj_hashval>9a2d91a5b58c17b8bdb132ee66093714</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mifix_getnrinventarns(INOUT wme_result numeric, INOUT acodnirstoc numeric, INOUT acodnirser numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NrInv numeric;
begin
  --Florin 05.01.2022 - sinc. Oracle (29.12.2021)
  BEGIN
    SELECT mf.nrinventar
    INTO NrInv
    FROM mifix mf INNER JOIN mifix1 mf1 ON  mf1.codmifix = mf.codmifix
    WHERE  mf1.codnirstoc = acodnirstoc
      and  COALESCE( mf1.codnirser, 0) = acodnirser
           and mf1.codmifix1 = (select max(mf2.codmifix1) from mifix1 mf2 where mf2.codmifix = mf.codmifix and mf2.codnirstoc = acodnirstoc and coalesce(mf2.codnirser,0) = acodnirser);
  EXCEPTION WHEN others THEN
    NrInv := 0;
  END;

  WME_Result :=  NrInv;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mifix_getnrinventarns_ext</obj_name>
  <obj_hashval>8b534288252dc4bc08d60e4eede3d601</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mifix_getnrinventarns_ext(acodnirstoc numeric, acodnirser numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
NrInv varchar(2000);
BEGIN
  --Florin 16.09.2024 - fixat 63357
 begin
    select SUBSTR(string_agg(mf.nrinventar::varchar, ' '), 1, 2000) into NrInv
    from mifix mf inner join mifix1 mf1 on mf1.codmifix = mf.codmifix
    where mf1.codnirstoc = acodnirstoc
      and nvl(mf1.codnirser,0) = acodnirser
      and mf1.codmifix1 = (select max(mf2.codmifix1) from mifix1 mf2 where mf2.codmifix = mf.codmifix and mf2.codnirstoc = acodnirstoc and nvl(mf2.codnirser,0) = acodnirser)
    group by  mf1.codnirstoc, nvl(mf1.codnirser,0);
  exception when others then
    NrInv := '';
  end;
  return NrInv;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mifix_locknumarinv</obj_name>
  <obj_hashval>ea86e27f47b921a09ab4c7c5df79eae2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mifix_locknumarinv(atip character varying, anumarinv numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 11.10.2024 - sinc. oracle
  INSERT INTO NRINVLOCK(CODINVLOCK, TIP, USEDNO, USERID, SUBUNITATEA)
  VALUES(NEXTVAL('SEQ_NRINVLOCK_CODINVLOCK'), aTIP, aNUMARINV, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), GETSUBUNITATE_DOC());
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mifix_newfisamffromtransf</obj_name>
  <obj_hashval>d284879415c580f6b327908b4d9a3f3a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mifix_newfisamffromtransf(acodnirstoc numeric, acodmifix numeric, acodoperatie numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR v_rec IN (SELECT nir.datanir, NIR.GEST, NS.PRET, T.NRDOC, T.PREFIXDOC, NS.REST CANT, T1.CODTRANSF1, T.TIPDOC
                FROM nirstoc ns
                    INNER JOIN nir        ON  nir.codnir    = ns.codnir
                    INNER JOIN transf  t  ON  NIR.CODTRANSF = T.CODTRANSF
                    INNER JOIN TRANSF1 T1 ON  NS.CODTRANSF1 = T1.CODTRANSF1
                WHERE ns.codnirstoc = acodnirstoc
                )
  LOOP
    INSERT INTO FISAMF(CODFISAMF, CODMIFIX, CODOPERATIE, DATAOPERATIE, GESTSURSA, GESTDEST, PRETI, PRETE, PREFIXDOC, NRDOC, CANT, OBS, CODDOC1, TIPDOC)
    VALUES(NEXTVAL('SEQ_FISAMF_CODFISAMF'), ACODMIFIX, aCodOperatie, V_REC.DATANIR, V_REC.GEST, V_REC.GEST, V_REC.PRET, V_REC.PRET, V_REC.PREFIXDOC, V_REC.NRDOC, V_REC.CANT, '', V_REC.CODTRANSF1, V_REC.TIPDOC);
    EXIT ;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mifix_newmifix</obj_name>
  <obj_hashval>62d6dedceb3f6f4e57deb1aee394227b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mifix_newmifix(INOUT wme_result numeric, INOUT acodnirstoc numeric, INOUT acodclasif numeric, INOUT acodcentru numeric, INOUT anrinventar numeric, INOUT aan numeric, INOUT aluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  aDurataN  numeric;
  aDurataF  numeric;
  aDurataG  numeric;
  aCodMifix numeric;
  aTipAmo   numeric := 1;
  aAnMax    numeric;
  aLunaMax  numeric;
begin
  BEGIN
    SELECT DURATA * 12, DURATAF * 12, DURATAG * 12
    INTO aDURATAN, aDurataF, aDurataG
    FROM MFCLASIF
    WHERE CODCLASIF = aCODCLASIF;
  EXCEPTION WHEN others THEN
    aDurataN := 0;
  END;

  BEGIN
    aTipAmo := COALESCE((fnc_GetValConstantaLucru('TipAmoOI')::numeric), 1);
  EXCEPTION WHEN OTHERS THEN
    aTIPAMO := 1;
  END;

  SELECT AnMaxim, LunaMaxima INTO aAnMax, aLunaMax FROM firmaluni;

  INSERT INTO MASTERMIFIX(CODNIRSTOC, CODCLASIF, DURATAN, DURATANF, DURATANG)
  VALUES(aCODNIRSTOC, aCODCLASIF, aDURATAN, aDurataF, aDurataG);

  SELECT NEXTVAL('SEQ_MIFIX_CODMIFIX') INTO aCODMIFIX;

  INSERT INTO MIFIX(CODMIFIX, TIP, NRINVENTAR, ANINTRARE, LUNAINTRARE, RESTIMBMF, ANINTRAREG, LUNAINTRAREG)
  VALUES(aCODMIFIX, 'MF', aNrInventar, TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999'), TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999'), 0, aAn, aLuna);

  INSERT INTO MIFIX1(CODMIFIX1, CODMIFIX, CODNIRSTOC, PRET, CANT, CODCLASIF, TIPAMO, STARE, DURATAN, GRADU, DURATAF, AMO, DFBLOCAT, ANSTART, LUNASTART, DFBLOCAT_F, DFBLOCAT_G, CODCENTRU)
  VALUES(NEXTVAL('SEQ_MIFIX1_CODMIFIX1'), aCODMIFIX, aCODNIRSTOC, 0, 1, aCODCLASIF, aTIPAMO, 5, aDURATAN, 100, 0, 0, 1, aAn, aLuna, 1, 1, aCodCentru);

  FOR v_rec IN (SELECT nir.datanir, NIR.GEST, NS.PRET, I.NRDOC, I.PREFIXDOC, NS.REST CANT, I1.CODIES1, I.TIPDOC
                FROM nirstoc ns
                    INNER JOIN nir          ON  nir.codnir    = ns.codnir
                    INNER JOIN IESIRI   I   ON  NIR.CODIES    = I.CODIES
                    INNER JOIN INTRARI1 IN1 ON  NS.CODINTR1   = IN1.CODINTR1
                    INNER JOIN LIVR1    L1  ON  L1.CODNIRSTOC = NS.CODNIRSTOC
                    INNER JOIN IESIRI1  I1  ON  I1.CODIES1    = L1.CODIES1 AND  I.CODIES = I1.CODIES
                WHERE ns.codnirstoc = acodnirstoc
                )
  LOOP
    INSERT INTO FISAMF(CODFISAMF, CODMIFIX, CODOPERATIE, DATAOPERATIE, GESTSURSA, GESTDEST, PRETI, PRETE, PREFIXDOC, NRDOC, CANT, OBS, CODDOC1, TIPDOC)
    VALUES(NEXTVAL('SEQ_FISAMF_CODFISAMF'), ACODMIFIX, 1, V_REC.DATANIR, 0, V_REC.GEST, V_REC.PRET, 0, V_REC.PREFIXDOC, V_REC.NRDOC, V_REC.CANT, '', V_REC.CODIES1, V_REC.TIPDOC);
    EXIT ;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mifix_propaganext</obj_name>
  <obj_hashval>7d1ffc91faf1ae8cb0c735d1b425464d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mifix_propaganext(acodmifix numeric, tip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vcodclasif  numeric;
  vstare      numeric;
  vduratan    numeric;
  vdurataf    numeric;
  vduratanf   numeric;
  vduratang   numeric;
  vCodCentru  numeric;
  vCodNirStoc numeric;
begin
  SELECT codclasif, stare, durataf, duratan, duratanf, duratang, codcentru, codnirstoc
  INTO vcodclasif, vstare, vdurataf, vduratan, vduratanf, vduratang, vCodCentru, vCodNirStoc
  FROM mifix1
  WHERE codmifix = aCodMifix and  anstart * 12 + lunastart = (SELECT pkg_globals_getanlucru.WME_RESULT FROM pkg_globals_getanlucru(NULL,NULL)) * 12 + (SELECT pkg_globals_getlunalucru.WME_RESULT FROM pkg_globals_getlunalucru(NULL,NULL));

  IF  Tip = 0 THEN
    UPDATE mifix1
    SET
    codclasif = vcodclasif,
    stare     = vstare,
    duratanf  = vduratanf,
    duratang  = vduratang,
    duratan   = vduratan
    WHERE codmifix = aCodMifix and  anstart * 12 + lunastart &gt; (SELECT pkg_globals_getanlucru.WME_RESULT FROM pkg_globals_getanlucru(NULL,NULL)) * 12 + (SELECT pkg_globals_getlunalucru.WME_RESULT FROM pkg_globals_getlunalucru(NULL,NULL));

    UPDATE mifix1
    SET
    codcentru = vCodCentru
    WHERE
     codmifix = aCodMifix and  codnirstoc = vCodNirStoc and  anstart * 12 + lunastart &gt; (SELECT pkg_globals_getanlucru.WME_RESULT FROM pkg_globals_getanlucru(NULL,NULL)) * 12 + (SELECT pkg_globals_getlunalucru.WME_RESULT FROM pkg_globals_getlunalucru(NULL,NULL));
  ELSE
    IF  Tip = 3 THEN
      UPDATE mifix1
      SET
      codcentru = vCodCentru
      WHERE
       codmifix = aCodMifix and  codnirstoc = vCodNirStoc and  anstart * 12 + lunastart &gt; (SELECT pkg_globals_getanlucru.WME_RESULT FROM pkg_globals_getanlucru(NULL,NULL)) * 12 + (SELECT pkg_globals_getlunalucru.WME_RESULT FROM pkg_globals_getlunalucru(NULL,NULL));
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mifix_sp_gotorecord_for_reeval</obj_name>
  <obj_hashval>16529df2505812411bc17db14d7a57bc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mifix_sp_gotorecord_for_reeval(acodnirstoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 20.01.2023 - fixat 56869
  --Adina 14.01.2021 - sinc.Oracle
  --Florin 21.12.2020 - fixat #41766
  DELETE FROM TMP_MIFIX;
  INSERT INTO TMP_MIFIX(CODMIFIX, TIP, NRINVENTAR, ANINTRARE, LUNAINTRARE, CODMIFIX1, CODNIRSTOC, PRET, CANT, CODCLASIF,
                        TIPAMO, STARE, DURATAN, GRADU, DURATAF, AMO, NEUTIL, DFBLOCAT, CODPERS, CODNIRSER, ANSTART, LUNASTART,
                        CODIOART, CODGEST, SERIE, CODSERIE, CODNIRSTOCNOU, SUBUNITATEA, DENUMIRE, AMOLUNA, AMOINI, REZERVA,
                        CODCENTRU, AMOREZERVA, AMORBLOCAT, AMOFBLOCAT, AMOGBLOCAT,
                        PRETINIBLOCAT,
                        pretinitial_fblocat
                       )
  SELECT *
  FROM (
  SELECT MF. CODMIFIX, MF.TIP, NRINVENTAR, ANINTRARE, LUNAINTRARE, CODMIFIX1, MF1.CODNIRSTOC, MF1.PRET, CANT, CODCLASIF, TIPAMO,
         MF1.STARE, DURATAN, GRADU, DURATAF, AMO, NEUTIL, DFBLOCAT, CODPERS, MF1.CODNIRSER, ANSTART, LUNASTART, NS.CODIOART,
         N.GEST, SER.SERIE, SER.CODSERIE, MF1.CODNIRSTOC AS CODNIRSTOCNOU, G.CODSUBUNIT, O.DENUMIRE,
         (SELECT PKG_INCHIDERI_AMORTIZARELUNARA.WME_RESULT FROM PKG_INCHIDERI_AMORTIZARELUNARA(NULL, MF.CODMIFIX, TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999'), TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999'))) AS AMOLUNARA,
         MF1.AMO AS AMOINI, MF1.REZERVA, MF1.CODCENTRU, MF1.AMOREZERVA, MF1.AMORBLOCAT, MF1.AMOFBLOCAT, MF1.AMOGBLOCAT,
         MF1.PRETINIBLOCAT,
         MF1.pretinitial_fblocat
  FROM MIFIX MF, MIFIX1 MF1
      LEFT JOIN NIRSTOC NS   ON  NS.CODNIRSTOC  = MF1.CODNIRSTOC
      LEFT JOIN NIR     N    ON  N.CODNIR       = NS.CODNIR
      LEFT JOIN NGEST   G    ON  G.CODGEST      = N.GEST
      LEFT JOIN NIRSER  NSER ON  NSER.CODNIRSER = MF1.CODNIRSER
      LEFT JOIN NSERII  SER  ON  SER.CODSERIE   = NSER.CODSERIE, NARTOBJ O
  WHERE
     MF.CODMIFIX = MF1.CODMIFIX AND  MF1.CODNIRSTOC = aCODNIRSTOC AND  MF1.ANSTART * 12 + MF1.LUNASTART = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') * 12 + TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999') AND  O.CODOBIECT = NS.CODOBIECT
  ORDER BY NRINVENTAR
  ) A_PG;

  UPDATE TMP_MIFIX
  SET
  CODTMPMIFIX = (SELECT ROW_NUMBER() OVER() FROM TMP_MIFIX LIMIT 1),
  AMO         = AMO + AMOLUNA,
  INCLUDRATA  = 1;

  DELETE FROM TMP_JURNAL;
  DELETE FROM TMP_JURNAL1;
  INSERT INTO TMP_JURNAL
  (SELECT * FROM JURNAL
   WHERE  TIPDOC = 36
     AND CODDOC IN (SELECT CODMIFIX FROM TMP_MIFIX)
     AND  AN   = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU'  , true)),'999999999999999999')
     AND  LUNA = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999')
  );

  INSERT INTO TMP_JURNAL1
  (SELECT * FROM JURNAL1
   WHERE TIPDOC = 36
     AND CODDOC IN (SELECT CODMIFIX FROM TMP_MIFIX)
     AND  AN   = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU'  , true)),'999999999999999999')
     AND  LUNA = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999')
  );

  DELETE FROM TMP_RULAJ;
  DELETE FROM TMP_MIFIX_INITIAL;
  INSERT INTO TMP_MIFIX_INITIAL(CODMIFIX) SELECT CODMIFIX FROM TMP_MIFIX;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mifix_vindere</obj_name>
  <obj_hashval>db18770f4c4d1847f4b0fd44ecd3f8c9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mifix_vindere(acodmifix1 numeric, acodies numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  UPDATE mifix1 SET stare = 4 WHERE codmifix1 = acodmifix1;

  FOR v_rec IN (SELECT l.datalivr, NIR.GEST, NS.PRET, i.NRDOC, i.PREFIXDOC, l1.CANT, i1.CODIES1, I.TIPDOC, MFIX1.CODMIFIX, mfix1.anstart, mfix1.lunastart
                FROM nirstoc ns
                    INNER JOIN livr1   l1    ON  l1.codnirstoc    = ns.codnirstoc
                    INNER JOIN iesiri1 i1    ON  i1.codies1       = l1.codies1
                    INNER JOIN iesiri  i     ON  i.codies         = i1.codies
                    INNER JOIN livr    l     ON  l.codies         = i.codies and  l1.codlivr = l.codlivr
                    INNER JOIN mifix1  mfix1 ON  mfix1.CODNIRSTOC = ns.codnirstoc
                    INNER JOIN nir           ON  nir.codnir       = ns.codnir
                WHERE mfix1.codmifix1 = acodMifix1 and  i.codies = aCodIes
                )
  LOOP
    INSERT INTO FISAMF(CODFISAMF, CODMIFIX, CODOPERATIE, DATAOPERATIE, GESTSURSA, GESTDEST, PRETI, PRETE, PREFIXDOC, NRDOC, CANT, OBS, CODDOC1, TIPDOC)
    VALUES(NEXTVAL('SEQ_FISAMF_CODFISAMF'), V_rec.CODMIFIX, 5, V_REC.DATALIVR, V_REC.GEST, V_REC.GEST, V_REC.PRET, V_REC.PRET, V_REC.PREFIXDOC, V_REC.NRDOC, V_REC.CANT, '', V_REC.CODIES1, V_REC.TIPDOC);

    UPDATE jurnal1 SET dirty = 1 WHERE coddoc = v_rec.codmifix and  tipdoc = 36 and  an * 12 + luna &gt;= v_rec.anstart * 12 + v_rec.lunastart;
    EXIT ;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_check_coerenta_modipret_mf</obj_name>
  <obj_hashval>7d0cea1bc9e707974526b5940c5d0830</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_check_coerenta_modipret_mf(acoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  DELETE FROM TMP_JURNAL_MAN;

  FOR V_REC IN (SELECT MF1.codmifix1, MF1.codmifix, MF1.pret, ns.pret AS PRETNIRSTOC, MF1.ANSTART, MF1.LUNASTART, NS.CODTRANSF1
                FROM NIRSTOC NS, NIR N, MIFIX1 MF1
                WHERE  N.CODTRANSF = aCODDOC
                  AND  N.TIPNIR = 13
                  AND  NS.CODNIR = N.CODNIR
                  AND  MF1.CODNIRSTOC = NS.CODNIRSTOC
                  AND  MF1.ANSTART * 12 + MF1.LUNASTART &gt;= TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') * 12 + TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999')
                  AND  MF1.PRET &lt;&gt; NS.PRET
  )
  LOOP
    UPDATE MIFIX1  SET PRET  = V_REC.PRETNIRSTOC WHERE CODMIFIX1 = V_REC.CODMIFIX1;
    UPDATE FISAMF  SET PRETE = V_REC.PRETNIRSTOC WHERE CODMIFIX  = V_REC.CODMIFIX AND  TIPDOC = 13 AND  CODDOC1 = V_REC.CODTRANSF1;
    UPDATE JURNAL1 SET DIRTY = 1                 WHERE TIPDOC    = 36 AND  CODDOC = V_REC.CODMIFIX AND  AN = V_REC.ANSTART AND  LUNA = V_REC.LUNASTART;

    INSERT INTO TMP_JURNAL_MAN(CODDOC, TIPDOC) VALUES(V_REC.CODMIFIX, 36);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_check_rezervari</obj_name>
  <obj_hashval>82007559cd66597d7b1e67e23ecd24c3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_check_rezervari(codnirstoc_sursa numeric, codnirser_sursa numeric, codnirstoc_dest numeric, codnirser_dest numeric, acant numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  NR           numeric := 0;
  CANTLIVR     double precision := 0;
  CANTREZ      double precision := 0;
  NEEDSTERGERE numeric := 0;
begin
  CANTLIVR := aCANT;

  FOR V_REC IN (SELECT * FROM REZERVATS WHERE CODNIRSTOC = CODNIRSTOC_SURSA AND  CODNIRSER = CODNIRSER_SURSA) LOOP
    IF (V_REC.REST &gt; 0)  AND (CANTLIVR &gt; 0) THEN
      IF  CANTLIVR &lt;= V_REC.REST THEN
        CANTREZ := CANTLIVR;
      ELSE
        CANTREZ := V_REC.REST;
      END IF;

      CANTLIVR := CANTLIVR - CANTREZ;
      IF  CANTREZ = V_REC.REST THEN
        NEEDSTERGERE := 1;
      ELSE
        NEEDSTERGERE := 0;
      END IF;

      IF  NEEDSTERGERE = 0 THEN
        UPDATE REZERVATS SET REST = COALESCE( REST, 0) - CANTREZ WHERE CODREZERVATS = V_REC.CODREZERVATS;
      ELSE
        DELETE FROM REZERVATS WHERE CODREZERVATS = V_REC.CODREZERVATS;
      END IF;

      SELECT COUNT( *) INTO NR
      FROM REZERVATS
      WHERE CODNIRSTOC = CODNIRSTOC_DEST AND  CODNIRSER = CODNIRSER_DEST AND  CODCOMANDA1 = V_REC.CODCOMANDA1;

      IF  NR = 0 THEN
        INSERT INTO REZERVATS(CODREZERVATS, CODCOMANDA1, CODNIRSTOC, CODNIRSER, REST, UMSEC, CODINVENTAR1)
        VALUES(NEXTVAL('SEQ_REZERVATS_CODREZERVATS'), V_REC.CODCOMANDA1, CODNIRSTOC_DEST, CODNIRSER_DEST, CANTREZ, V_REC.UMSEC, V_REC.CODINVENTAR1);
      ELSE
        UPDATE REZERVATS SET REST = COALESCE( REST, 0) + CANTREZ WHERE CODNIRSTOC = CODNIRSTOC_DEST AND  CODNIRSER = CODNIRSER_DEST AND  CODCOMANDA1 = V_REC.CODCOMANDA1;
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_check_rezervari_modipret_out</obj_name>
  <obj_hashval>920ad28a209eb02df2b568cc1ccee2c2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_check_rezervari_modipret_out()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN
  (
  SELECT L1.CODNIRSTOC AS CODNIRSTOC_SURSA, L1.CODNIRSER AS CODNIRSER_SURSA, L1.CANT, NS.CODNIRSTOC AS CODNIRSTOC_DEST, COALESCE( NSE.CODNIRSER, 0) AS CODNIRSER_DEST
  FROM TMP_LIVR1 L1, TMP_NIRSTOC NS
       LEFT JOIN TMP_NIRSER NSE ON  NSE.CODNIRSTOC = NS.CODNIRSTOC
  WHERE NS.CODLIVR1 = L1.CODLIVR1
  )
  LOOP
    PERFORM PKG_MISCARI_INTERNE_CHECK_REZERVARI( V_REC.CODNIRSTOC_SURSA, V_REC.CODNIRSER_SURSA, V_REC.CODNIRSTOC_DEST, V_REC.CODNIRSER_DEST, V_REC.CANT);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_check_rezervari_transf</obj_name>
  <obj_hashval>e50b944a92b2680db4f94672853f0202</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_check_rezervari_transf(codnirstoc_sursa numeric, codnirser_sursa numeric, codnirstoc_dest numeric, codnirser_dest numeric, acant numeric, acodcomanda1 numeric, acodcomand1orig numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  NR           numeric := 0;
  CANTLIVR     double precision := 0;
  CANTREZ      double precision := 0;
  NEEDSTERGERE numeric := 0;
begin
  CANTLIVR := aCANT;

  FOR V_REC IN (SELECT *
                FROM REZERVATS
                WHERE  CODNIRSTOC = CODNIRSTOC_SURSA
                  AND  CODNIRSER = CODNIRSER_SURSA
                  AND (CODCOMANDA1 = aCODCOMANDA1 OR CODCOMANDA1 = aCODCOMAND1ORIG)
                  AND COALESCE( codobiect, 0) = 0
               )
  LOOP
    IF (V_REC.REST &gt; 0)  AND (CANTLIVR &gt; 0) THEN
      IF  CANTLIVR &lt;= V_REC.REST THEN
        CANTREZ := CANTLIVR;
      ELSE
        CANTREZ := V_REC.REST;
      END IF;

      CANTLIVR := CANTLIVR - CANTREZ;
      IF  CANTREZ = V_REC.REST THEN
        NEEDSTERGERE := 1;
      ELSE
        NEEDSTERGERE := 0;
      END IF;

      IF  NEEDSTERGERE = 0 THEN
        UPDATE REZERVATS SET REST = COALESCE( REST, 0) - CANTREZ WHERE CODREZERVATS = V_REC.CODREZERVATS;
      ELSE
        DELETE FROM REZERVATS WHERE CODREZERVATS = V_REC.CODREZERVATS;
      END IF;

      SELECT COUNT( *) INTO NR
      FROM REZERVATS
      WHERE CODNIRSTOC = CODNIRSTOC_DEST AND  CODNIRSER = CODNIRSER_DEST AND  CODCOMANDA1 = V_REC.CODCOMANDA1;

      IF  NR = 0 THEN
        INSERT INTO REZERVATS(CODREZERVATS, CODCOMANDA1, CODNIRSTOC, CODNIRSER, REST, UMSEC)
        VALUES(NEXTVAL('SEQ_REZERVATS_CODREZERVATS'), V_REC.CODCOMANDA1, CODNIRSTOC_DEST, CODNIRSER_DEST, CANTREZ, V_REC.UMSEC);
      ELSE
        UPDATE REZERVATS SET REST = COALESCE( REST, 0) + CANTREZ WHERE CODNIRSTOC = CODNIRSTOC_DEST AND  CODNIRSER = CODNIRSER_DEST AND  CODCOMANDA1 = V_REC.CODCOMANDA1;
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_check_rezervari_transf_in</obj_name>
  <obj_hashval>f5617f54e17ddbec00eb3a3be8f6bfed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_check_rezervari_transf_in()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Florin 26.05.2021 - fixat 50258
  FOR V_REC IN
  (
  SELECT L1.CODNIRSTOC AS CODNIRSTOC_DEST, L1.CODNIRSER AS CODNIRSER_DEST, L1.CANT, NS.CODNIRSTOC AS CODNIRSTOC_SURSA, COALESCE( NSE.CODNIRSER, 0) AS CODNIRSER_SURSA, T1.CODCOMANDA1, COALESCE( CL.CODLINIECOMANDA, 0) AS CODCOMAND1ORIG
  FROM TMP_LIVR1_INITIAL L1,
       TMP_NIRSTOCINI NS
       LEFT JOIN TMP_NIRSERINI NSE ON  NSE.CODNIRSTOC = NS.CODNIRSTOC, TRANSF1_MAN T1
       LEFT JOIN CMDLINK       CL  ON  CL.CODCOMANDA1 = T1.CODCOMANDA1
  WHERE NS.CODLIVR1 = L1.CODLIVR1 AND  T1.CODTRANSF1 = L1.CODIES1 AND  COALESCE( T1.CODCOMANDA1, 0) &lt;&gt; 0
  )
  LOOP
    PERFORM pkg_miscari_interne_CHECK_REZERVARI_TRANSF( V_REC.CODNIRSTOC_SURSA, V_REC.CODNIRSER_SURSA, V_REC.CODNIRSTOC_DEST, V_REC.CODNIRSER_DEST, V_REC.CANT, V_REC.CODCOMANDA1, V_REC.CODCOMAND1ORIG);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_check_rezervari_transf_out</obj_name>
  <obj_hashval>5aed190455ca2381a92c27f7ec5be97f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_check_rezervari_transf_out()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Florin 26.05.2021 - fixat 50258
  FOR V_REC IN
  (
  SELECT L1.CODNIRSTOC AS CODNIRSTOC_SURSA, L1.CODNIRSER AS CODNIRSER_SURSA, L1.CANT, NS.CODNIRSTOC AS CODNIRSTOC_DEST, COALESCE( NSE.CODNIRSER, 0) AS CODNIRSER_DEST, T1.CODCOMANDA1, COALESCE( CL.CODLINIECOMANDA, 0) AS CODCOMAND1ORIG
  FROM TMP_LIVR1 L1,
       TMP_NIRSTOC NS
       LEFT JOIN TMP_NIRSER NSE ON  NSE.CODNIRSTOC = NS.CODNIRSTOC, TRANSF1 T1
       LEFT JOIN CMDLINK    CL  ON  CL.CODCOMANDA1 = T1.CODCOMANDA1
  WHERE NS.CODLIVR1 = L1.CODLIVR1 AND  T1.CODTRANSF1 = L1.CODIES1 AND  COALESCE( T1.CODCOMANDA1, 0) &lt;&gt; 0
  )
  LOOP
    PERFORM pkg_miscari_interne_CHECK_REZERVARI_TRANSF( V_REC.CODNIRSTOC_SURSA, V_REC.CODNIRSER_SURSA, V_REC.CODNIRSTOC_DEST, V_REC.CODNIRSER_DEST, V_REC.CANT, V_REC.CODCOMANDA1, V_REC.CODCOMAND1ORIG);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_check_transf_mifix_faraserie</obj_name>
  <obj_hashval>b85d03f7f2f29c460957d0e262ae1301</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_check_transf_mifix_faraserie(acodtransf numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  V_REC RECORD;
  nr NUMERIC;
begin
  --Florin 04.12.2025 - sinc. Oracle
  --Florin 25.11.2025 - sinc. Oracle
  --Florin 26.10.2023 - sinc. Oracle
  --Florin 22.06.2022 - sinc. Oracle (21.06.2022)
  --Florin 22.01.2022 - sinc. Oracle (29.12.2021)
   if current_setting('pkg_miscari_interne.vCodMifix', true)::NUMERIC then
    FOR V_REC IN (
      SELECT M1.CODMIFIX1, M1.CODMIFIX, MF_TRANSF.*, M.TIP, M1.ANSTART, M1.LUNASTART
      FROM MIFIX1 M1, MIFIX M,
      (
      SELECT
        NSP.CODNIRSTOC CODNIRSTOPARINTE,
        NSP.CANTNIR AS CANTNIRPARINTE,
        NSD.CODNIRSTOC CODNIRSTOCDEST,
        L1.CANT,
        L.DATALIVR,
        NP.GEST AS GESTSURSA,
        ND.GEST AS GESTDEST,
        NSP.PRET AS PRETE,
        NSD.PRET AS PRETI,
        NSD.CODTRANSF1,
        NSP.CODIOART AS CODIOARTP,
        NSD.CODIOART AS CODIOARTD,
        T.NRDOC
      FROM
        LIVR1 L1,
        LIVR L,
        TRANSF T,
        NIRSTOC NSD,
        NIR ND,
        NIRSTOC NSP,
        NIR NP,
        TMP_IOART_LUNA IOA
      WHERE
        L.CODTRANSF = aCODTRANSF
        AND L1.CODLIVR = L.CODLIVR
        AND NSD.CODLIVR1 = L1.CODLIVR1
        AND NSP.CODNIRSTOC = L1.CODNIRSTOC
        AND IOA.CODIOART = NSD.CODIOART
        AND COALESCE(IOA.ESTEMIFIX, 0) + COALESCE(IOA.ESTEOBINV, 0) = 1
        AND NVL(NSP.TIPSERIE, 0) = 0
        AND L1.CANT = 1
        AND NSP.CANTNIR = 1
        AND ND.CODNIR = NSD.CODNIR
        AND NP.CODNIR = NSP.CODNIR
        AND L.CODTRANSF = T.CODTRANSF
      ) MF_TRANSF
      WHERE
        M1.ANSTART * 12 + M1.LUNASTART &gt;= getANLUCRU() * 12 + getLUNALUCRU()
       AND M1.CODNIRSTOC = MF_TRANSF.CODNIRSTOPARINTE
       AND M1.CODMIFIX = vCodMifix
       AND M1.CODMIFIX = M.CODMIFIX
    ) LOOP
      IF V_REC.CODIOARTP &lt;&gt; V_REC.CODIOARTD   AND V_REC.TIP = 'MF' THEN
        perform pkg_miscari_interne_MAKE_MIFIX_NOU(V_REC.CODMIFIX, V_REC.CODMIFIX1, V_REC.ANSTART, V_REC.LUNASTART);
      END IF;
      UPDATE MIFIX1
      SET CODNIRSTOC = V_REC.CODNIRSTOCDEST
      WHERE CODMIFIX1 = V_REC.CODMIFIX1;

      SELECT COUNT(*) INTO NR
      FROM
        FISAMF
      WHERE
        CODMIFIX = V_REC.CODMIFIX
        AND CODOPERATIE = 2
        AND CODDOC1 = V_REC.CODTRANSF1
        AND TIPDOC = 12;

      IF NR = 0 THEN
        INSERT INTO FISAMF(CODFISAMF, CODMIFIX, CODOPERATIE, DATAOPERATIE, GESTSURSA, GESTDEST, PRETI, PRETE, PREFIXDOC, NRDOC, CANT, CODDOC1, TIPDOC)
        VALUES(NEXTVAL('SEQ_FISAMF_CODFISAMF'), V_REC.CODMIFIX, 2, V_REC.DATALIVR, V_REC.GESTSURSA, V_REC.GESTDEST, V_REC.PRETI, V_REC.PRETE, 'NT', V_REC.NRDOC, 1, V_REC.CODTRANSF1, 12);
      END IF;

      UPDATE JURNAL1
      SET DIRTY = 1
      WHERE
        CODDOC = V_REC.CODMIFIX
        AND TIPDOC = 36
        AND AN * 12 + LUNA &gt;= getANLUCRU() * 12 + getLUNALUCRU();
    END LOOP;
  ELSE
    PERFORM pkg_miscari_interne_Solve_TRANSF_MIFIX(aCODTRANSF, 1); --1 = cu legatura in TRANSF1
    PERFORM pkg_miscari_interne_Solve_TRANSF_MIFIX(aCODTRANSF, 0); --0 = fara legatura in TRANSF1
  end if;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_ct_monitor</obj_name>
  <obj_hashval>2b0b5e049097334ce101d33f097bf57e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_MISCARI_INTERNE.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_13';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_docommit</obj_name>
  <obj_hashval>3784e87892e59428387da7e0bbadd966</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_docommit(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_MISCARI_INTERNE.DoCommit'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := true;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_empty_transf_temptables</obj_name>
  <obj_hashval>cd2c3fab5bdec50b69bdb62bd905ac7b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_empty_transf_temptables()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM TMP_TRANSF1;
  DELETE FROM TMP_TRANSF1_INITIAL;
  DELETE FROM TMP_NIR;
  DELETE FROM TMP_NIRSTOC;
  DELETE FROM TMP_LIVR;
  DELETE FROM TMP_LIVRTOT;
  DELETE FROM TMP_LIVR1;
  DELETE FROM TMP_LIVR1_INITIAL;
  DELETE FROM TMP_NIRSER;
  DELETE FROM TMP_LIVRVAL;
  DELETE FROM TMP_JURNAL1;
  DELETE FROM TMP_JURNAL;
  DELETE FROM TMP_RULAJ;
  DELETE FROM TMP_TRANSFLINK;
  DELETE FROM TMP_TRANSFLINK_INITIAL;
  DELETE FROM TMP_IMBMIFIXLINK;
  DELETE FROM TMP_IMBMIFIXLINK_INITIAL;
  DELETE FROM TMP_NIRSTOC1;

  IF  (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(NULL, 'TMP_TRANSF1EXT')) = 1 THEN
    EXECUTE 'Delete FROM TMP_TRANSF1EXT';
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_getcarnetdoc_i</obj_name>
  <obj_hashval>e0f8c186efb37918e7c0ef16d0d13403</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_getcarnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_MISCARI_INTERNE.CARNETDOC_I', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_getct_monitor</obj_name>
  <obj_hashval>67afb36accce877b127fd4e5160c817f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_MISCARI_INTERNE.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_13';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_getcursoriginal</obj_name>
  <obj_hashval>6156df7e60ae54722e1bf897e4982b4d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_getcursoriginal(INOUT wme_result numeric, INOUT anirstocparinte numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  IRES double precision;
begin
  BEGIN
    SELECT (PRET - COALESCE( ADAOS, 0))  / PUVAL INTO IRES FROM NIRSTOC WHERE CODNIRSTOC = ANIRSTOCPARINTE;
  EXCEPTION WHEN OTHERS THEN
    IRES := 1;
  END;

  WME_Result :=  IRES;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_getvskipmifixaut</obj_name>
  <obj_hashval>c6e874acbbfc10bbcd635ba9f661bdc2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_getvskipmifixaut(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_MISCARI_INTERNE.vSkipMifixAut'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := False;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_nrdoc_i</obj_name>
  <obj_hashval>0850e451c7923933098f02a8d9c90e65</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_nrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_MISCARI_INTERNE.NRDOC_I', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_setct_monitor</obj_name>
  <obj_hashval>c9414d6a1c3d2cfe7700b8a084e9da34</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_MISCARI_INTERNE.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_setdocommit</obj_name>
  <obj_hashval>f62e0d5acc8bf16a2e0d32a20c88c0c4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_setdocommit(adocommit boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 08.07.2022
  perform set_config('PKG_MISCARI_INTERNE.DoCommit',aDoCommit::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_setnrdoc_i</obj_name>
  <obj_hashval>7a50f80b0efd10a92e03263950cbb7dc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_setnrdoc_i(anrdoc numeric, acarnet numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_MISCARI_INTERNE.CARNETDOC_I',to_char(ACARNET,'999999999999999999'),false);
  perform set_config('PKG_MISCARI_INTERNE.NRDOC_I'    ,to_char(ANRDOC ,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_setskipmifix</obj_name>
  <obj_hashval>491d1d096dc0d0790fb4e8e04764834d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_setskipmifix(askip boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_MISCARI_INTERNE.vSkipMifixAut',aSkip,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_setvskipmifixaut</obj_name>
  <obj_hashval>8e244fc64a515d9af1e3a501733ddc4a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_setvskipmifixaut(avskipmifixaut boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_MISCARI_INTERNE.vSkipMifixAut',avSkipMifixAut::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_solve_mifix</obj_name>
  <obj_hashval>da025679f62a901220eb45737c23b0ab</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_solve_mifix(acodtransf numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC            RECORD;
  REZOLVAT         double precision := 0;
  CODCLASIF_MASTER numeric := 0;
  aDURATAN         numeric;
  NR               numeric := 0;
  aCODMIFIX        numeric;
  aTIPAMO          numeric;
begin
  FOR V_REC IN (SELECT CODNIRSTOC, CODNIRSTOCPARINTE, PRET, REST, AN, LUNA
                FROM NIRSTOC NS, NIR N, TRANSF T
                WHERE N.CODTRANSF = aCODTRANSF AND  NS.CODNIR = N.CODNIR AND  T.CODTRANSF = N.CODTRANSF
               )
  LOOP
    SELECT COUNT( *) INTO NR FROM MASTERMIFIX WHERE CODNIRSTOC = V_REC.CODNIRSTOC;

    IF  NR = 0 THEN
      INSERT INTO MASTERMIFIX  (CODNIRSTOC, CODCLASIF, DURATAN, DURATANF, DURATANG, CODANALIZA)
      SELECT V_REC.CODNIRSTOC, CODCLASIF, DURATAN, DURATANF, DURATANG, CODANALIZA
      FROM MASTERMIFIX WHERE CODNIRSTOC = V_REC.CODNIRSTOCPARINTE;
    ELSE
      UPDATE MASTERMIFIX
      SET
      (CODCLASIF, DURATAN, DURATANF, DURATANG, CODANALIZA) = (SELECT CODCLASIF, DURATAN, DURATANF, DURATANG, CODANALIZA FROM MASTERMIFIX WHERE CODNIRSTOC = V_REC.CODNIRSTOCPARINTE)
      WHERE
       CODNIRSTOC = V_REC.CODNIRSTOC;
    END IF;

    UPDATE MIFIX1
    SET
    CODNIRSTOC = V_REC.CODNIRSTOC
    WHERE
     CODNIRSTOC = V_REC.CODNIRSTOCPARINTE AND  ANSTART * 12 + LUNASTART &gt;= V_REC.AN * 12 + V_REC.LUNA;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_solve_obinv</obj_name>
  <obj_hashval>cc11bcb8136d1589342ccc4edb19d378</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_solve_obinv(acodtransf numeric, acodclasif numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC            RECORD;
  REZOLVAT         double precision := 0;
  CODCLASIF_MASTER numeric := 0;
  aDURATAN         numeric;
  NR               numeric := 0;
  aCODMIFIX        numeric;
  aTIPAMO          numeric;
BEGIN
  --Florin 11.03.2021 - inlocuit rownum (44855)
  CODCLASIF_MASTER := aCODCLASIF;
  BEGIN
    aTipAmo := COALESCE( (fnc_GetValConstantaLucru('TipAmoOI')::numeric), 1);
  EXCEPTION WHEN OTHERS THEN
    aTIPAMO := 1;
  END;

  FOR V_REC IN (SELECT CODNIRSTOC, PRET, REST, CODNIRSTOCPARINTE
                FROM NIRSTOC NS, NIR N, TMP_IOART_LUNA IOLUNA
                WHERE N.CODTRANSF = aCODTRANSF AND  NS.CODNIR = N.CODNIR AND  IOLUNA.CODIOART = NS.CODIOART AND  IOLUNA.ESTEOBINV &gt; 0
               )
  LOOP
    SELECT COALESCE( SUM( CANT), 0) INTO REZOLVAT FROM MIFIX1 MF
    WHERE MF.CODNIRSTOC = V_REC.CODNIRSTOC AND  MF.ANSTART * 12 + MF.LUNASTART = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') * 12 + TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999');

    IF  REZOLVAT &lt; V_REC.REST THEN
      BEGIN
        SELECT COALESCE( CODCLASIF, 0) INTO CODCLASIF_MASTER FROM MASTERMIFIX WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
      EXCEPTION WHEN OTHERS THEN
        CODCLASIF_MASTER := 0;
      END;

      IF  CODCLASIF_MASTER = 0 THEN
        CODCLASIF_MASTER := aCODCLASIF;
      END IF;

      BEGIN
        SELECT DURATA INTO aDURATAN FROM MFCLASIF WHERE CODCLASIF = aCODCLASIF;
      END;

      IF  aDURATAN &gt; 0 THEN
        SELECT COUNT( *) INTO NR FROM MASTERMIFIX WHERE CODNIRSTOC = V_REC.CODNIRSTOC;

        IF  NR = 0 THEN
          INSERT INTO MASTERMIFIX(CODNIRSTOC, CODCLASIF, DURATAN)
          VALUES(V_REC.CODNIRSTOC, CODCLASIF_MASTER, aDURATAN);
        END IF;

        SELECT NEXTVAL('SEQ_MIFIX_CODMIFIX') INTO aCODMIFIX;

        INSERT INTO MIFIX(CODMIFIX, TIP, NRINVENTAR, ANINTRARE, LUNAINTRARE)
        VALUES(aCODMIFIX, 'OI', (SELECT PKG_MIFIX_GetNextNrInv.WME_RESULT FROM PKG_MIFIX_GetNextNrInv(NULL, 'OI')), TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999'), TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999'));

        INSERT INTO MIFIX1(CODMIFIX1, CODMIFIX, CODNIRSTOC, PRET, CANT, CODCLASIF, TIPAMO, STARE, DURATAN, GRADU, DURATAF, AMO, DFBLOCAT, ANSTART, LUNASTART, DFBLOCAT_F, DFBLOCAT_G)
        VALUES(  NEXTVAL('SEQ_MIFIX1_CODMIFIX1'), aCODMIFIX, V_REC.CODNIRSTOC, V_REC.PRET, V_REC.REST - REZOLVAT, CODCLASIF_MASTER, aTIPAMO, 1, aDURATAN, 100,
                (SELECT DURATAF FROM MIFIX1 WHERE CODNIRSTOC = V_REC.CODNIRSTOCPARINTE AND  ANSTART = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') AND  LUNASTART = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999') LIMIT 1),
                (V_REC.REST - REZOLVAT)  * V_REC.PRET, 0,
                TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU'  , true)),'999999999999999999'),
                TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999'),
                1, 1
              );

        UPDATE MIFIX1 SET CANT = CANT - (  V_REC.REST - REZOLVAT)
        WHERE CODNIRSTOC = V_REC.CODNIRSTOCPARINTE AND  ANSTART = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') AND  LUNASTART = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999');

        DELETE FROM MIFIX1
        WHERE CANT = 0 AND  CODNIRSTOC = V_REC.CODNIRSTOCPARINTE AND  ANSTART = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') AND  LUNASTART = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999');
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_solve_transf_mifix</obj_name>
  <obj_hashval>fc568898dc5b73a6b8ec77157c44b311</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_solve_transf_mifix(acodtransf numeric, legaturatransf1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR NUMERIC;
  v_rec record;
BEGIN
  --Florin 30.11.2023 - fixat 59878
  IF LegaturaTRANSF1 = 0 THEN -- fara legatura in transf1
    FOR V_REC IN (
      SELECT M1.CODMIFIX1, M1.CODMIFIX, MF_TRANSF.*
      FROM MIFIX1 M1,
      (
      SELECT
        NSP.CODNIRSTOC CODNIRSTOPARINTE,
        NSP.CANTNIR AS CANTNIRPARINTE,
        NSD.CODNIRSTOC CODNIRSTOCDEST,
        L1.CANT,
        L.DATALIVR,
        NP.GEST AS GESTSURSA,
        ND.GEST AS GESTDEST,
        NSP.PRET AS PRETE,
        NSD.PRET AS PRETI,
        NSD.CODTRANSF1,
        T.NRDOC
      FROM
        LIVR1 L1,
        TRANSF1 T1,
        LIVR L,
        TRANSF T,
        NIRSTOC NSD,
        NIR ND,
        NIRSTOC NSP,
        NIR NP,
        TMP_IOART_LUNA IOA
      WHERE
        L.CODTRANSF = aCODTRANSF
        AND L1.CODLIVR = L.CODLIVR
        AND T1.CODTRANSF1 = L1.CODIES1
        AND NVL(T1.CODMIFIX, 0) = 0
        AND NSD.CODLIVR1 = L1.CODLIVR1
        AND NSP.CODNIRSTOC = L1.CODNIRSTOC
        AND IOA.CODIOART = NSD.CODIOART
        AND COALESCE(IOA.ESTEMIFIX, 0) + COALESCE(IOA.ESTEOBINV, 0) = 1
        AND NVL(NSP.TIPSERIE, 0) = 0
        AND L1.CANT = 1
        AND NSP.CANTNIR &lt;= 1
        AND ND.CODNIR = NSD.CODNIR
        AND NP.CODNIR = NSP.CODNIR
        AND L.CODTRANSF = T.CODTRANSF
      ) MF_TRANSF
      WHERE
        M1.ANSTART * 12 + M1.LUNASTART &gt;= getANLUCRU() * 12 + getLUNALUCRU()
       -- M1.ANSTART = PKG_GLOBALS.ANLUCRU
       -- AND M1.LUNASTART = PKG_GLOBALS.LUNALUCRU
        AND M1.CODNIRSTOC = MF_TRANSF.CODNIRSTOPARINTE
    ) LOOP
      UPDATE MIFIX1
      SET CODNIRSTOC = V_REC.CODNIRSTOCDEST
      WHERE CODMIFIX1 = V_REC.CODMIFIX1;

      SELECT COUNT(*) INTO NR
      FROM
        FISAMF
      WHERE
        CODMIFIX = V_REC.CODMIFIX
        AND CODOPERATIE = 2
        AND CODDOC1 = V_REC.CODTRANSF1
        AND TIPDOC = 12;

      IF NR = 0 THEN
        INSERT INTO FISAMF(CODFISAMF, CODMIFIX, CODOPERATIE, DATAOPERATIE, GESTSURSA, GESTDEST, PRETI, PRETE, PREFIXDOC, NRDOC, CANT, CODDOC1, TIPDOC)
        VALUES(NEXTVAL('SEQ_FISAMF_CODFISAMF'), V_REC.CODMIFIX, 2, V_REC.DATALIVR, V_REC.GESTSURSA, V_REC.GESTDEST, V_REC.PRETI, V_REC.PRETE, 'NT', V_REC.NRDOC, 1, V_REC.CODTRANSF1, 12);
      END IF;

      UPDATE JURNAL1
      SET
        DIRTY = 1
      WHERE
        CODDOC = V_REC.CODMIFIX
        AND TIPDOC = 36
        AND AN * 12 + LUNA &gt;= getANLUCRU() * 12 + getLUNALUCRU();
    END LOOP;
  ELSE -- cu legatura in transf1
    FOR V_REC IN (
      SELECT M1.CODMIFIX1, M1.CODMIFIX, MF_TRANSF.*
      FROM MIFIX1 M1,
      (
      SELECT
        NSP.CODNIRSTOC CODNIRSTOPARINTE,
        NSP.CANTNIR AS CANTNIRPARINTE,
        NSD.CODNIRSTOC CODNIRSTOCDEST,
        L1.CANT,
        L.DATALIVR,
        NP.GEST AS GESTSURSA,
        ND.GEST AS GESTDEST,
        NSP.PRET AS PRETE,
        NSD.PRET AS PRETI,
        NSD.CODTRANSF1,
        T.NRDOC,
        T1.CODMIFIX AS CODMIFIX_TRANSF1
      FROM
        LIVR1 L1,
        TRANSF1 T1,
        LIVR L,
        TRANSF T,
        NIRSTOC NSD,
        NIR ND,
        NIRSTOC NSP,
        NIR NP,
        TMP_IOART_LUNA IOA
      WHERE
        L.CODTRANSF = aCODTRANSF
        AND L1.CODLIVR = L.CODLIVR
        AND T1.CODTRANSF1 = L1.CODIES1
        AND NSD.CODLIVR1 = L1.CODLIVR1
        AND NSP.CODNIRSTOC = L1.CODNIRSTOC
        AND IOA.CODIOART = NSD.CODIOART
        AND COALESCE(IOA.ESTEMIFIX, 0) + COALESCE(IOA.ESTEOBINV, 0) = 1
        AND NVL(NSP.TIPSERIE, 0) = 0
        AND L1.CANT = 1
--      AND NSP.CANTNIR &lt;= 1
        AND ND.CODNIR = NSD.CODNIR
        AND NP.CODNIR = NSP.CODNIR
        AND L.CODTRANSF = T.CODTRANSF
      ) MF_TRANSF
      WHERE
        M1.ANSTART * 12 + M1.LUNASTART &gt;= getANLUCRU() * 12 + getLUNALUCRU()
        AND M1.CODNIRSTOC = MF_TRANSF.CODNIRSTOPARINTE
        AND M1.CODMIFIX = MF_TRANSF.CODMIFIX_TRANSF1
    ) LOOP
      UPDATE MIFIX1
      SET CODNIRSTOC = V_REC.CODNIRSTOCDEST
      WHERE CODMIFIX1 = V_REC.CODMIFIX1;

      SELECT COUNT(*) INTO NR
      FROM
        FISAMF
      WHERE
        CODMIFIX = V_REC.CODMIFIX
        AND CODOPERATIE = 2
        AND CODDOC1 = V_REC.CODTRANSF1
        AND TIPDOC = 12;

      IF NR = 0 THEN
        INSERT INTO FISAMF(CODFISAMF, CODMIFIX, CODOPERATIE, DATAOPERATIE, GESTSURSA, GESTDEST, PRETI, PRETE, PREFIXDOC, NRDOC, CANT, CODDOC1, TIPDOC)
        VALUES(NEXTVAL('SEQ_FISAMF_CODFISAMF'), V_REC.CODMIFIX, 2, V_REC.DATALIVR, V_REC.GESTSURSA, V_REC.GESTDEST, V_REC.PRETI, V_REC.PRETE, 'NT', V_REC.NRDOC, 1, V_REC.CODTRANSF1, 12);
      END IF;

      UPDATE JURNAL1
      SET
        DIRTY = 1
      WHERE
        CODDOC = V_REC.CODMIFIX
        AND TIPDOC = 36
        AND AN * 12 + LUNA &gt;= getANLUCRU() * 12 + getLUNALUCRU();
    END LOOP;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_solve_transf_mifix_serie</obj_name>
  <obj_hashval>57e3ff9fda455044b95307d5a06efee0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_solve_transf_mifix_serie(acodtransf numeric, legaturatransf1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR NUMERIC;
  V_REC record;
BEGIN
  --Florin 18.11.2025 - sinc. Oracle
  --Florin 14.11.2023
  if LegaturaTransf1 = 0 then
    FOR V_REC IN
    (
    SELECT M1.CODMIFIX1, M1.CODMIFIX, M1.ANSTART, M1.LUNASTART, M.TIP, MF_TRANSF.*
    FROM
     MIFIX1 M1,
     MIFIX M,
    (
    SELECT
      NSP.CODNIRSTOC CODNIRSTOPARINTE,
      NSP.CANTNIR AS CANTNIRPARINTE,
      NSEP.CODNIRSER AS CODNIRSSERPARINTE,
      NSD.CODNIRSTOC CODNIRSTOCDEST,
      NSED.CODNIRSER AS CODNIRSERDEST,
      L1.CANT,
      L.DATALIVR,
      NP.GEST AS GESTSURSA,
      ND.GEST AS GESTDEST,
      NSP.PRET AS PRETE,
      NSD.PRET AS PRETI,
      NSD.CODTRANSF1,
      NSP.CODIOART AS CODIOARTP,
      NSD.CODIOART AS CODIOARTD,
      T.NRDOC
    FROM
      LIVR1 L1,
      LIVR L,
      TRANSF T,
      NIRSER NSEP,
      NIRSTOC NSD,
      NIRSER NSED,
      NIRSTOC NSP,
      NIR ND,
      NIR NP,
      TMP_IOART_LUNA IOA
    WHERE
      L.CODTRANSF = aCODTRANSF
      AND L1.CODLIVR = L.CODLIVR
      AND NSEP.CODNIRSER = L1.CODNIRSER
      AND NSD.CODLIVR1 = L1.CODLIVR1
      AND IOA.CODIOART = NSD.CODIOART
      AND COALESCE(IOA.ESTEMIFIX, 0) + COALESCE(IOA.ESTEOBINV, 0) = 1
      AND NSED.CODNIRSTOC = NSD.CODNIRSTOC
      AND NSP.CODNIRSTOC = L1.CODNIRSTOC
      AND NVL(NSP.TIPSERIE, 0) = 1
      AND L1.CANT = 1
      AND ND.CODNIR = NSD.CODNIR
      AND NP.CODNIR = NSP.CODNIR
      AND L.CODTRANSF = T.CODTRANSF
    ) MF_TRANSF
    WHERE
    --  M1.ANSTART = PKG_GLOBALS.ANLUCRU
    --  AND M1.LUNASTART = PKG_GLOBALS.LUNALUCRU
       M1.ANSTART * 12 + M1.LUNASTART &gt;= getANLUCRU() * 12 + getLUNALUCRU()
      AND M1.CODNIRSTOC = MF_TRANSF.CODNIRSTOPARINTE
      AND NVL(M1.CODNIRSER, 0) = NVL(MF_TRANSF.CODNIRSSERPARINTE, 0)
      AND M.CODMIFIX = M1.CODMIFIX
    )
    LOOP
    -- START CERINTA SAFT : LA SCHIMBARE TIP CONTABIL CREEZ MIFIXNOU --
        IF V_REC.CODIOARTP &lt;&gt; V_REC.CODIOARTD   AND V_REC.TIP = 'MF' THEN
          perform pkg_miscari_interne_MAKE_MIFIX_NOU(V_REC.CODMIFIX, V_REC.CODMIFIX1, V_REC.ANSTART, V_REC.LUNASTART);
        END IF;
    -- END CERINTA SAFT : LA SCHIMBARE TIP CONTABIL CREEZ MIFIXNOU --
        UPDATE MIFIX1
        SET
          CODNIRSTOC = V_REC.CODNIRSTOCDEST,
          CODNIRSER = V_REC.CODNIRSERDEST
        WHERE
          CODMIFIX1 = V_REC.CODMIFIX1;

           INSERT INTO FISAMF(CODFISAMF,
                              CODMIFIX,
                              CODOPERATIE,
                              DATAOPERATIE,
                              GESTSURSA,
                              GESTDEST,
                              PRETI,
                              PRETE,
                              PREFIXDOC,
                              NRDOC,
                              CANT,
                              CODDOC1,
                              TIPDOC)
                       VALUES(NEXTVAL('SEQ_FISAMF_CODFISAMF'),
                              V_REC.CODMIFIX,
                              2,
                              V_REC.DATALIVR,
                              V_REC.GESTSURSA,
                              V_REC.GESTDEST,
                              V_REC.PRETI,
                              V_REC.PRETE,
                              'NT',
                              V_REC.NRDOC,
                              1,
                              V_REC.CODTRANSF1,
                              12);
          UPDATE JURNAL1
          SET
            DIRTY = 1
          WHERE
            CODDOC = V_REC.CODMIFIX
            AND TIPDOC = 36
            AND AN * 12 + LUNA &gt;= getANLUCRU() * 12 + getLUNALUCRU();
    END LOOP;

  else
    FOR V_REC IN
    (
    SELECT M1.CODMIFIX1, M1.CODMIFIX, M1.ANSTART, M1.LUNASTART, M.TIP,  MF_TRANSF.*
    FROM
     MIFIX1 M1,
     MIFIX M,
    (
    SELECT
      NSP.CODNIRSTOC CODNIRSTOPARINTE,
      NSP.CANTNIR AS CANTNIRPARINTE,
      NSEP.CODNIRSER AS CODNIRSSERPARINTE,
      NSD.CODNIRSTOC CODNIRSTOCDEST,
      NSED.CODNIRSER AS CODNIRSERDEST,
      L1.CANT,
      L.DATALIVR,
      NP.GEST AS GESTSURSA,
      ND.GEST AS GESTDEST,
      NSP.PRET AS PRETE,
      NSD.PRET AS PRETI,
      NSD.CODTRANSF1,
      T.NRDOC,
      NSP.CODIOART AS CODIOARTP,
      NSD.CODIOART AS CODIOARTD,
      T1.CODMIFIX AS CODMIFIX_TRANSF1
    FROM
      LIVR1 L1,
      LIVR L,
      TRANSF T,
      TRANSF1 T1,
      NIRSER NSEP,
      NIRSTOC NSD,
      NIRSER NSED,
      NIRSTOC NSP,
      NIR ND,
      NIR NP,
      TMP_IOART_LUNA IOA
    WHERE
      L.CODTRANSF = aCODTRANSF
      AND L1.CODLIVR = L.CODLIVR
      AND T1.CODTRANSF1 = L1.CODIES1
      AND NSEP.CODNIRSER = L1.CODNIRSER
      AND NSD.CODLIVR1 = L1.CODLIVR1
      AND IOA.CODIOART = NSD.CODIOART
      AND COALESCE(IOA.ESTEMIFIX, 0) + COALESCE(IOA.ESTEOBINV, 0) = 1
      AND NSED.CODNIRSTOC = NSD.CODNIRSTOC
      AND NSP.CODNIRSTOC = L1.CODNIRSTOC
      AND NVL(NSP.TIPSERIE, 0) = 1
      AND L1.CANT = 1
      AND ND.CODNIR = NSD.CODNIR
      AND NP.CODNIR = NSP.CODNIR
      AND L.CODTRANSF = T.CODTRANSF
    ) MF_TRANSF
    WHERE
    --  M1.ANSTART = PKG_GLOBALS.ANLUCRU
    --  AND M1.LUNASTART = PKG_GLOBALS.LUNALUCRU
       M1.ANSTART * 12 + M1.LUNASTART &gt;= getANLUCRU() * 12 + getLUNALUCRU()
      AND M1.CODNIRSTOC = MF_TRANSF.CODNIRSTOPARINTE
      AND NVL(M1.CODNIRSER, 0) = NVL(MF_TRANSF.CODNIRSSERPARINTE, 0)
      AND M1.CODMIFIX = MF_TRANSF.CODMIFIX_TRANSF1
      AND M1.CODMIFIX = M.CODMIFIX
    )
    LOOP
    -- START CERINTA SAFT : LA SCHIMBARE TIP CONTABIL CREEZ MIFIXNOU --
        IF V_REC.CODIOARTP &lt;&gt; V_REC.CODIOARTD   AND V_REC.TIP = 'MF' THEN
          perform pkg_miscari_interne_MAKE_MIFIX_NOU(V_REC.CODMIFIX, V_REC.CODMIFIX1, V_REC.ANSTART, V_REC.LUNASTART);
        END IF;
    -- END CERINTA SAFT : LA SCHIMBARE TIP CONTABIL CREEZ MIFIXNOU --
        UPDATE MIFIX1
        SET
          CODNIRSTOC = V_REC.CODNIRSTOCDEST,
          CODNIRSER = V_REC.CODNIRSERDEST
        WHERE
          CODMIFIX1 = V_REC.CODMIFIX1;

           INSERT INTO FISAMF(CODFISAMF,
                              CODMIFIX,
                              CODOPERATIE,
                              DATAOPERATIE,
                              GESTSURSA,
                              GESTDEST,
                              PRETI,
                              PRETE,
                              PREFIXDOC,
                              NRDOC,
                              CANT,
                              CODDOC1,
                              TIPDOC)
                       VALUES(NEXTVAL('SEQ_FISAMF_CODFISAMF'),
                              V_REC.CODMIFIX,
                              2,
                              V_REC.DATALIVR,
                              V_REC.GESTSURSA,
                              V_REC.GESTDEST,
                              V_REC.PRETI,
                              V_REC.PRETE,
                              'NT',
                              V_REC.NRDOC,
                              1,
                              V_REC.CODTRANSF1,
                              12);
          UPDATE JURNAL1
          SET
            DIRTY = 1
          WHERE
            CODDOC = V_REC.CODMIFIX
            AND TIPDOC = 36
            AND AN * 12 + LUNA &gt;= getANLUCRU() * 12 + getLUNALUCRU();
    END LOOP;
  end if;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_stoc_neg_livr1_transf_rosu</obj_name>
  <obj_hashval>4326bfa81ad06ec5ed8907d374111745</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_stoc_neg_livr1_transf_rosu(INOUT wme_result numeric, INOUT acodlivr1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  STOCNEG numeric := 0;
  NR      numeric := 0;
begin
  SELECT COUNT( *) INTO NR FROM LIVR1 L1, LIVR L WHERE L1.CANT &lt; 0 AND  L1.CODLIVR = L.CODLIVR AND  L.TIPLIVR = 12 AND  L1.CODLIVR1 = aCODLIVR1;

  IF  NR = 0 THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  FOR V_REC IN (SELECT NS.CODNIRSTOC, NS.CANTNIR, ALTELIVR.CANTIES, LIVRCURENT.CANTDOCCURENT
                FROM (SELECT L1.CODNIRSTOC, SUM( CASE WHEN  L.TIPLIVR=15 THEN -L1.CANT ELSE  L1.CANT END ) AS CANTDOCCURENT
                      FROM LIVR1 L1, LIVR L WHERE L1.CODLIVR = L.CODLIVR AND  L.TIPLIVR = 12 AND  L1.CODLIVR1 = aCODLIVR1
                      GROUP BY L1.CODNIRSTOC
                     ) LIVRCURENT,
                     (SELECT CODNIRSTOC, SUM( CASE WHEN  L.TIPLIVR=15 THEN -L1.CANT ELSE  L1.CANT END ) AS CANTIES
                      FROM LIVR1 L1, LIVR L
                      WHERE L1.CODLIVR = L.CODLIVR AND  NOT (   L.TIPLIVR = 12 AND  L1.CODLIVR1 = aCODLIVR1)
                      GROUP BY CODNIRSTOC
                     ) ALTELIVR,
                     NIRSTOC NS
                WHERE NS.CODNIRSTOC = LIVRCURENT.CODNIRSTOC AND  LIVRCURENT.CODNIRSTOC = ALTELIVR.CODNIRSTOC
  )
  LOOP
    IF  V_REC.CANTNIR &lt; V_REC.CANTIES THEN
      WME_Result :=  1;
      RETURN;
    END IF;
  END LOOP;

  WME_Result :=  STOCNEG;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_stocneg_la_sterg_transf_rosu</obj_name>
  <obj_hashval>cd606d0ee353643a34ff90a1a44fc507</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_stocneg_la_sterg_transf_rosu(INOUT wme_result numeric, INOUT acodtransf numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  STOCNEG numeric := 0;
  NR      numeric := 0;
begin
  SELECT COUNT( *) INTO NR FROM LIVR1 L1, LIVR L WHERE L1.CANT &lt; 0 AND  L1.CODLIVR = L.CODLIVR AND  L.TIPLIVR = 12 AND  L.CODTRANSF = aCODTRANSF;

  IF  NR = 0 THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  FOR V_REC IN (SELECT NS.CODNIRSTOC, NS.CANTNIR, ALTELIVR.CANTIES, LIVRCURENT.CANTDOCCURENT
                FROM (SELECT L1.CODNIRSTOC, SUM( CASE WHEN  L.TIPLIVR=15 THEN -L1.CANT ELSE  L1.CANT END ) AS CANTDOCCURENT
                      FROM LIVR1 L1, LIVR L
                      WHERE L1.CODLIVR = L.CODLIVR AND  L.TIPLIVR = 12 AND  L.CODTRANSF = aCODTRANSF
                      GROUP BY L1.CODNIRSTOC
                     ) LIVRCURENT,
                     (SELECT CODNIRSTOC, SUM( CASE WHEN  L.TIPLIVR=15 THEN -L1.CANT ELSE  L1.CANT END ) AS CANTIES
                      FROM LIVR1 L1, LIVR L
                      WHERE L1.CODLIVR = L.CODLIVR AND  NOT (   L.TIPLIVR = 12 AND  L.CODTRANSF = aCODTRANSF)
                      GROUP BY CODNIRSTOC
                     ) ALTELIVR,
                     NIRSTOC NS
                WHERE NS.CODNIRSTOC = LIVRCURENT.CODNIRSTOC AND  LIVRCURENT.CODNIRSTOC = ALTELIVR.CODNIRSTOC
               )
  LOOP
    IF  V_REC.CANTNIR &lt; V_REC.CANTIES THEN
      WME_Result :=  1;
      RETURN;
    END IF;
  END LOOP;

  WME_Result :=  STOCNEG;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_vskipmifixaut</obj_name>
  <obj_hashval>f041a7f400261c6d07a266841380030c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_vskipmifixaut(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_MISCARI_INTERNE.vSkipMifixAut'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := False;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_monede_getcursmoneda</obj_name>
  <obj_hashval>795df0d0c5d411ab29e12ace6b66cb12</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_monede_getcursmoneda(INOUT wme_result numeric, INOUT acodmoneda numeric, INOUT acodbanca numeric, INOUT adata character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCURS double precision := 0;
BEGIN
  BEGIN
    SELECT COALESCE( VALOARE, 1)
    INTO aCURS
    FROM NMONEDE N, NMONEDE1 N1
    WHERE N.CODMONEDA = N1.CODMONEDA AND  N1.CODBANCA = aCODBANCA AND  N.CODMONEDA = aCODMONEDA AND
          DATA = (SELECT MAX( DATA)
                  FROM NMONEDE1
                  WHERE CODBANCA = aCODBANCA AND  CODMONEDA = aCODMONEDA AND  DATA &lt;= TO_DATE( aDATA, 'dd.mm.yyyy')
                 );
  EXCEPTION WHEN OTHERS THEN
    aCURS := 1;
  END;

  IF coalesce(aCURS,0) = 0 THEN aCURS := 1; END IF;

  WME_Result :=  aCURS;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_monede_getdatacurs</obj_name>
  <obj_hashval>19ae08287333002060a52a5911e6a9bf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_monede_getdatacurs(INOUT wme_result numeric, INOUT acodmoneda numeric, INOUT acodbanca numeric, INOUT adatadoc date, INOUT acurs numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
aDATA date;
BEGIN
  aData := null;
  BEGIN
    SELECT N1.DATA INTO aDATA
    FROM
      NMONEDE  N,
      NMONEDE1 N1
    WHERE
      N.CODMONEDA = N1.CODMONEDA AND
      N1.CODBANCA = aCODBANCA  AND
      N.CODMONEDA = aCODMONEDA AND
      DATA = (SELECT MAX(M1.DATA) FROM NMONEDE1 M1 WHERE M1.CODBANCA = aCODBANCA AND M1.CODMONEDA = aCODMONEDA AND M1.DATA &lt;= aDATADOC and M1.VALOARE = aCURS);
    EXCEPTION WHEN OTHERS THEN aData := null;
  END;
  WME_Result :=  aDATA;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_monede_getdatacurs</obj_name>
  <obj_hashval>d80cb294f25d25280df62a3f9275b861</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_monede_getdatacurs(acodmoneda numeric, acodbanca numeric, adatadoc date, acurs numeric)
 RETURNS date
 LANGUAGE plpgsql
AS $function$
DECLARE
aDATA date;
BEGIN
  --Adina 23 septembrie 2020
  aData := null;
  BEGIN
    SELECT N1.DATA INTO aDATA
    FROM
      NMONEDE  N,
      NMONEDE1 N1
    WHERE
      N.CODMONEDA = N1.CODMONEDA AND
      N1.CODBANCA = aCODBANCA  AND
      N.CODMONEDA = aCODMONEDA AND
      DATA = (SELECT MAX(M1.DATA) FROM NMONEDE1 M1 WHERE M1.CODBANCA = aCODBANCA AND M1.CODMONEDA = aCODMONEDA AND M1.DATA &lt;= aDATADOC and M1.VALOARE = aCURS);
    EXCEPTION WHEN OTHERS THEN aData := null;
  END;
  RETURN aDATA;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_monede_getmonedacurenta</obj_name>
  <obj_hashval>f4016eb346f7fb5fb519ddd1f9a50dd7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_monede_getmonedacurenta(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_MONEDE.MONEDACURENTA')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_monede_moneda_valida</obj_name>
  <obj_hashval>dbc6c8b7c2341330de2cb55d53cb2b3b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_monede_moneda_valida(acodmoneda numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vMonC NUMERIC := CASE WHEN length(current_setting('PKG_MONEDE.MONEDACURENTA',true))=0 THEN 0 ELSE current_setting('PKG_MONEDE.MONEDACURENTA',true)::NUMERIC END;
BEGIN
  --Adina 23 septembrie 2020
  IF  vMonC &lt; 0 THEN
    RETURN 1;
  ELSE
    IF  aCODMONEDA = vMonC THEN
      RETURN 1;
    ELSE
      RETURN 0;
    END IF;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_monede_moneda_valida</obj_name>
  <obj_hashval>8f0a8e267bb6c4963ef9c353b754fdff</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_monede_moneda_valida(INOUT wme_result numeric, INOUT acodmoneda numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  TO_NUMBER((current_setting('PKG_MONEDE.MONEDACURENTA',true)),'999999999999999999') &lt; 0 THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    IF  aCODMONEDA = TO_NUMBER((current_setting('PKG_MONEDE.MONEDACURENTA',true)),'999999999999999999') THEN
      WME_Result :=  1;
      RETURN;
    ELSE
      WME_Result :=  0;
      RETURN;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_monede_monedacurenta</obj_name>
  <obj_hashval>8ab5d8f56c6959123eed79fceb7b02cd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_monede_monedacurenta(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_MONEDE.MONEDACURENTA')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_monede_set_moneda_curenta</obj_name>
  <obj_hashval>d876f543516cb6a1353ee540cf1b3b4d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_monede_set_moneda_curenta(acodmoneda numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_MONEDE.MONEDACURENTA',to_char(aCodMoneda,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_monede_sp_deleterecord</obj_name>
  <obj_hashval>5be7ee23473ded01ac0647b3be2ca743</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_monede_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_MONEDE_SP_LOCKRECORD( RecId);
  DELETE FROM NMONEDE1 WHERE codmoneda = RecId;
  DELETE FROM NMONEDE  WHERE codmoneda = RecId;
  PERFORM NotifyModif( 2, RECID, 'NMONEDE');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_monede_sp_gotorecord</obj_name>
  <obj_hashval>18dc02f7148afad2a22074d6a14a7f94</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_monede_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 05.02.2021
  INSERT INTO TMP_NMONEDE (codmoneda, den_moneda, simbol, Sdenumire, ssimbol, zecimale)
  (SELECT codmoneda, den_moneda, simbol, Sdenumire, ssimbol, zecimale FROM NMONEDE WHERE codmoneda = RecId);

  INSERT INTO TMP_NMONEDE1 (codmoneda1, codmoneda, codbanca, data, valoare)
  (SELECT codmoneda1, codmoneda, codbanca, data, valoare FROM NMONEDE1 WHERE codmoneda = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_monede_sp_lockrecord</obj_name>
  <obj_hashval>ca6a659a78984921cb03c79e4bfc104a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_monede_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT codmoneda INTO Tmp FROM NMONEDE WHERE codmoneda = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_monede_sp_postrecords</obj_name>
  <obj_hashval>6c999be21abac49b16963fdb23b7fd7e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_monede_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  vRecNo integer := 0;
  vAn    integer := 0;
  vLuna  integer := 0;
  vCod   numeric;
begin
  --Bogdan 05.02.2021
  IF Operation = 0 THEN
    SELECT codmoneda INTO RecId FROM TMP_NMONEDE;

    UPDATE NMONEDE
    SET
      (den_moneda, simbol, Sdenumire, ssimbol, zecimale) = (SELECT den_moneda, simbol, Sdenumire, ssimbol, zecimale FROM TMP_NMONEDE)
    WHERE
      codmoneda = RecId;

    DELETE FROM NMONEDE1
    WHERE (codmoneda = RecId AND codmoneda1 NOT IN (SELECT codmoneda1 FROM TMP_NMONEDE1 WHERE COALESCE (codmoneda1, 0) &lt;&gt; 0));

    INSERT INTO NMONEDE1 (codmoneda1, codmoneda, codbanca, data, valoare)
    SELECT NEXTVAL ('SEQ_NMONEDE1_CODMONEDA1') , RecId, codbanca, data, valoare FROM TMP_NMONEDE1 WHERE codmoneda1 &lt; 0;

    FOR v_rec IN (SELECT * FROM TMP_NMONEDE1 WHERE COALESCE (codmoneda1, -1) &gt; 0 ORDER BY codmoneda1) LOOP
      UPDATE NMONEDE1
      SET
      codmoneda = RecId,
      codbanca  = v_rec.codbanca,
      data      = v_rec.data,
      valoare   = v_rec.valoare
      WHERE
        codmoneda1 = v_rec.codmoneda1;
    END LOOP;
  ELSE
    SELECT NEXTVAL ('SEQ_NMONEDE_CODMONEDA') INTO RecId;

    INSERT INTO NMONEDE (codmoneda, den_moneda, simbol, Sdenumire, ssimbol, zecimale)
    (SELECT RecId, den_moneda, simbol, Sdenumire, ssimbol, zecimale FROM TMP_NMONEDE);

    INSERT INTO NMONEDE1 (codmoneda1, codmoneda, codbanca, data, valoare)
    (SELECT NEXTVAL ('SEQ_NMONEDE1_CODMONEDA1') , RecId, codbanca, data, valoare FROM TMP_NMONEDE1);
  END IF;

  PERFORM NotifyModif( OPERATION, RECID, 'NMONEDE');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_motive_sp_deleterecord</obj_name>
  <obj_hashval>4e4c4de839cde866a27dde0f81a9c065</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_motive_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_MOTIVE_SP_LOCKRECORD( RecId);
  DELETE FROM MOTIVE WHERE CodMOTIV = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_motive_sp_gotorecord</obj_name>
  <obj_hashval>bb3b2620dadaf725c6811635a98a10c0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_motive_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_MOTIVE(CodMOTIV, Continut, Tip, Cod, Motiv)
  (SELECT CodMOTIV, Continut, Tip, Cod, Motiv FROM MOTIVE WHERE CodMOTIV = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_motive_sp_lockrecord</obj_name>
  <obj_hashval>e7fcd03ba0ecbbb66971eb10bb52e35b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_motive_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodMOTIV INTO Tmp FROM MOTIVE WHERE CodMOTIV = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_motive_sp_postrecords</obj_name>
  <obj_hashval>afe300e5724fd335693e453b37ed4cf9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_motive_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    SELECT CodMOTIV INTO RecId FROM TMP_MOTIVE;

    UPDATE MOTIVE
    SET
    (Continut, Tip, Cod, Motiv) = (SELECT Continut, Tip, Cod, Motiv FROM TMP_MOTIVE)
    WHERE
     CodMOTIV = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_MOTIVE_CODMOTIV') INTO RecId;

    INSERT INTO MOTIVE(CodMOTIV, Continut, Tip, Cod, Motiv)
    (SELECT RecId, Continut, Tip, Cod, Motiv FROM TMP_MOTIVE);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_motivep_ct_monitor</obj_name>
  <obj_hashval>fe6aaff21f70e36651e3107243732ab4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_motivep_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_MOTIVEP.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_57';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_motivep_getct_monitor</obj_name>
  <obj_hashval>47d35e240128f8a24319342f3dadff26</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_motivep_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_MOTIVEP.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_57';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_motivep_setct_monitor</obj_name>
  <obj_hashval>29b6673ec798d5353a875efbfdb659e9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_motivep_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_MOTIVEP.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_motivep_sp_deleterecord</obj_name>
  <obj_hashval>8dfe962f5bc06c59772917678e06bd23</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_motivep_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDoc varchar;
BEGIN
  --Florin 01.06.2023 - monitor
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_motivep_setct_monitor('MON_57');
  PERFORM PKG_MOTIVEP_SP_LockRecord( RecId);

  IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_MOTIVEP.CT_MONITOR', true))))
  THEN
    SELECT 'Motiv "' || denmotiv || '"' INTO aDoc FROM MotiveP WHERE codmotiv = recid;
    PERFORM pkg_userfirme_postlogcucommit( 'MotiveP', (current_setting('PKG_GLOBALS.USERNAME', true)), 'S', RECID, (current_setting('PKG_GLOBALS.FIRMANAME', true)), TO_NUMBER((current_setting('PKG_GLOBALS.SUBUNITATE', true)),'999999999999999999'), null, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  DELETE FROM MotiveP WHERE CodMotiv = RecId;

  PERFORM NotifyModif( 2, RECID, 'MOTIVEP');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_motivep_sp_insertrecord</obj_name>
  <obj_hashval>59c963566895434cb52b87ab6fd4e362</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_motivep_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO Tmp_MotiveP (CodMotiv) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_motivep_sp_lockrecord</obj_name>
  <obj_hashval>891bfd6dbf30c8e711f684e38ad8f597</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_motivep_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodMotiv INTO Tmp FROM MotiveP WHERE CodMotiv = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_motivep_sp_postrecords</obj_name>
  <obj_hashval>cf5405b72322eff793ff99f68804df0c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_motivep_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDoc varchar;
BEGIN
  --Florin 01.06.2023 - monitor
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_motivep_setct_monitor('MON_57');
  IF  Operation = 0 THEN
    SELECT CodMotiv INTO RecId FROM Tmp_MotiveP;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_MOTIVEP.CT_MONITOR', true))))
    THEN
      SELECT 'Motiv "' || denmotiv || '"' INTO aDoc FROM MotiveP WHERE codmotiv = recid;
      PERFORM pkg_userfirme_postlogcucommit( 'MotiveP', (current_setting('PKG_GLOBALS.USERNAME', true)), 'M', RECID, (current_setting('PKG_GLOBALS.FIRMANAME', true)), TO_NUMBER((current_setting('PKG_GLOBALS.SUBUNITATE', true)),'999999999999999999'), null, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    UPDATE MotiveP
    SET
    (CodMotiv, DenMotiv, Motiv) = (SELECT CodMotiv, DenMotiv, Motiv FROM Tmp_MotiveP)
    WHERE
     CodMotiv = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_MOTIVEP_CODMOTIV') INTO RecId;

    INSERT INTO MotiveP(CodMotiv, DenMotiv, Motiv)
    (SELECT RecId, DenMotiv, Motiv FROM Tmp_MotiveP);

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_MOTIVEP.CT_MONITOR', true))))
    THEN
      SELECT 'Motiv "' || denmotiv || '"' INTO aDoc FROM MotiveP WHERE codmotiv = recid;
      PERFORM pkg_userfirme_postlogcucommit( 'MotiveP', (current_setting('PKG_GLOBALS.USERNAME', true)), 'A', RECID, (current_setting('PKG_GLOBALS.FIRMANAME', true)), TO_NUMBER((current_setting('PKG_GLOBALS.SUBUNITATE', true)),'999999999999999999'), null, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;
  END IF;

  PERFORM NotifyModif( OPERATION, RECID, 'MOTIVEP');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nc_ct_monitor</obj_name>
  <obj_hashval>ea5c0af64408445899c3f860afb56c6d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nc_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NC.CT_MONITOR', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_40';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nc_getct_monitor</obj_name>
  <obj_hashval>6821a910e132317a00c160a0d15b3dba</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nc_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NC.CT_MONITOR', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_40';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nc_setct_monitor</obj_name>
  <obj_hashval>cd9b1fcf2b2fb01cf14adbe2d5518b4e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nc_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NC.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nc_sp_insertrecord</obj_name>
  <obj_hashval>655785642648d878db107c17a1d09d07</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nc_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 20.04.2023 - sinc. Oracle
  delete from NC1_MAN;
  PERFORM PKG_CFGTABLES_CHECK_STRUCT_EXTENSIE_X_TIPDOC(35);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(35);

  INSERT INTO TMP_NC (CodNC, sablon) VALUES(0, 0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nc_sp_lockrecord</obj_name>
  <obj_hashval>7facb97b0de6460504279eb3128bc5d6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nc_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodNC INTO Tmp FROM NC WHERE CodNC = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nc_sp_postrecords</obj_name>
  <obj_hashval>4e39e33658d1e15f71cc60f377f3f85b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nc_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  V_REC        RECORD;
  V_RECAV      RECORD;
  V_RECJURN    RECORD;
  V_REC_SUB    RECORD;
  V_CHELT1     RECORD;
  v_xxx        RECORD;
  vCod         numeric;
  NR           numeric := 0;
  aCARNETDOC   numeric := 0;
  aNRDOC       numeric := 0;
  aMONEDA      numeric := 0;
  aSubunitatea numeric;
  aDataDoc     date;
  aDoc         varchar;
  aCURS        double precision;
  NRCHELT      numeric := 0;
  aAn          numeric;
  aLuna        numeric;
  aCount       numeric;
BEGIN
  --Florin 12.11.2025 - sinc. Oracle
  --Florin 22.10.2025 - sinc. Oracle
  --Florin 01.06.2023 - monitor
  --Florin 20.04.2023 - sinc. Oracle
  --Florin 07.12.2022 - sinc. Oracle
  --Laura 06.12.2021 - sinc Oracle (06.12.2021)
  --Laura 03.12.2021 - sinc Oracle (03.12.2021)
  --Adina 14.08.2021 - sinc.Oracle din 13.08.2021
    --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
    perform pkg_nc_setct_monitor('MON_62');
    PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT (35);
  begin
    SELECT CARNETDOC, NRDOC, CURS, coalesce( MONEDA, 0),
           CodNC, subunitatea, datadoc, 'NC'||COALESCE(nrdoc::varchar,'')||'/'||COALESCE(to_char(datadoc,'dd.mm.yyyy'),''), An, Luna
    INTO aCARNETDOC, aNRDOC, aCURS, aMONEDA,
         RecId,aSubunitatea,aDataDoc,aDoc,aAn,aLuna
    FROM TMP_NC;

    if coalesce( aCURS, 0) = 0 then aCURS := 1; end if;
    if aMONEDA = 0 then aCURS := 1; end if;

    if fnc_GetValConstantaLucru('MifixExtins')::numeric = 1 then
      DELETE FROM tmp_manevra_intr1;
    end if;

    UPDATE TMP_NC1 SET (An, Luna) = (SELECT N.An, N.Luna FROM TMP_NC N) WHERE An IS NULL OR Luna IS NULL;

    IF Operation = 0 THEN   -- UPDATE
      if (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT
          FROM   PKG_USERFIRME_ValidPostLog(null, to_number(current_setting('PKG_GLOBALS.USERID', true), '999999999999999999'), current_setting('PKG_NC.CT_MONITOR', true)))
      then
        perform pkg_userfirme_postlogcucommit('NC', current_setting('PKG_GLOBALS.USERNAME', true), 'M', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true),
                                              aSubunitatea, aDataDoc, aDoc, '-',
                                              (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(null, null)));
      end if;

      UPDATE NC
      SET
        (Part, JurnalTVA, TIPTRANZ, TIPTVA, Valoare, Moneda, Curs, Obs, NrDoc, DataDoc, An, Luna, SUBUNITATEA, sablon, CARNETDOC, CodAnaliza, Aprobat)
        =
        (SELECT Part, JurnalTVA, TIPTRANZ, TIPTVA, Valoare, Moneda, Curs, Obs, NrDoc, DataDoc, AN, Luna, SUBUNITATEA, sablon, CARNETDOC, CodAnaliza, Aprobat
         FROM TMP_NC )
      WHERE CodNC = RecId ;

      DELETE FROM OBLIGPIF
      WHERE CODGENERAL in (SELECT CODGENERAL FROM GENERAL WHERE TIPDOC = 35 and CODDOC in (SELECT CODNC1 FROM NC1 WHERE CODNC = RecID ) )
        and CODOBLIGPIF not in (SELECT CODOBLIGPIF FROM TMP_OBLIGPIF );

      DELETE FROM GENERAL
      WHERE TIPDOC = 35 and CODDOC in (SELECT CODNC1 FROM NC1 WHERE CODNC = RecID ) and CODGENERAL not in (SELECT CODGENERAL FROM TMP_GENERAL );

      for V_REC in (SELECT * FROM NC1 WHERE CodNC = RecId and CodNC1 not in (SELECT CodNC1 FROM TMP_NC1 ) ) loop
        for V_RECAV in (SELECT * FROM CHELTAVANS WHERE CODNC1 = V_REC.CODNC1 ) loop
          for V_RECJURN in (SELECT * FROM JURNAL WHERE CODDOC = V_RECAV.CODCHELTAVANS and TIPDOC in (52, 106) ) loop
            UPDATE NCONTRUL
            SET
              RULAJCD      = RULAJCD      - V_RECJURN.VALOARE,
              RULAJVCD     = RULAJVCD     - V_RECJURN.VALOAREV,
              RULAJC_IFRS  = RULAJC_IFRS  - V_RECJURN.VALOARE_IFRS,
              RULAJVC_IFRS = RULAJVC_IFRS - V_RECJURN.VALOAREV_IFRS,
              RULAJC_GRUP  = RULAJC_IFRS  - V_RECJURN.VALOAREGRUP,
              RULAJVC_GRUP = RULAJVC_GRUP - (SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(null, coalesce( V_RECJURN.VALOAREGRUP, 0), coalesce( V_RECJURN.VALOARE, 0), coalesce( V_RECJURN.VALOAREV, 0)))
            WHERE
              CODCONT = V_RECJURN.CONTD
              and AN = V_RECJURN.AN
              and LUNA = V_RECJURN.LUNA ;

            UPDATE NCONTRUL
            SET
              RULAJCC      = RULAJCC      - V_RECJURN.VALOARE,
              RULAJVCC     = RULAJVCC     - V_RECJURN.VALOAREV,
              RULAJC_IFRS  = RULAJC_IFRS  - V_RECJURN.VALOARE_IFRS,
              RULAJVC_IFRS = RULAJVC_IFRS - V_RECJURN.VALOAREV_IFRS,
              RULAJC_GRUP  = RULAJC_GRUP  - V_RECJURN.VALOAREGRUP,
              RULAJVC_GRUP = RULAJVC_GRUP - (SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(null, coalesce( V_RECJURN.VALOAREGRUP, 0), coalesce( V_RECJURN.VALOARE, 0), coalesce( V_RECJURN.VALOAREV, 0)))
            WHERE
              CODCONT = V_RECJURN.CONTC
              and AN = V_RECJURN.AN
              and LUNA = V_RECJURN.LUNA ;
          end loop;

          DELETE FROM JURNAL1 WHERE CODDOC = V_RECAV.CODCHELTAVANS and TIPDOC in (52, 106);
          DELETE FROM JURNAL  WHERE CODDOC = V_RECAV.CODCHELTAVANS and TIPDOC in (52, 106);

          DELETE FROM CHELTAVANS1 WHERE CODCHELTAVANS = V_RECAV.CODCHELTAVANS;
          DELETE FROM CHELTAVANS  WHERE CODCHELTAVANS = V_RECAV.CODCHELTAVANS;
        end loop;

        DELETE FROM MASTERCHELTAVANS WHERE CODNC1 = V_REC.CODNC1;
        DELETE FROM NC1 WHERE CODNC1 = V_REC.CODNC1;
      end loop;

      for v_rec in (SELECT * FROM TMP_NC1 order BY INDEXLOCAL ) loop
        if v_rec.CODNC1 &lt; 0 then
          SELECT nextval('SEQ_NC1_CODNC1') INTO vCod;

          UPDATE TMP_GENERAL SET CODDOC     = vCod WHERE CODDOC     = v_rec.CODNC1 ;
          UPDATE TMP_JURNAL  SET INDEXLOCAL = vCod WHERE INDEXLOCAL = v_rec.CODNC1 ;
          UPDATE TMP_JURNAL1 SET INDEXLOCAL = vCod WHERE INDEXLOCAL = v_rec.CODNC1 ;

          PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('NC1', vCod, V_REC.CODNC1);

          INSERT INTO NC1 (
            PartD, PersD, PartC, PersC,CODPART, CODMIFIX, MFSaft, CODCMDINT1, CODNC1, CODNC, CONTD, CONTC,
            ICONTD, ICONTC, TIPLINIETVA, VALOARE,
            RESTIMBMF,
            OBS, CODGEST, CODFORMATIE, AN, LUNA, INDEXLOCAL, CODCENTRU, CODAUTO, AGENT, CODANALIZANOD )
          VALUES (
            v_rec.PartD, v_rec.PersD, v_rec.PartC, v_rec.PersC, V_REC.CODPART, V_REC.CODMIFIX, V_REC.MFSaft, V_REC.CODCMDINT1, vCod, RecID, v_rec.CONTD, v_rec.CONTC,
            v_rec.ICONTD, v_rec.ICONTC, V_REC.TIPLINIETVA, v_rec.VALOARE,
                  CASE when coalesce( V_REC.CODMIFIX, 0) &lt;&gt; 0 then V_REC.VALOARE * aCURS else 0 END ,
                  v_rec.OBS, v_rec.CODGEST, V_REC.CODFORMATIE, v_rec.AN, v_rec.LUNA, v_rec.INDEXLOCAL, V_REC.CODCENTRU, V_REC.CODAUTO, V_REC.AGENT, v_rec.codanalizanod );

          if fnc_GetValConstantaLucru('MifixExtins')::numeric = 1 and v_rec.codmifix &gt; 0 then
            for v_xxx in (select mfix1.codnirstoc
                          from mifix1 mfix1
                          where mfix1.codmifix = v_rec.codmifix and mfix1.anstart * 12 + mfix1.lunastart = aAn*12+aLuna
                         )
            loop
              insert into tmp_manevra_intr1(codintr1, codobiect, pretpredare)
              values(vCod, v_xxx.codnirstoc, v_rec.valoare * aCurs);
              exit;
            end loop;
          end if;
        else
          -- VERIFIC DACA NU S-AU RUPT LEGATURUILE CU CHELTAVANS;
          if (SELECT PKG_CATEGCONST_ESTECHELTAVANS.WME_RESULT FROM PKG_CATEGCONST_ESTECHELTAVANS(null, V_REC.CONTD)) +
             (SELECT PKG_CATEGCONST_ESTEVENITAVANS.WME_RESULT FROM PKG_CATEGCONST_ESTEVENITAVANS(null, V_REC.CONTD)) +
             (SELECT PKG_CATEGCONST_ESTECHELTAVANS.WME_RESULT FROM PKG_CATEGCONST_ESTECHELTAVANS(null, V_REC.CONTC)) +
             (SELECT PKG_CATEGCONST_ESTEVENITAVANS.WME_RESULT FROM PKG_CATEGCONST_ESTEVENITAVANS(null, V_REC.CONTC)) = 0
          then
            SELECT count(*) INTO NR FROM MASTERCHELTAVANS WHERE CODNC1 = V_REC.CODNC1;

            if NR &gt; 0 then
              for V_RECAV in (SELECT * FROM CHELTAVANS WHERE CODNC1 = V_REC.CODNC1 ) loop
                for V_RECJURN in (SELECT * FROM JURNAL WHERE CODDOC = V_RECAV.CODCHELTAVANS and TIPDOC in (52, 106) ) loop
                  UPDATE NCONTRUL
                  SET
                    RULAJCD      = RULAJCD      - V_RECJURN.VALOARE,
                    RULAJVCD     = RULAJVCD     - V_RECJURN.VALOAREV,
                    RULAJC_IFRS  = RULAJC_IFRS  - V_RECJURN.VALOARE_IFRS,
                    RULAJVC_IFRS = RULAJVC_IFRS - V_RECJURN.VALOAREV_IFRS,
                    RULAJC_GRUP  = RULAJC_GRUP  - V_RECJURN.VALOAREGRUP,
                    RULAJVC_GRUP = RULAJVC_GRUP - (SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT
                                                   FROM PKG_NC_VALOARE_GRUP_VALUTA(null,
                                                                                   coalesce( V_RECJURN.VALOAREGRUP, 0),
                                                                                   coalesce( V_RECJURN.VALOARE, 0),
                                                                                   coalesce( V_RECJURN.VALOAREV, 0)))
                  WHERE
                    CODCONT = V_RECJURN.CONTD
                    and AN = V_RECJURN.AN
                    and LUNA = V_RECJURN.LUNA ;

                  UPDATE NCONTRUL
                  SET
                    RULAJCC      = RULAJCC      - V_RECJURN.VALOARE,
                    RULAJVCC     = RULAJVCC     - V_RECJURN.VALOAREV,
                    RULAJC_IFRS  = RULAJC_IFRS  - V_RECJURN.VALOARE_IFRS,
                    RULAJVC_IFRS = RULAJVC_IFRS - V_RECJURN.VALOAREV_IFRS,
                    RULAJC_GRUP  = RULAJC_GRUP  - V_RECJURN.VALOAREGRUP,
                    RULAJVC_GRUP = RULAJVC_GRUP - (SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT
                                                   FROM PKG_NC_VALOARE_GRUP_VALUTA(null,
                                                                                   coalesce( V_RECJURN.VALOAREGRUP, 0),
                                                                                   coalesce( V_RECJURN.VALOARE, 0),
                                                                                   coalesce( V_RECJURN.VALOAREV, 0)))
                  WHERE
                    CODCONT  = V_RECJURN.CONTC
                    and AN   = V_RECJURN.AN
                    and LUNA = V_RECJURN.LUNA ;
                end loop;

                DELETE FROM JURNAL1 WHERE CODDOC = V_RECAV.CODCHELTAVANS and TIPDOC in (52, 106);
                DELETE FROM JURNAL  WHERE CODDOC = V_RECAV.CODCHELTAVANS and TIPDOC in (52, 106);

                DELETE FROM CHELTAVANS1 WHERE CODCHELTAVANS = V_RECAV.CODCHELTAVANS;
                DELETE FROM CHELTAVANS  WHERE CODCHELTAVANS = V_RECAV.CODCHELTAVANS;
              end loop;

              DELETE FROM MASTERCHELTAVANS WHERE CODNC1 = V_REC.CODNC1;
            end if;
          end if;

          UPDATE NC1
          SET
            PartD           = v_rec.PartD,
            PartC           = v_rec.PartC,
            PersD           = v_rec.PersD,
            PersC           = v_rec.PersC,
            CODPART         = V_REC.CODPART,
            CODMIFIX        = V_REC.CODMIFIX,
            MFSaft          = V_REC.MFSaft,
            CODCMDINT1      = V_REC.CODCMDINT1,
            RestIMBMF       = CASE when coalesce( V_REC.CODMIFIX, 0) &lt;&gt; 0 then v_rec.VALOARE * aCURS - (SELECT coalesce( sum(IL.CANT), 0)
                                                                                                        FROM IMBMIFIXLINK IL
                                                                                                            left join TRANSF1 T1 ON T1.CODTRANSF1 = IL.CODTRANSF1
                                                                                                            left join TRANSF  T  ON T.CODTRANSF   = T1.CODTRANSF
                                                                                                        WHERE IL.CODNC1 = v_Rec.CodNC1 and T.OPERAT = 1 and T.ANULAT = 0 )
                                   else 0
                              END,
              CODNC1        = v_rec.CODNC1,
              CODNC         = v_rec.CODNC,
              CONTD         = v_rec.CONTD,
              CONTC         = v_rec.CONTC,
              ICONTD        = v_rec.ICONTD,
              ICONTC        = v_rec.ICONTC,
              TIPLINIETVA   = v_rec.TIPLINIETVA,
              VALOARE       = v_rec.VALOARE,
              OBS           = v_rec.OBS,
              CODGEST       = v_rec.CODGEST,
              CODFORMATIE   = V_REC.CODFORMATIE,
              INDEXLOCAL    = v_rec.INDEXLOCAL,
              CODCENTRU     = V_REC.CODCENTRU,
              CODAUTO       = V_REC.CODAUTO,
              AGENT         = V_REC.AGENT,
              CODANALIZANOD = v_rec.codanalizanod
            where
              CODNC1 = v_rec.CODNC1 ;
          end if;
        end loop;

      DELETE FROM CMDAPROBARI A WHERE CODDOC = RECID AND TIPDOC = 35
      AND NOT EXISTS(SELECT COD FROM TMP_CMDAPROBARI WHERE COD = A.COD);

      FOR V_REC IN (SELECT * FROM TMP_CMDAPROBARI)
      LOOP
       IF V_REC.COD &lt; 0 THEN
          INSERT INTO CMDAPROBARI(COD,  CODDOC, TIPDOC, NIVEL, STARE, OBS, USERID)
          VALUES (NEXTVAL('SEQ_CMDAPROBARI_COD'), RECID, 35, V_REC.NIVEL, V_REC.STARE, V_REC.OBS, V_REC.USERID);
        ELSE
          UPDATE CMDAPROBARI
          SET
            NIVEL  = V_REC.NIVEL,
            STARE  = V_REC.STARE,
            USERID = V_REC.USERID,
            OBS    = V_REC.OBS
          WHERE
            COD = V_REC.COD;
        END IF;
      END LOOP;

        -- detail GENERAL
        for v_rec in (SELECT * FROM TMP_GENERAL ) loop
          if v_rec.CODGENERAL &lt; 0 then
            SELECT nextval('SEQ_GENERAL_CODGENERAL') INTO VCOD;

            UPDATE TMP_OBLIGPIF SET CODGENERAL = vCod WHERE CODGENERAL = v_rec.CODGENERAL ;

            INSERT INTO general (CODGENERAL, TIPDOC, CODDOC, MONEDA, CURS, SEMNIFICATIE, FARAREG )
            values (vCOD, v_rec.TIPDOC, v_rec.CODDOC, v_rec.MONEDA, v_rec.CURS, v_rec.SEMNIFICATIE, V_REC.FARAREG );
          else
            UPDATE general
            SET
              TIPDOC       = v_rec.TIPDOC,
              CODDOC       = v_rec.CODDOC,
              MONEDA       = v_rec.MONEDA,
              CURS         = v_rec.CURS,
              SEMNIFICATIE = v_rec.SEMNIFICATIE,
              FARAREG      = V_REC.FARAREG
            WHERE
              CODGENERAL = v_rec.CODGENERAL ;
          end if;
        end loop;

        -- detail OBLIGPIF
        for v_rec in (SELECT * FROM TMP_OBLIGPIF ) loop
          if v_rec.CODOBLIGPIF &gt; 0 then
            UPDATE OBLIGPIF
            SET
              CODGENERAL = v_rec.CODGENERAL,
              TERMEN     = v_rec.TERMEN,
              VALOARE    = v_rec.VALOARE,
              REST       = (
                            case
                              when v_rec.VALOARE &gt; 0 then v_rec.VALOARE - coalesce( ( select sum(VALOARE) from STINGERE where CODSTINSPIF = v_rec.CODOBLIGPIF ), 0)
                              when v_rec.VALOARE &lt; 0 then v_rec.VALOARE + coalesce( ( select sum(VALOARE) from STINGERE where CODSTINSPIF = v_rec.CODOBLIGPIF ), 0) end ) ,
              CODPART            = v_rec.CODPART,
              ICONT              = v_rec.ICONT,
              TIPPLATA           = v_rec.TIPPLATA,
              MAJORARI           = v_rec.MAJORARI,
              SEMNIFICATIE       = v_rec.SEMNIFICATIE,
              TIP                = v_rec.TIP,
              CONTBANKTRANZACTIE = v_rec.CONTBANKTRANZACTIE,
              CODOBLIGASOCIAT    = v_rec.CODOBLIGASOCIAT,
              CODCENTRU          = v_rec.CODCENTRU,
              CODANALIZANOD      = v_rec.codanalizanod
            where
              CODOBLIGPIF = v_rec.CODOBLIGPIF ;
          else
            SELECT nextval('SEQ_OBLIGPIF_CODOBLIGPIF') INTO vCOD;

            INSERT INTO OBLIGPIF (CODOBLIGPIF, CODGENERAL, TERMEN, VALOARE, REST, CODPART, ICONT, TIPPLATA, MAJORARI, SEMNIFICATIE,
                                  TIP, CONTBANKTRANZACTIE, CODOBLIGASOCIAT, CODCENTRU, CODANALIZANOD )
            values (vCOD, v_rec.CODGENERAL, v_rec.TERMEN, v_rec.VALOARE, v_rec.VALOARE, v_rec.CODPART, v_rec.ICONT, v_rec.TIPPLATA, v_rec.MAJORARI, v_rec.SEMNIFICATIE,
                    v_rec.TIP, v_rec.CONTBANKTRANZACTIE, v_rec.CODOBLIGASOCIAT, V_REC.CODCENTRU, V_REC.CODANALIZANOD );
          end if;
        end loop;

        -- detail JURNAlL1
        DELETE FROM JURNAl1 WHERE TIPDOC = 35 and CODDOC = RECID and CODJURNAL1 not in (SELECT CODJURNAL1 FROM TMP_JURNAl1 );

        for V_REC in (SELECT * FROM TMP_JURNAL1 ) loop
          if V_REC.CODJURNAL1 &gt; 0 then
            UPDATE JURNAL1
            SET
              CODDOC        = V_REC.CODDOC,
              TIPDOC        = V_REC.TIPDOC,
              INDEXLOCAL    = V_REC.INDEXLOCAL,
              CODBAZAD      = V_REC.CODBAZAD,
              ICONTBAZAD    = V_REC.ICONTBAZAD,
              TIPBAZAD      = V_REC.TIPBAZAD,
              CODBAZAC      = V_REC.CODBAZAC,
              ICONTBAZAC    = V_REC.ICONTBAZAC,
              TIPBAZAC      = V_REC.TIPBAZAC,
              CODDESCRD     = V_REC.CODDESCRD,
              ICONTD        = V_REC.ICONTD,
              TIPCONTD      = V_REC.TIPCONTD,
              ANALITICCONTD = V_REC.ANALITICCONTD,
              CODDESCRC     = V_REC.CODDESCRC,
              ICONTC        = V_REC.ICONTC,
              TIPCONTC      = V_REC.TIPCONTC,
              ANALITICCONTC = V_REC.ANALITICCONTC,
              GEST          = V_REC.GEST,
              VALOARE       = V_REC.VALOARE,
              VALOAREV      = V_REC.VALOAREV,
              OBS           = V_REC.OBS,
              AN            = V_REC.AN,
              LUNA          = V_REC.LUNA,
              DIRTY         = V_REC.DIRTY,
              SUBUNITATEA   = V_REC.SUBUNITATEA,
              CODCENTRU     = v_rec.CODCENTRU,
              CODANALIZANOD = v_rec.CODANALIZANOD,
              DATADOC       = V_REC.DATADOC,
              document      = V_REC.DOCUMENT,
              VALOARE_IFRS  = V_REC.VALOARE_IFRS,
              VALOAREV_IFRS = V_REC.VALOAREV_IFRS,
              VALOAREGRUP   = V_REC.VALOAREGRUP
            WHERE
              CODJURNAL1 = V_REC.CODJURNAl1 ;
          else
            INSERT INTO JURNAL1 (CODJURNAL1, CODDOC, TIPDOC, INDEXLOCAL, CODBAZAD, ICONTBAZAD, TIPBAZAD, CODDESCRD, ICONTD, TIPCONTD, ANALITICCONTD,
                                 CODBAZAC, ICONTBAZAC, TIPBAZAC, CODDESCRC, ICONTC, TIPCONTC, ANALITICCONTC, GEST, VALOARE, VALOAREV, OBS, AN, LUNA, DIRTY,
                                 SUBUNITATEA, CODCENTRU, CODANALIZANOD, DATADOC, document, VALOARE_IFRS, VALOAREV_IFRS, VALOAREGRUP )
            values (nextval('SEQ_JURNAL1_CODJURNAL1'), RECID, V_REC.TIPDOC, V_REC.INDEXLOCAL, V_REC.CODBAZAD, V_REC.ICONTBAZAD, V_REC.TIPBAZAD, V_REC.CODDESCRD,
                    V_REC.ICONTD, V_REC.TIPCONTD, V_REC.ANALITICCONTD, V_REC.CODBAZAC, V_REC.ICONTBAZAC, V_REC.TIPBAZAC, V_REC.CODDESCRC, V_REC.ICONTC, V_REC.TIPCONTC,
                    V_REC.ANALITICCONTC, V_REC.GEST, V_REC.VALOARE, V_REC.VALOAREV, V_REC.OBS, V_REC.AN, V_REC.LUNA, V_REC.DIRTY, V_REC.SUBUNITATEA, v_rec.CODCENTRU,
                    v_rec.CODANALIZANOD, V_REC.DATADOC, V_REC.DOCUMENT, V_REC.VALOARE_IFRS, V_REC.VALOAREV_IFRS, V_REC.VALOAREGRUP );
          end if;
        end loop;

        -- detail JURNAL
        DELETE FROM JURNAL WHERE TIPDOC = 35 and CODDOC = RECID and CODJURNAL not in (SELECT CODJURNAL FROM TMP_JURNAl );

        for V_REC in (SELECT * FROM TMP_JURNAL ) loop
          if V_REC.CODJURNAL &gt; 0 then
            UPDATE JURNAL
            SET
              CODDOC        = V_REC.CODDOC,
              TIPDOC        = V_REC.TIPDOC,
              INDEXLOCAL    = V_REC.INDEXLOCAL,
              CONTD         = V_REC.CONTD,
              CONTC         = V_REC.CONTC,
              GEST          = V_REC.GEST,
              VALOARE       = V_REC.VALOARE,
              VALOAREV      = V_REC.VALOAREV,
              OBS           = V_REC.OBS,
              AN            = V_REC.AN,
              LUNA          = V_REC.LUNA,
              SUBUNITATEA   = V_REC.SUBUNITATEA,
              CODCENTRU     = v_rec.CODCENTRU,
              CODANALIZANOD = v_rec.CODANALIZANOD,
              DATADOC       = V_REC.DATADOC,
              document      = V_REC.DOCUMENT,
              VALOARE_IFRS  = V_REC.VALOARE_IFRS,
              VALOAREV_IFRS = V_REC.VALOAREV_IFRS,
              VALOAREGRUP   = V_REC.VALOAREGRUP
            WHERE
              CODJURNAL = V_REC.CODJURNAl ;
          else
            INSERT INTO JURNAL (CODJURNAL, CODDOC, TIPDOC, INDEXLOCAL, CONTD, CONTC, GEST, VALOARE, VALOAREV, OBS, AN, LUNA, SUBUNITATEA, CODCENTRU,
                                CODANALIZANOD, DATADOC, document, VALOARE_IFRS, VALOAREV_IFRS, VALOAREGRUP )
            values (nextval('SEQ_JURNAL_CODJURNAL'), RECID, V_REC.TIPDOC, V_REC.INDEXLOCAL, V_REC.CONTD, V_REC.CONTC, V_REC.GEST, V_REC.VALOARE, V_REC.VALOAREV,
                    V_REC.OBS, V_REC.AN, V_REC.LUNA, V_REC.SUBUNITATEA, v_rec.CODCENTRU, v_rec.CODANALIZANOD, V_REC.DATADOC, V_REC.DOCUMENT,
                    V_REC.VALOARE_IFRS, V_REC.VALOAREV_IFRS, V_REC.VALOAREGRUP );
          end if;
        end loop;

      ELSE   --INSERT
        -- Master NC
        SELECT nextval('SEQ_NC_CODNC') INTO RECId;
        PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('NC', RecId);

        if (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT
            FROM PKG_USERFIRME_ValidPostLog(null, to_number(current_setting('PKG_GLOBALS.USERID', true), '999999999999999999'), current_setting('PKG_NC.CT_MONITOR', true)))
        then
          perform pkg_userfirme_postlogcucommit( 'NC', current_setting('PKG_GLOBALS.USERNAME', true), 'A', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true),
                                                 aSubunitatea, aDataDoc, aDoc, '-',
                                                 (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(null, null)));
        end if;

        INSERT INTO NC (Part, JurnalTVA, TIPTRANZ, TIPTVA, Valoare, Moneda, Curs, Obs, CodNC, NrDoc, DataDoc, An, Luna, SUBUNITATEA, userid,
                        datacreare, sablon, CARNETDOC, CodAnaliza, Aprobat)
        SELECT Part, JurnalTVA, TIPTRANZ, TIPTVA, Valoare, Moneda, Curs, Obs, RecId, NrDoc, DataDoc, An, Luna, SUBUNITATEA,
               to_number(current_setting('PKG_GLOBALS.USERID', true), '999999999999999999'), current_timestamp, sablon, CARNETDOC, CodAnaliza, Aprobat
        FROM TMP_NC;

        -- Detail
        for v_rec in (SELECT * FROM TMP_NC1 order BY INDEXLOCAL ) loop
          SELECT nextval('SEQ_NC1_CODNC1') INTO vCod;

          UPDATE TMP_GENERAL SET CODDOC     = vCod WHERE CODDOC     = v_rec.CODNC1 ;
          UPDATE TMP_JURNAL1 SET INDEXLOCAL = vCod WHERE INDEXLOCAL = v_rec.CODNC1 ;
          UPDATE TMP_JURNAL  SET INDEXLOCAL = vCod WHERE INDEXLOCAL = v_rec.CODNC1 ;

          PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('NC1', vCod, V_REC.CODNC1);

           INSERT INTO NC1 (
        INDEXLOCAL, PartD, PersD, PartC, PersC, CODPART, CODMIFIX, MFSaft, CODCMDINT1, CODNC1, CODNC, CONTD, CONTC, ICONTD, ICONTC, TIPLINIETVA,
        VALOARE, RESTIMBMF, OBS, CODGEST, CODFORMATIE, AN, LUNA, CODCENTRU, CODAUTO, AGENT, CODANALIZANOD )
        VALUES (
          v_rec.INDEXLOCAL, v_rec.PartD, v_rec.PersD, v_rec.PartC, v_rec.PersC,V_REC.CODPART, V_REC.CODMIFIX, V_REC.MFSaft, V_REC.CODCMDINT1, vCod, RecID, v_rec.CONTD, v_rec.CONTC, V_REC.ICONTD, V_REC.ICONTC, V_REC.TIPLINIETVA,
          v_rec.VALOARE,
                  CASE when coalesce( V_REC.CODMIFIX, 0) &lt;&gt; 0 then V_REC.VALOARE * aCURS else 0 END ,
                  v_rec.OBS, v_rec.CODGEST, V_REC.CODFORMATIE, v_rec.AN, v_rec.LUNA, V_REC.CODCENTRU, V_REC.CODAUTO, V_REC.AGENT, v_Rec.Codanalizanod );

          if fnc_GetValConstantaLucru('MifixExtins')::numeric = 1 and v_rec.codmifix &gt; 0 then
            for v_xxx in (select mfix1.codnirstoc
                          from mifix1 mfix1
                          where mfix1.codmifix = v_rec.codmifix and mfix1.anstart * 12 + mfix1.lunastart = aAn*12+aLuna
                         )
            loop
              insert into tmp_manevra_intr1(codintr1, codobiect, pretpredare)
              values(vCod, v_xxx.codnirstoc, v_rec.valoare * aCurs);
              exit;
            end loop;
          end if;
        end loop;

       INSERT INTO CMDAPROBARI(COD, CODDOC, TIPDOC, NIVEL, STARE, OBS, USERID)
       SELECT NEXTVAL('SEQ_CMDAPROBARI_COD'), RECID, 35, NIVEL, STARE, OBS, USERID FROM TMP_CMDAPROBARI;

        for v_rec in (SELECT * FROM TMP_GENERAL ) loop
          SELECT nextval('SEQ_GENERAL_CODGENERAL') INTO VCOD;

          UPDATE TMP_OBLIGPIF SET CODGENERAL = vCod WHERE CODGENERAL = v_rec.CODGENERAL ;

          INSERT INTO general ( CODGENERAL, TIPDOC, CODDOC, MONEDA, CURS, SEMNIFICATIE, FARAREG )
          values ( vCOD, v_rec.TIPDOC, v_rec.CODDOC, v_rec.MONEDA, v_rec.CURS, v_rec.SEMNIFICATIE, V_REC.FARAREG );
        end loop;

        for v_rec in (SELECT * FROM TMP_OBLIGPIF ) loop
          INSERT INTO OBLIGPIF (CODOBLIGPIF, CODGENERAL, TERMEN, VALOARE, REST, CODPART, ICONT, TIPPLATA, MAJORARI, SEMNIFICATIE, TIP, CONTBANKTRANZACTIE,
                            CODOBLIGASOCIAT, CODCENTRU, CODANALIZANOD )
          values (nextval('SEQ_OBLIGPIF_CODOBLIGPIF'), v_rec.CODGENERAL, v_rec.TERMEN, v_rec.VALOARE, v_rec.VALOARE, v_rec.CODPART, v_rec.ICONT, v_rec.TIPPLATA, v_rec.MAJORARI,
                  v_rec.SEMNIFICATIE, v_rec.TIP, v_rec.CONTBANKTRANZACTIE, v_rec.CODOBLIGASOCIAT, V_REC.CODCENTRU, V_REC.CODANALIZANOD );
        end loop;

        INSERT INTO JURNAL1 (CODJURNAL1, CODDOC, TIPDOC, INDEXLOCAL, CODBAZAD, ICONTBAZAD, TIPBAZAD, CODDESCRD, ICONTD, TIPCONTD, ANALITICCONTD,
                             CODBAZAC, ICONTBAZAC, TIPBAZAC, CODDESCRC, ICONTC, TIPCONTC, ANALITICCONTC, GEST, VALOARE, VALOAREV, OBS, AN, LUNA, DIRTY, SUBUNITATEA,
                             CODCENTRU, CODANALIZANOD, DATADOC, document, VALOARE_IFRS, VALOAREV_IFRS, VALOAREGRUP )
        SELECT nextval('SEQ_JURNAL1_CODJURNAL1'), RECID, TIPDOC, INDEXLOCAL, CODBAZAD, ICONTBAZAD, TIPBAZAD, CODDESCRD, ICONTD, TIPCONTD, ANALITICCONTD,
               CODBAZAC, ICONTBAZAC, TIPBAZAC, CODDESCRC, ICONTC, TIPCONTC, ANALITICCONTC, GEST, VALOARE, VALOAREV, OBS, AN, LUNA, DIRTY, SUBUNITATEA,
               CODCENTRU, CODANALIZANOD, DATADOC, document, VALOARE_IFRS, VALOAREV_IFRS, VALOAREGRUP
        FROM TMP_JURNAL1;

        INSERT INTO JURNAL (CODJURNAL, CODDOC, TIPDOC, INDEXLOCAL, CONTD, CONTC, GEST, VALOARE, VALOAREV, OBS, AN, LUNA, SUBUNITATEA, CODCENTRU, CODANALIZANOD,
                            DATADOC, document, VALOARE_IFRS, VALOAREV_IFRS, VALOAREGRUP )
        SELECT nextval('SEQ_JURNAL_CODJURNAL'), RECID, TIPDOC, INDEXLOCAL, CONTD, CONTC, GEST, VALOARE, VALOAREV, OBS, AN, LUNA, SUBUNITATEA, CODCENTRU, CODANALIZANOD,
               DATADOC, document, VALOARE_IFRS, VALOAREV_IFRS, VALOAREGRUP
        FROM TMP_JURNAL;
      END IF;

      -- ACTUALIZARE RULAJE CONTURI
      for V_REC in (SELECT * FROM TMP_RULAJ ) loop
        SELECT count(*) INTO NR
        FROM NCONTRUL
        WHERE
          CODCONT  = V_REC.CODCONT
          and AN   = to_number(current_setting('PKG_GLOBALS.ANLUCRU'  , true), '999999999999999999')
          and LUNA = to_number(current_setting('PKG_GLOBALS.LUNALUCRU', true), '999999999999999999');

        if NR = 0 then
          INSERT INTO NCONTRUL (CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC,
                                RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS,
                                RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP,
                                AN, LUNA )
          values (nextval('SEQ_NCONTRUL_CODCONTRUL'), V_REC.CODCONT, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                  to_number(current_setting('PKG_GLOBALS.ANLUCRU'  , true), '999999999999999999'),
                  to_number(current_setting('PKG_GLOBALS.LUNALUCRU', true), '999999999999999999') );
        end if;

        UPDATE NCONTRUL
        SET
          RULAJCD      = coalesce( RULAJCD     , 0) + (CASE when V_REC.TIP = 'D' then V_REC.VALOARE  else 0 end ) ,
          RULAJCC      = coalesce( RULAJCC     , 0) + (CASE when V_REC.TIP = 'C' then V_REC.VALOARE  else 0 end ) ,
          RULAJVCD     = coalesce( RULAJVCD    , 0) + (CASE when V_REC.TIP = 'D' then V_REC.VALOAREV else 0 end ) ,
          RULAJVCC     = coalesce( RULAJVCC    , 0) + (CASE when V_REC.TIP = 'C' then V_REC.VALOAREV else 0 end ) ,
          RULAJC_IFRS  = coalesce( RULAJC_IFRS , 0) + (CASE when V_REC.TIP = 'C' then -coalesce( V_REC.VALOARE_IFRS , 0) else coalesce( V_REC.VALOARE_IFRS , 0) end ) ,
          RULAJVC_IFRS = coalesce( RULAJVC_IFRS, 0) + (CASE when V_REC.TIP = 'C' then -coalesce( V_REC.VALOAREV_IFRS, 0) else coalesce( V_REC.VALOAREV_IFRS, 0) end ) ,
          RULAJC_GRUP  = coalesce( RULAJC_GRUP , 0) + (CASE when V_REC.TIP = 'C' then -coalesce( V_REC.VALOARE_GRUP , 0) else coalesce( V_REC.VALOARE_GRUP , 0) end ) ,
          RULAJVC_GRUP = coalesce( RULAJVC_GRUP, 0) + (CASE when V_REC.TIP = 'C' then -(SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(null, coalesce( V_REC.VALOARE_GRUP, 0), coalesce( V_REC.VALOARE, 0), coalesce( V_REC.VALOAREV, 0)))
                                                            else (SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(null, coalesce( V_REC.VALOARE_GRUP, 0), coalesce( V_REC.VALOARE, 0), coalesce( V_REC.VALOAREV, 0))) end )
        WHERE
          CODCONT  = V_REC.CODCONT
          and AN   = to_number(current_setting('PKG_GLOBALS.ANLUCRU'  , true), '999999999999999999')
          and LUNA = to_number(current_setting('PKG_GLOBALS.LUNALUCRU', true), '999999999999999999') ;

        if coalesce( V_REC.SUBUNITATEA, 0) &lt;&gt; 0 then
          for V_REC_SUB in (SELECT * FROM NCONTRUL
                            WHERE
                              CODCONT  = V_REC.CODCONT
                              and AN   = to_number(current_setting('PKG_GLOBALS.ANLUCRU'  , true), '999999999999999999')
                              and LUNA = to_number(current_setting('PKG_GLOBALS.LUNALUCRU', true), '999999999999999999')
                           )
          loop
            SELECT count(*) INTO NR FROM NCONTRULSUB WHERE CODCONTRUL = V_REC_SUB.CODCONTRUL and SUBUNITATEA = V_REC.SUBUNITATEA;

            if NR = 0 then
              INSERT INTO NCONTRULSUB (CODCONTRULSUB, CODCONTRUL, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC,
                                       RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, SUBUNITATEA )
              values (nextval('SEQ_NCONTRULSUB_CODRULSUB'), V_REC_SUB.CODCONTRUL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, V_REC.SUBUNITATEA );
            end if;

            UPDATE NCONTRULSUB
            SET
              RULAJCD      = coalesce( RULAJCD     , 0) + (CASE when V_REC.TIP = 'D' then V_REC.VALOARE  else 0 end ) ,
              RULAJCC      = coalesce( RULAJCC     , 0) + (CASE when V_REC.TIP = 'C' then V_REC.VALOARE  else 0 end ) ,
              RULAJVCD     = coalesce( RULAJVCD    , 0) + (CASE when V_REC.TIP = 'D' then V_REC.VALOAREV else 0 end ) ,
              RULAJVCC     = coalesce( RULAJVCC    , 0) + (CASE when V_REC.TIP = 'C' then V_REC.VALOAREV else 0 end ) ,
              RULAJC_IFRS  = coalesce( RULAJC_IFRS , 0) + (CASE when V_REC.TIP = 'C' then -coalesce( V_REC.VALOARE_IFRS , 0) else coalesce( V_REC.VALOARE_IFRS , 0) end ) ,
              RULAJVC_IFRS = coalesce( RULAJVC_IFRS, 0) + (CASE when V_REC.TIP = 'C' then -coalesce( V_REC.VALOAREV_IFRS, 0) else coalesce( V_REC.VALOAREV_IFRS, 0) end ) ,
              RULAJC_GRUP  = coalesce( RULAJC_GRUP , 0) + (CASE when V_REC.TIP = 'C' then -coalesce( V_REC.VALOARE_GRUP , 0) else coalesce( V_REC.VALOARE_GRUP , 0) end ) ,
              RULAJVC_GRUP = coalesce( RULAJVC_GRUP, 0) + (CASE when V_REC.TIP = 'C' then -(SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(null, coalesce( V_REC.VALOARE_GRUP, 0), coalesce( V_REC.VALOARE, 0), coalesce( V_REC.VALOAREV, 0)))
                                                                else (SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(null, coalesce( V_REC.VALOARE_GRUP, 0), coalesce( V_REC.VALOARE, 0), coalesce( V_REC.VALOAREV, 0))) end )
            WHERE
              CODCONTRUL = V_REC_SUB.CODCONTRUL
              and SUBUNITATEA = V_REC.SUBUNITATEA ;
          end loop;
        end if;
      end loop;

      if coalesce( aCARNETDOC, 0) &lt;&gt; 0 then
        perform PKG_CARNETEDOC_SOLVENUMARDOC( ACARNETDOC, (ANRDOC)::character varying);
      end if;

      SELECT count(*) INTO NR FROM TMP_OREPONTAJ;
      if NR &gt; 0 then
        DELETE FROM OREPONTAJ WHERE AN * 12 + Luna = (SELECT PKG_GLOBALS_ANLUNALUCRU.WME_RESULT FROM PKG_GLOBALS_ANLUNALUCRU(null, null));

        INSERT INTO OREPONTAJ ( CODFORMATIE, CODPERS, ORE, SALAR, AN, LUNA )
        SELECT CODFORMATIE, CodPers, Ore, Salar, to_number(current_setting('PKG_GLOBALS.AnLucru', true), '999999999999999999'), to_number(current_setting('PKG_GLOBALS.LunaLucru', true), '999999999999999999')
        FROM Tmp_Orepontaj;
      end if;

      perform PKG_GLOBALS_MarkDirtyJurnal();

      -- LEGATURI CU CHELTAVANS
      for V_REC in (SELECT * FROM TMP_NC1 WHERE CODNC1 &gt; 0 ) loop
        begin
          SELECT count(*) INTO NRCHELT FROM CHELTAVANS WHERE CODNC1 = V_REC.CODNC1;
        exception
          when others then NRCHELT := 0;
        end;

        if NRCHELT &gt; 0 then
          for V_CHELT1 in (SELECT CA1.CODCHELTAVANS1, CA1.CODCHELTAVANS
                           FROM CHELTAVANS CA, CHELTAVANS1 CA1
                           WHERE CA.CODNC1 = V_REC.CODNC1 and CA1.CODCHELTAVANS = CA.CODCHELTAVANS and VALOARE &lt;&gt; V_REC.VALOARE * aCURS
                          )
          loop
            UPDATE CHELTAVANS1 SET VALOARE = V_REC.VALOARE * aCURS WHERE CODCHELTAVANS1 = V_CHELT1.CODCHELTAVANS1 ;
            UPDATE JURNAL1     SET DIRTY = 1 WHERE CODDOC = V_CHELT1.CODCHELTAVANS and TIPDOC in (52, 106) ;
          end loop;
        end if;
      end loop;

      PERFORM PKG_CFGTABLES_EXT_POSTRECORDS(35, operation);
      perform NotifyModif( OPERATION, RECID, 'NC');

      if fnc_GetValConstantaLucru('MifixExtins')::numeric  = 1 then
        begin
          select count(*) into aCount from tmp_manevra_intr1;
        exception when others then
          aCount := 0;
        end;

        if aCount &gt; 0 then PERFORM pkg_nc_GenereazaModificareDePretMifix(aDataDoc, aAn, aLuna, aSubunitatea); end if;
      end if;
    exception
       when others then begin
        raise;
    end;
  end;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nc_sp_postrecords_from_import</obj_name>
  <obj_hashval>1f9a4a0ab165cd492ffe70cded50655e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nc_sp_postrecords_from_import(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  vCod  numeric;
  NR    numeric := 0;
BEGIN
  --Florin 12.11.2025 - sinc. Oracle
  --Florin 07.12.2022 - sinc. Oracle
  SELECT NEXTVAL('SEQ_NC_CODNC') INTO RECId;

  INSERT INTO NC (
   CodNC, NrDoc, DataDoc, Part, JurnalTVA, TIPTRANZ, TIPTVA, Valoare, Moneda, Curs, Obs, An, Luna, Subunitatea,
   UserId, DataCreare, Sablon, CarnetDoc, CodAnaliza)
  SELECT
    RecId ,NrDoc, DataDoc, Part, JurnalTVA, TIPTRANZ, TIPTVA, Valoare, Moneda, Curs, Obs, An, Luna, Subunitatea,
    TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true)), CURRENT_TIMESTAMP, Sablon, CarnetDoc, CodAnaliza
  FROM TMP_NC;

  UPDATE TMP_NC1 SET (An, Luna) = (SELECT N.An, N.Luna FROM TMP_NC N) WHERE An IS NULL OR Luna IS NULL;

  FOR v_rec IN (SELECT * FROM TMP_NC1 ORDER BY INDEXLOCAL) LOOP
    SELECT NEXTVAL('SEQ_NC1_CODNC1') INTO vCod;

    UPDATE TMP_GENERAL SET CODDOC = vCod WHERE CODDOC = v_rec.CODNC1;

    INSERT INTO NC1 (
      INDEXLOCAL, PartD, PersD, PartC, PersC, CODPART, CODMIFIX, MFSaft, CODCMDINT1, CODNC1, CODNC, CONTD, CONTC, ICONTD, ICONTC, TIPLINIETVA,
      VALOARE, OBS, CODGEST, CODFORMATIE, AN, LUNA )
    VALUES (
      v_rec.INDEXLOCAL, v_rec.PartD, v_rec.PersD, v_rec.PartC, v_rec.PersC,V_REC.CODPART, V_REC.CODMIFIX, V_REC.MFSaft, V_REC.CODCMDINT1, vCod, RecID, v_rec.CONTD, v_rec.CONTC, V_REC.ICONTD, V_REC.ICONTC, V_REC.TIPLINIETVA,
      v_rec.VALOARE, v_rec.OBS, v_rec.CODGEST, V_REC.CODFORMATIE, v_rec.AN, v_rec.LUNA);
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_GENERAL) LOOP
    SELECT NEXTVAL('SEQ_GENERAL_CODGENERAL') INTO VCOD;

    UPDATE TMP_OBLIGPIF SET CODGENERAL = vCod WHERE CODGENERAL = v_rec.CODGENERAL;

    INSERT INTO GENERAL(CODGENERAL, TIPDOC, CODDOC, MONEDA, CURS, SEMNIFICATIE)
    VALUES(vCOD, V_REC.TIPDOC, V_REC.CODDOC, V_REC.MONEDA, V_REC.CURS, V_REC.SEMNIFICATIE);
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_OBLIGPIF) LOOP
    IF  V_REC.CODOBLIGPIF &lt; 0 THEN
      SELECT NEXTVAL('SEQ_OBLIGPIF_CODOBLIGPIF') INTO vCOD;
    ELSE
      VCOD := V_REC.CODOBLIGPIF;
    END IF;

    INSERT INTO OBLIGPIF (CODOBLIGPIF, CODGENERAL, TERMEN, VALOARE, REST, CODPART, ICONT, TIPPLATA, MAJORARI, SEMNIFICATIE, TIP, CONTBANKTRANZACTIE, CODOBLIGASOCIAT)
    VALUES(VCOD, v_rec.CODGENERAL, v_rec.TERMEN, v_rec.VALOARE, v_rec.VALOARE, v_rec.CODPART, v_rec.ICONT, v_rec.TIPPLATA, v_rec.MAJORARI, v_rec.SEMNIFICATIE, v_rec.TIP, v_rec.CONTBANKTRANZACTIE, v_rec.CODOBLIGASOCIAT);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nc_valoare_grup_valuta</obj_name>
  <obj_hashval>f9689d24fe8bed3b1c051717272da925</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nc_valoare_grup_valuta(INOUT wme_result numeric, INOUT avalgrup numeric, INOUT avaloare numeric, INOUT avaloare_valuta numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCURS double precision;
begin
  IF  COALESCE( aVALOARE_VALUTA, 0) = 0 THEN
    WME_Result :=  0;
    RETURN;
  ELSE
    aCURS := COALESCE( aVALOARE, 0) / aVALOARE_VALUTA;

    IF  aCURS = 0 THEN
      aCURS := 1;
    END IF;

    WME_Result :=  COALESCE( aVALGRUP, 0) / aCURS;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_necesar_delete</obj_name>
  <obj_hashval>6cd26d0a8abcf69aef29418ad4208c4d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_necesar_delete(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  ACARNETDOC numeric;
  ANRDOC     numeric;
begin
  BEGIN
    SELECT COALESCE( CARNETDOC, 0), NRDOC INTO ACARNETDOC, ANRDOC FROM NECESAR WHERE CODNECESAR = RECID;
  EXCEPTION WHEN others THEN
    acarnetdoc := 0;
    anrdoc := 0;
  END;

  DELETE FROM NECESAROBJ WHERE CODNECESAR = RECID;
  DELETE FROM NECESARDOC WHERE CODNECESAR = RECID;
  DELETE FROM NECESARCMD WHERE CODNECESAR = RECID;
  DELETE FROM NECESAR    WHERE CODNECESAR = RECID;

  IF  aCARNETDOC &lt;&gt; 0 THEN
    PERFORM PKG_CARNETEDOC_RELEASENUMARDOC( aCARNETDOC, aNRDOC);
    PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE( aCARNETDOC);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_necesar_postnecesar</obj_name>
  <obj_hashval>dda701113a9ac757feaa693196102019</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_necesar_postnecesar(INOUT recidold numeric, INOUT acarnetdoc numeric, INOUT anrdoc numeric, INOUT aseriadoc character varying, INOUT adatadoc character varying, INOUT aobs character varying, INOUT asaptamana numeric, INOUT recid numeric, INOUT atipnecesar numeric, INOUT asupliment numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 22.05.2023 - corectie PKG_CARNETEDOC_SOLVENUMARDOC
  --INSERT INTO x(test) VALUES(asupliment);

  IF  RecIdOld = 0 THEN
    SELECT NEXTVAL('SEQ_NECESAR_CODNECESAR') INTO RecId;

    INSERT INTO necesar(codnecesar, carnetdoc, nrdoc, seriadoc, datadoc, obs, Subunitatea, Saptamana, TipNecesar, Supliment, An)
    VALUES(RecId, aCarnetDoc, aNrDoc, aSeriaDoc, to_date( aDataDoc, 'dd.mm.yyyy'), aObs, (SELECT pkg_globals_GETSUBUNITATE_DOC.WME_RESULT FROM pkg_globals_GETSUBUNITATE_DOC(NULL,NULL)), aSaptamana, aTipNecesar, aSupliment, (SELECT pkg_globals_GetANLUCRU.WME_RESULT FROM pkg_globals_GetANLUCRU(NULL,NULL)));
  ELSE
    RecId := RecIdOld;

    UPDATE necesar
    SET
    carnetdoc  = aCarnetDoc,
    nrdoc      = aNrDoc,
    seriadoc   = aSeriaDoc,
    datadoc    = to_date( aDataDoc, 'dd.mm.yyyy'),
    obs        = aObs,
    Saptamana  = aSaptamana,
    TipNecesar = aTipNecesar,
    Supliment  = aSupliment
    WHERE
     codnecesar = RecId;
  END IF;

  DELETE FROM necesardoc ndoc
  WHERE ndoc.codnecesar = RecId and  NOT  EXISTS (SELECT tmp.valoare FROM tmp_manevra_liste tmp WHERE tmp.filtru = 'CODPLANIFPROD' and  tmp.valoare = ndoc.codplanifprod);

  INSERT INTO necesardoc(codnecesar, codplanifprod)
  SELECT RecId, tmp.valoare
  FROM tmp_manevra_liste tmp
  WHERE tmp.filtru = 'CODPLANIFPROD' and  NOT  EXISTS (SELECT ndoc.codplanifprod FROM necesardoc ndoc WHERE ndoc.Codnecesar = RecId and  tmp.valoare = ndoc.codplanifprod);

  IF  RecIdOld = 0 THEN
    IF  ACARNETDOC &lt;&gt; 0 THEN
      PERFORM PKG_CARNETEDOC_SOLVENUMARDOC( ACARNETDOC, ANRDOC::varchar);
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_necesar_updatecmdext</obj_name>
  <obj_hashval>8a227d9f323cf07dcfd1ad1cb3fd8484</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_necesar_updatecmdext(acodnecesar numeric, afield character varying, acodcomanda numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Val    varchar;
  Aux    varchar;
  aCount numeric;
begin
  IF  (SELECT pkg_list_struct_TmpExists.WME_RESULT FROM pkg_list_struct_TmpExists(NULL, 'COMANDF')) = 1 THEN
    Val := 'Necesar : ';

    BEGIN
      SELECT nrdoc || '/' || to_char( datadoc, 'dd.mm.yyyy') INTO Aux FROM necesar WHERE codnecesar = aCodNecesar;
    EXCEPTION WHEN others THEN
      Aux := '';
    END;

    Val := Val || Aux;
    Val := Val || ' Detalieri : ';

    BEGIN
      SELECT string_agg( p.nrdoc || '/' || to_char( p.datadoc, 'dd.mm.yyyy'),',')
      INTO Aux
      FROM necesardoc n INNER JOIN planifprod p ON  p.codplanifprod = n.codplanifprod
      WHERE n.codnecesar = aCodnecesar;
    EXCEPTION WHEN others THEN
      Aux := '';
    END;

    Val := Val || Aux;

    BEGIN
      EXECUTE 'select count(*) from comandf where codcomanda = ' || acodcomanda into aCount;
    EXCEPTION WHEN others THEN
      aCount := 0;
    END;

    IF  aCount &gt; 0 THEN
      BEGIN
        Aux := 'update comandf set ' || aField || ' = ''' || Val || ''' where codcomanda = ' || aCodComanda;
        EXECUTE Aux;
      EXCEPTION WHEN others THEN
        Aux := '';
      END;
    ELSE
      BEGIN
        Aux := 'insert into comandf(CodComanda,' || aField || ') values(' || aCodComanda || ',''' || Val || ''')';
        EXECUTE Aux;
      EXCEPTION WHEN others THEN
        Aux := '';
      END;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nimob_sp_gotorecord</obj_name>
  <obj_hashval>02e48dd9fdc75586fb1b06602d4f4a13</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nimob_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NIMOB(codnimob, denumire, datastart, datastop)
  SELECT codnimob, denumire, datastart, datastop FROM NIMOB WHERE codnimob = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nimob_sp_insertrecord</obj_name>
  <obj_hashval>5f925ac79097a1a9dea8f01f2818c09d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nimob_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NIMOB(CODNIMOB) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nimob_sp_lockrecord</obj_name>
  <obj_hashval>bd9eee0f3553899ffd1c93a9cbf6f78f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nimob_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CODNIMOB INTO Tmp FROM NIMOB WHERE CODNIMOB = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nmeserii_sp_deleterecord</obj_name>
  <obj_hashval>99148a983703d05c3848794da59c5495</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nmeserii_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_NMESERII_SP_LOCKRECORD( RecId);
  DELETE FROM NMESERII WHERE CodMeserie = RecId;
  PERFORM NotifyModif( 2, RECID, 'NMESERII');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nmeserii_sp_gotorecord</obj_name>
  <obj_hashval>522d80b175585ebe0bdd6f3575cc249c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nmeserii_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NMESERII(CodMeserie, Den_Meserie)
  (SELECT CodMeserie, Den_Meserie FROM NMESERII WHERE CodMeserie = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nmeserii_sp_insertrecord</obj_name>
  <obj_hashval>85e9969006bfb443526f0f428143bd97</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nmeserii_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NMESERII(CodMeserie) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nmeserii_sp_lockrecord</obj_name>
  <obj_hashval>37d75e84f433ee631cd788516365abd8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nmeserii_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodMeserie INTO Tmp FROM NMESERII WHERE CodMeserie = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nmeserii_sp_postrecords</obj_name>
  <obj_hashval>c1018e1b00bb705376d25e914ab9e1fb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nmeserii_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    SELECT CodMeserie INTO RecId FROM TMP_NMESERII;

    UPDATE NMESERII SET (Den_Meserie)  = (SELECT Den_Meserie FROM TMP_NMESERII) WHERE CodMeserie = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_NMESERII_CODMESERIE') INTO RecId;

    INSERT INTO NMESERII(CodMeserie, Den_Meserie)
    (SELECT RecId, Den_Meserie FROM TMP_NMESERII);
  END IF;

  PERFORM NotifyModif( OPERATION, RECID, 'NMESERII');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nmvs_getrecords</obj_name>
  <obj_hashval>e43da587b6ac1c561ac686cd9d541a4b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nmvs_getrecords(atipdoc numeric, acoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NMVSKEY varchar;
BEGIN
  --Florin 15.06.2023 - fixat 58586
  --Florin 03.09.2021 - fixat 51236
  --Adina 17.06.2021 - sinc.Oracle din 16.06.2021
  --Adina 18.05.2021 - sinc.Oracle din 18.05.2021
  NMVSKEY := fnc_GetValConstanta('NMVSKey', current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric, current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric);
  DELETE FROM TMP_NMVS_LOT;
  DELETE FROM TMP_NMVS_SERII;

  IF aTIPDOC IN (1, 2, 3, 5) THEN
    INSERT INTO TMP_NMVS_LOT(CODSERIE, CODOBIECT, GTIN, SERIE, DATAEXP, DENUMIRE, CANT)
    SELECT LOT.CODSERIE, O.CODOBIECT,
           CASE WHEN  COALESCE(NMVSKEY, '1') = '2' THEN LPAD(O.CODINTERN, 14, '0') ELSE LPAD(O.CODEXTERN, 14, '0') END  AS GTIN,
           SER.SERIE, LOT.DATAEXP, O.DENUMIRE, LOT.CANT
    FROM NARTOBJ O, NART A, NSERII SER,
         (SELECT NS.CODOBIECT, NSE.CODSERIE, TO_CHAR(COALESCE(NSE.TG, NS.TG), 'YYMMDD') AS DATAEXP, SUM(NSE.CANTNIR) AS CANT
          FROM NIRSER NSE, NIRSTOC NS, NIR N
          WHERE N.TIPNIR = aTIPDOC AND  N.CODINTR = aCODDOC AND  N.CODNIR = NS.CODNIR AND  NSE.CODNIRSTOC = NS.CODNIRSTOC
          GROUP BY NS.CODOBIECT, NSE.CODSERIE, TO_CHAR(COALESCE(NSE.TG, NS.TG), 'YYMMDD')
         ) LOT
    WHERE LOT.CODOBIECT = O.CODOBIECT AND  A.CODARTICOL = O.CODARTICOL AND  COALESCE(A.CHECKISAUTENTIC, 0) = 1 AND  LOT.CODSERIE = SER.CODSERIE;

    INSERT INTO TMP_NMVS_SERII(COD, CODSERIE, CODPARINTE, SERIE, RASPUNS, CODRASPUNS, STATUS, DATAVERIF, VERIFICARE, SKEMETYPE, USERID, GLN, MOTIV)
    SELECT S.CODSERIEINTR, S.CODSERIE, SER.CODPARINTE, SER.SERIE, S.RASPUNS, S.CODRASPUNS, S.STATUS, S.DATAVERIF, 0, COALESCE(S.SCHEMETYPE, 'GTIN'), S.USERID, S.GLN, S.MOTIV
    FROM SERIIINTR S, NSERII SER
    WHERE CODINTR = aCODDOC AND  S.CODSERIE = SER.CODSERIE;
  END IF;

  IF  aTIPDOC = 18 THEN
    INSERT INTO TMP_NMVS_LOT(CODSERIE, CODOBIECT, GTIN, SERIE, DATAEXP, DENUMIRE, CANT)
    SELECT LOT.CODSERIE, O.CODOBIECT,
           CASE WHEN  COALESCE(NMVSKEY, '1') = '2' THEN LPAD(O.CODINTERN, 14, '0') ELSE LPAD(O.CODEXTERN, 14, '0') END  AS GTIN,
           SER.SERIE, LOT.DATAEXP, O.DENUMIRE, LOT.CANT
    FROM NARTOBJ O, NART A, NSERII SER,
         (SELECT NS.CODOBIECT, NSE.CODSERIE, TO_CHAR(COALESCE(NSE.TG, NS.TG), 'YYMMDD') AS DATAEXP, SUM(R.REST) AS CANT
          FROM NIRSER NSE, NIRSTOC NS, REZERVATS R, COMANDA1 C1, COMANDA C
          WHERE C.TIPDOC = aTIPDOC AND  C.CODCOMANDA = aCODDOC AND  C1.CODCOMANDA = C.CODCOMANDA AND  R.CODCOMANDA1 = C1.CODCOMANDA1 AND  R.CODNIRSTOC = NS.CODNIRSTOC AND  R.CODNIRSER = NSE.CODNIRSER AND  NSE.CODNIRSTOC = NS.CODNIRSTOC
          GROUP BY NS.CODOBIECT, NSE.CODSERIE, TO_CHAR(COALESCE(NSE.TG, NS.TG), 'YYMMDD')
         ) LOT
    WHERE LOT.CODOBIECT = O.CODOBIECT AND  A.CODARTICOL = O.CODARTICOL AND  COALESCE(A.CHECKISAUTENTIC, 0) = 1 AND  LOT.CODSERIE = SER.CODSERIE;

    INSERT INTO TMP_NMVS_SERII(COD, CODSERIE, CODPARINTE, SERIE, RASPUNS, CODRASPUNS, STATUS, DATAVERIF, VERIFICARE, SKEMETYPE, USERID, GLN, MOTIV)
    SELECT S.CODSERIECMD, S.CODSERIE, SER.CODPARINTE, SER.SERIE, S.RASPUNS, S.CODRASPUNS, S.STATUS, S.DATAVERIF, 0, COALESCE(S.SCHEMETYPE, 'GTIN'), S.USERID, S.GLN, S.MOTIV
    FROM SERIICMD S, NSERII SER
    WHERE CODCOMANDA = aCODDOC AND  S.CODSERIE = SER.CODSERIE;
  END IF;

  IF aTIPDOC IN (14, 19, 20) THEN
    INSERT INTO TMP_NMVS_LOT(CODSERIE, CODOBIECT, GTIN, SERIE, DATAEXP, DENUMIRE, CANT)
    SELECT LOT.CODSERIE, O.CODOBIECT,
           CASE WHEN  COALESCE(NMVSKEY, '1') = '2' THEN LPAD(O.CODINTERN, 14, '0') ELSE LPAD(O.CODEXTERN, 14, '0') END  AS GTIN,
           SER.SERIE, LOT.DATAEXP, O.DENUMIRE, LOT.CANT
    FROM NARTOBJ O, NART A, NSERII SER,
         (SELECT NS.CODOBIECT, NSE.CODSERIE, TO_CHAR(COALESCE(NSE.TG, NS.TG), 'YYMMDD') AS DATAEXP, SUM(NSE.CANTNIR) AS CANT
          FROM NIRSER NSE, NIRSTOC NS, LIVR1 L1, LIVR L, IESIRI1 I1, IESIRI I
          WHERE I.TIPDOC = aTIPDOC AND  I.CODIES = aCODDOC AND  I1.CODIES = I.CODIES AND  L.CODIES = I.CODIES AND  L1.CODLIVR = L.CODLIVR AND  I1.CODIES1 = L1.CODIES1 AND  L1.CODNIRSTOC = NS.CODNIRSTOC AND  L1.CODNIRSER = NSE.CODNIRSER AND  NSE.CODNIRSTOC = NS.CODNIRSTOC
          GROUP BY NS.CODOBIECT, NSE.CODSERIE, TO_CHAR(COALESCE(NSE.TG, NS.TG), 'YYMMDD')
         ) LOT
    WHERE LOT.CODOBIECT = O.CODOBIECT AND  A.CODARTICOL = O.CODARTICOL AND  COALESCE(A.CHECKISAUTENTIC, 0) = 1 AND  LOT.CODSERIE = SER.CODSERIE;

    INSERT INTO TMP_NMVS_SERII(COD, CODSERIE, CODPARINTE, SERIE, RASPUNS, CODRASPUNS, STATUS, DATAVERIF, VERIFICARE, SKEMETYPE, USERID, GLN, MOTIV)
    SELECT S.CODSERIEIES, S.CODSERIE, SER.CODPARINTE, SER.SERIE, S.RASPUNS, S.CODRASPUNS, S.STATUS, S.DATAVERIF, 0, COALESCE(S.SCHEMETYPE, 'GTIN'), S.USERID, S.GLN, S.MOTIV
    FROM SERIIIES S, NSERII SER
    WHERE CODIES = aCODDOC AND  S.CODSERIE = SER.CODSERIE;
  END IF;

  IF  aTIPDOC = 12 THEN
    INSERT INTO TMP_NMVS_LOT(CODSERIE, CODOBIECT, GTIN, SERIE, DATAEXP, DENUMIRE, CANT)
    SELECT LOT.CODSERIE, O.CODOBIECT,
           CASE WHEN  COALESCE(NMVSKEY, '1') = '2' THEN LPAD(O.CODINTERN, 14, '0') ELSE LPAD(O.CODEXTERN, 14, '0') END  AS GTIN,
           SER.SERIE, LOT.DATAEXP, O.DENUMIRE, LOT.CANT
    FROM NARTOBJ O, NART A, NSERII SER,
         (SELECT NS.CODOBIECT, NSE.CODSERIE, TO_CHAR(COALESCE(NSE.TG, NS.TG), 'YYMMDD') AS DATAEXP, SUM(NSE.CANTNIR) AS CANT
          FROM NIRSER NSE, NIRSTOC NS, LIVR1 L1, LIVR L, TRANSF1 T1, TRANSF T
          WHERE T.TIPDOC = aTIPDOC AND  T.CODTRANSF = aCODDOC AND  T1.CODTRANSF = T.CODTRANSF AND  L.CODTRANSF = T.CODTRANSF AND  L1.CODLIVR = L.CODLIVR AND  T1.CODTRANSF1 = L1.CODIES1 AND  L1.CODNIRSTOC = NS.CODNIRSTOC AND  L1.CODNIRSER = NSE.CODNIRSER AND  NSE.CODNIRSTOC = NS.CODNIRSTOC
          GROUP BY NS.CODOBIECT, NSE.CODSERIE, TO_CHAR(COALESCE(NSE.TG, NS.TG), 'YYMMDD')
         ) LOT
    WHERE LOT.CODOBIECT = O.CODOBIECT AND  A.CODARTICOL = O.CODARTICOL AND  COALESCE(A.CHECKISAUTENTIC, 0) = 1 AND  LOT.CODSERIE = SER.CODSERIE;

    INSERT INTO TMP_NMVS_SERII(COD, CODSERIE, CODPARINTE, SERIE, RASPUNS, CODRASPUNS, STATUS, DATAVERIF, VERIFICARE, SKEMETYPE, USERID, GLN, MOTIV)
    SELECT S.CODSERIETRANSF, S.CODSERIE, SER.CODPARINTE, SER.SERIE, S.RASPUNS, S.CODRASPUNS, S.STATUS, S.DATAVERIF, 0, COALESCE(S.SCHEMETYPE, 'GTIN'), S.USERID, S.GLN, S.MOTIV
    FROM SERIITRANSF S, NSERII SER
    WHERE CODTRANSF = aCODDOC AND  S.CODSERIE = SER.CODSERIE;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nmvs_postrecords</obj_name>
  <obj_hashval>b9331d7db88400ff0fc6e54fb85aca30</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nmvs_postrecords(atipdoc numeric, acoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC_LOT   RECORD;
  V_REC_SERII RECORD;
  aCODSERIE   numeric;
BEGIN
  --Florin 03.09.2021 - inlocuit SCHEMETYPE cu SKEMETYPE
  --Adina 17.06.2021 - sinc.Oracle din 16.06.2021
  --Adina 18.05.2021 - sinc.Oracle din 18.05.2021
  IF aTIPDOC IN (1, 2, 3, 5) THEN
    DELETE FROM SERIIINTR WHERE CODINTR = aCODDOC AND CODSERIEINTR NOT IN (SELECT COD FROM TMP_NMVS_SERII);

    FOR V_REC_LOT IN (SELECT CODSERIE, CODOBIECT, GTIN, DATAEXP FROM TMP_NMVS_LOT) LOOP
      FOR V_REC_SERII IN (SELECT * FROM TMP_NMVS_SERII WHERE CODPARINTE = V_REC_LOT.CODSERIE) LOOP
        IF  V_REC_SERII.COD &lt; 0 THEN
          IF  V_REC_SERII.CODSERIE &lt; 0 THEN
            aCODSERIE := (SELECT PKG_IMPORTALTEAPLICATII_GETSERIEDINLOT.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_GETSERIEDINLOT(NULL,V_REC_SERII.CODPARINTE, V_REC_LOT.CODOBIECT, V_REC_SERII.SERIE));
          ELSE
            aCODSERIE := V_REC_SERII.CODSERIE;
          END IF;

          INSERT INTO SERIIINTR(CODSERIEINTR, CODINTR, CODOBIECT, CODSERIE, DATAEXP, RASPUNS, STATUS, DATAVERIF, GTIN, CODRASPUNS, SKEMETYPE, USERID, GLN, MOTIV)
          VALUES(NEXTVAL('SEQ_SERIIINTR_CODSERIEINTR'), aCODDOC, V_REC_LOT.CODOBIECT, aCODSERIE, V_REC_LOT.DATAEXP, V_REC_SERII.RASPUNS, V_REC_SERII.STATUS,
                 V_REC_SERII.DATAVERIF, V_REC_LOT.GTIN, V_REC_SERII.CODRASPUNS, V_REC_SERII.SKEMETYPE, V_REC_SERII.USERID, V_REC_SERII.GLN, V_REC_SERII.MOTIV);
        ELSE
          UPDATE SERIIINTR
          SET
          RASPUNS    = V_REC_SERII.RASPUNS,
          STATUS     = V_REC_SERII.STATUS,
          DATAVERIF  = V_REC_SERII.DATAVERIF,
          GTIN       = V_REC_LOT.GTIN,
          CODRASPUNS = V_REC_SERII.CODRASPUNS,
          SKEMETYPE = V_REC_SERII.SKEMETYPE,
          USERID     = V_REC_SERII.USERID,
          GLN        = V_REC_SERII.GLN,
          MOTIV      = V_REC_SERII.MOTIV
          WHERE
           CODSERIEINTR = V_REC_SERII.COD;
        END IF;
      END LOOP;
    END LOOP;
  END IF;

  IF aTIPDOC IN (14, 19, 20) THEN
    DELETE FROM SERIIIES WHERE CODIES = aCODDOC AND CODSERIEIES NOT IN (SELECT COD FROM TMP_NMVS_SERII);

    FOR V_REC_LOT IN (SELECT CODSERIE, CODOBIECT, GTIN, DATAEXP FROM TMP_NMVS_LOT) LOOP
      FOR V_REC_SERII IN (SELECT * FROM TMP_NMVS_SERII WHERE CODPARINTE = V_REC_LOT.CODSERIE) LOOP
        IF  V_REC_SERII.COD &lt; 0 THEN
          IF  V_REC_SERII.CODSERIE &lt; 0 THEN
            aCODSERIE := (SELECT PKG_IMPORTALTEAPLICATII_GETSERIEDINLOT.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_GETSERIEDINLOT(NULL,V_REC_SERII.CODPARINTE, V_REC_LOT.CODOBIECT, V_REC_SERII.SERIE));
          ELSE
            aCODSERIE := V_REC_SERII.CODSERIE;
          END IF;

          INSERT INTO SERIIIES(CODSERIEIES, CODIES, CODOBIECT, CODSERIE, DATAEXP, RASPUNS, STATUS, DATAVERIF, GTIN, CODRASPUNS, SKEMETYPE, USERID, GLN, MOTIV)
          VALUES(NEXTVAL('SEQ_SERIIIES_CODSERIEIES'), aCODDOC, V_REC_LOT.CODOBIECT, aCODSERIE, V_REC_LOT.DATAEXP, V_REC_SERII.RASPUNS, V_REC_SERII.STATUS,
                 V_REC_SERII.DATAVERIF, V_REC_LOT.GTIN, V_REC_SERII.CODRASPUNS, V_REC_SERII.SKEMETYPE, V_REC_SERII.USERID, V_REC_SERII.GLN, V_REC_SERII.MOTIV);
        ELSE
          UPDATE SERIIIES
          SET
          RASPUNS    = V_REC_SERII.RASPUNS,
          STATUS     = V_REC_SERII.STATUS,
          DATAVERIF  = V_REC_SERII.DATAVERIF,
          GTIN       = V_REC_LOT.GTIN,
          CODRASPUNS = V_REC_SERII.CODRASPUNS,
          SKEMETYPE = V_REC_SERII.SKEMETYPE,
          USERID     = V_REC_SERII.USERID,
          GLN        = V_REC_SERII.GLN,
          MOTIV      = V_REC_SERII.MOTIV
          WHERE
           CODSERIEIES = V_REC_SERII.COD;
        END IF;
      END LOOP;
    END LOOP;
  END IF;

  IF  aTIPDOC = 18 THEN
    DELETE FROM SERIICMD WHERE CODCOMANDA = aCODDOC AND CODSERIECMD NOT IN (SELECT COD FROM TMP_NMVS_SERII);

    FOR V_REC_LOT IN (SELECT CODSERIE, CODOBIECT, GTIN, DATAEXP FROM TMP_NMVS_LOT) LOOP
      FOR V_REC_SERII IN (SELECT * FROM TMP_NMVS_SERII WHERE CODPARINTE = V_REC_LOT.CODSERIE) LOOP
        IF  V_REC_SERII.COD &lt; 0 THEN
          IF  V_REC_SERII.CODSERIE &lt; 0 THEN
            aCODSERIE := (SELECT PKG_IMPORTALTEAPLICATII_GETSERIEDINLOT.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_GETSERIEDINLOT(NULL,V_REC_SERII.CODPARINTE, V_REC_LOT.CODOBIECT, V_REC_SERII.SERIE));
          ELSE
            aCODSERIE := V_REC_SERII.CODSERIE;
          END IF;

          INSERT INTO SERIICMD(CODSERIECMD, CODCOMANDA, CODOBIECT, CODSERIE, DATAEXP, RASPUNS, STATUS, DATAVERIF, GTIN, CODRASPUNS, SKEMETYPE, USERID, GLN, MOTIV)
          VALUES(NEXTVAL('SEQ_SERIICMD_CODSERIECMD'), aCODDOC, V_REC_LOT.CODOBIECT, aCODSERIE, V_REC_LOT.DATAEXP, V_REC_SERII.RASPUNS, V_REC_SERII.STATUS,
                 V_REC_SERII.DATAVERIF, V_REC_LOT.GTIN, V_REC_SERII.CODRASPUNS, V_REC_SERII.SKEMETYPE, V_REC_SERII.USERID, V_REC_SERII.GLN, V_REC_SERII.MOTIV);
        ELSE
          UPDATE SERIICMD
          SET
          RASPUNS    = V_REC_SERII.RASPUNS,
          STATUS     = V_REC_SERII.STATUS,
          DATAVERIF  = V_REC_SERII.DATAVERIF,
          GTIN       = V_REC_LOT.GTIN,
          CODRASPUNS = V_REC_SERII.CODRASPUNS,
          SKEMETYPE = V_REC_SERII.SKEMETYPE,
          USERID     = V_REC_SERII.USERID,
          GLN        = V_REC_SERII.GLN,
          MOTIV      = V_REC_SERII.MOTIV
          WHERE
           CODSERIECMD = V_REC_SERII.COD;
        END IF;
      END LOOP;
    END LOOP;
  END IF;

  IF  aTIPDOC = 12 THEN
    DELETE FROM SERIITRANSF WHERE CODTRANSF = aCODDOC AND CODSERIETRANSF NOT IN (SELECT COD FROM TMP_NMVS_SERII);

    FOR V_REC_LOT IN (SELECT CODSERIE, CODOBIECT, GTIN, DATAEXP FROM TMP_NMVS_LOT) LOOP
      FOR V_REC_SERII IN (SELECT * FROM TMP_NMVS_SERII WHERE CODPARINTE = V_REC_LOT.CODSERIE) LOOP
        IF  V_REC_SERII.COD &lt; 0 THEN
          IF  V_REC_SERII.CODSERIE &lt; 0 THEN
            aCODSERIE := (SELECT PKG_IMPORTALTEAPLICATII_GETSERIEDINLOT.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_GETSERIEDINLOT(NULL,V_REC_SERII.CODPARINTE, V_REC_LOT.CODOBIECT, V_REC_SERII.SERIE));
          ELSE
            aCODSERIE := V_REC_SERII.CODSERIE;
          END IF;

          INSERT INTO SERIITRANSF(CODSERIETRANSF, CODTRANSF, CODOBIECT, CODSERIE, DATAEXP, RASPUNS, STATUS, DATAVERIF, GTIN, CODRASPUNS, SKEMETYPE, USERID, GLN, MOTIV)
          VALUES(NEXTVAL('SEQ_SERIITRANSF_CODSERIETRANSF'), aCODDOC, V_REC_LOT.CODOBIECT, aCODSERIE, V_REC_LOT.DATAEXP, V_REC_SERII.RASPUNS, V_REC_SERII.STATUS,
                 V_REC_SERII.DATAVERIF, V_REC_LOT.GTIN, V_REC_SERII.CODRASPUNS, V_REC_SERII.SKEMETYPE, V_REC_SERII.USERID, V_REC_SERII.GLN, V_REC_SERII.MOTIV);
        ELSE
          UPDATE SERIITRANSF
          SET
          RASPUNS    = V_REC_SERII.RASPUNS,
          STATUS     = V_REC_SERII.STATUS,
          DATAVERIF  = V_REC_SERII.DATAVERIF,
          GTIN       = V_REC_LOT.GTIN,
          CODRASPUNS = V_REC_SERII.CODRASPUNS,
          SKEMETYPE = V_REC_SERII.SKEMETYPE,
          USERID     = V_REC_SERII.USERID,
          GLN        = V_REC_SERII.GLN,
          MOTIV      = V_REC_SERII.MOTIV
          WHERE
           CODSERIETRANSF = V_REC_SERII.COD;
        END IF;
      END LOOP;
    END LOOP;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nmvs_updatenmvs</obj_name>
  <obj_hashval>81b1a31ca3e90a9f830e45662370f325</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nmvs_updatenmvs(INOUT acodnmvs numeric, INOUT araspuns character varying, INOUT acodraspuns character varying, INOUT astatus character varying, INOUT amotiv character varying, INOUT afunctie character varying, INOUT askemetype character varying, INOUT agln character varying, INOUT anewcodnmvs numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDataVerif date;
begin
  aNewCodNMVS := aCodNMVS;

  BEGIN
    SELECT coalesce(dataverif, to_date('30.12.1899', 'dd.mm.yyyy')) INTO aDataVerif FROM nmvs WHERE codnmvs = aCodNMVS;
  EXCEPTION WHEN others THEN
    aDataVerif := CURRENT_TIMESTAMP;
  END;

  IF  aDataVerif = to_date('30.12.1899', 'dd.mm.yyyy') THEN
    UPDATE nmvs
    SET
    dataverif   = CURRENT_TIMESTAMP,
    mesaj       = araspuns,
    codmesaj    = acodraspuns,
    status      = astatus,
    motiv       = amotiv,
    userid      = current_setting('PKG_GLOBALS.USERID', true)::numeric,
    codfunctie  = aFunctie,
    GLN         = aGLN,
    subunitatea = current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric
    WHERE
     codnmvs = acodnmvs;
  ELSE
    SELECT NEXTVAL('SEQ_NMVS_CODNMVS') INTO aNewCodNMVS;

    INSERT INTO nmvs(codnmvs, userid, subunitatea, dataverif, gtin, dataexp, lot, sn, skemetype, mesaj, codmesaj, status, motiv, codfunctie, gln)
    SELECT aNewCodNMVS, current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, CURRENT_TIMESTAMP, gtin, dataexp, lot, sn, aSkemeType, aRaspuns, aCodRaspuns, aStatus, aMotiv, aFunctie, agln
    FROM nmvs
    WHERE codnmvs = aCodNMVS;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_actualizeaza_nartcli</obj_name>
  <obj_hashval>33f6a3f814f6960a2cfaf827b73b83e8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_actualizeaza_nartcli(acodobiect numeric, acodpart numeric, acodclasep numeric, adenumire character varying, acodextern character varying, acodlaclient character varying, aumsec numeric, atipcodafisat numeric, aforceupd numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCodArtCli  numeric;
  vCodPart    numeric;
  vForceUpd   numeric;
BEGIN
  --Florin 17.03.2022 - fixat 53557
  vCodPart := CASE WHEN aCodClaseP = 0 THEN aCodPart ELSE 0 END;
  IF aForceUpd IS NULL THEN
    vForceUpd := Coalesce((fnc_GetValConstantaLucru('DetArtPartFromDoc')::numeric), 1);
  ELSE
    vForceUpd := aForceUpd;
  END IF;

  IF  aCodObiect IS NOT NULL
  AND (Coalesce(vCodPart,0) &gt; 0 OR Coalesce(aCodClaseP, 0) &gt; 0)
  AND ((aDenumire IS NOT NULL AND aDenumire &lt;&gt; '') OR (aCodExtern IS NOT NULL AND aCodExtern &lt;&gt; '') OR (aCodLaClient IS NOT NULL AND aCodLaClient &lt;&gt; ''))
  THEN
    SELECT Coalesce(Max(CODARTCLI), 0) INTO vCodArtCli
    FROM NArtCli
    WHERE CodObiect = aCodObiect
      AND CASE WHEN aCodClaseP = 0 THEN CodPart ELSE 0 END   = vCodPart
      AND CASE WHEN aCodClaseP = 0 THEN 0 ELSE CodClasep END = aCodClasep;

    IF vCodArtCli = 0 THEN
      vCodArtCli := NEXTVAL('SEQ_NARTCLI_CODARTCLI');
      INSERT INTO NARTCLI ( CodArtCli,  CodObiect,  CodPart,  CodClaseP,  Denumire,  CodExtern,  CodLaClient,  UMSec,  TipCodAfisat)
      VALUES              ( vCodArtCli, aCodObiect, vCodPart, aCodClaseP, aDenumire, aCodExtern, aCodLaClient, aUMSec, Coalesce(aTipCodAfisat,1)) ;
    ELSE
      UPDATE NARTCLI
      SET Denumire    = CASE WHEN vForceUpd = 1 THEN Coalesce(aDenumire, Denumire)      ELSE Coalesce(Denumire, aDenumire)      END,
          CodExtern   = CASE WHEN vForceUpd = 1 THEN Coalesce(aCodExtern,CodExtern)     ELSE Coalesce(CodExtern,aCodExtern)     END,
          CodLaClient = CASE WHEN vForceUpd = 1 THEN Coalesce(aCodLaClient,CodLaClient) ELSE Coalesce(CodLaClient,aCodLaClient) END
      WHERE CodArtCli = vCodArtCli;
    END IF;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_checkmodifpretretail</obj_name>
  <obj_hashval>56ffa94e1554cdfb7b33c02cf9b3c175</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_checkmodifpretretail(acodobiect numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC    RECORD;
  aCODSYNC NUMERIC;
  aVALUE   VARCHAR := '0';
  aVALUE2  varchar := '0';
BEGIN
  --Florin 24.05.2022 - sinc. Oracle
  --Adina 02.02.2021 - add aValue2
  BEGIN
    SELECT fnc_GetValConstanta('SyncPretRetail', getANLUCRU(), getLUNALUCRU()) INTO aValue;
  EXCEPTION WHEN OTHERS THEN
    aValue := '0';
  END;

  BEGIN
     SELECT fnc_GetValConstanta('ArtSyncPretRetail', getANLUCRU(), getLUNALUCRU()) INTO aValue2;
     EXCEPTION WHEN OTHERS THEN aValue2 := '0';
  END;

 --insert into x(view_name) values(' aValue ' || aValue);
  IF aVALUE = '1' THEN
    FOR V_REC IN (SELECT P.COD AS CODPOSTRETAIL, O.CODOBIECT, PM.LEI AS PRETNOU, PM.CODCATPRET
                  FROM POSTRETAIL P,
                       TMP_PRETM PM
                       LEFT JOIN PRETM PM_OLD ON PM_OLD.CODOBIECT = PM.CODOBIECT AND PM_OLD.CODCATPRET = PM.CODCATPRET AND PM_OLD.SUBUNITATEA = PM.SUBUNITATEA,
                       NARTOBJ O,
                       NART A,
                       NCATPRET CP
                  WHERE --PM.SUBUNITATEA = (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL, NULL))
                    --AND P.SUBUNITATEA  = (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL, NULL))
                    PM.SUBUNITATEA     = P.SUBUNITATEA
                    AND PM.CODOBIECT   = O.CODOBIECT
                    AND O.CODOBIECT    = aCODOBIECT
                    AND A.CODARTICOL   = O.CODARTICOL
                    AND COALESCE(A.CASADEMARCAT, 0) = 1
                    AND PM.CODCATPRET  = CP.CODCATPRET
                    AND CP.TIP IN (1, 2)
                    AND (COALESCE(PM_OLD.LEI, 0) &lt;&gt; COALESCE(PM.LEI, 0) OR coalesce(aVALUE2, '?')::numeric = 1)
                 )
    LOOP
      BEGIN
        SELECT CODSYNC INTO aCODSYNC
        FROM SYNCPRETRETAIL
        WHERE CODPOSTRETAIL = V_REC.CODPOSTRETAIL
          AND CODOBIECT = V_REC.CODOBIECT
          AND CODCATPRET = V_REC.CODCATPRET;
      EXCEPTION WHEN OTHERS THEN
        aCODSYNC := 0;
      END;

      IF coalesce(aCODSYNC, 0) = 0 THEN
        INSERT INTO SYNCPRETRETAIL (CODSYNC, CODPOSTRETAIL, CODOBIECT, CODCATPRET, PRETNOU, DATA, SINCRONIZAT)
        VALUES (NEXTVAL('SEQ_SYSNPRETRETAIL_CODSYNC'), V_REC.CODPOSTRETAIL, V_REC.CODOBIECT, V_REC.CODCATPRET, V_REC.PRETNOU, CURRENT_TIMESTAMP, 0);
      ELSE
        UPDATE SYNCPRETRETAIL
        SET
          PRETNOU     = V_REC.PRETNOU,
          DATA        = CURRENT_TIMESTAMP,
          SINCRONIZAT = 0
        WHERE
            CODSYNC = aCODSYNC AND PRETNOU  &lt;&gt; V_REC.PRETNOU;
      END IF;
    END LOOP;
  END IF;

  IF aVALUE = '1' THEN
    FOR V_REC IN (SELECT * FROM (SELECT P.COD AS CODPOSTRETAIL, O.CODOBIECT, PMAMB.LEI AS PRETNOU, PM.CODCATPRET,
                                        (SELECT PMAMB_OLD.LEI
                                         FROM PRETM PM_OLD,
                                              PRETMAMB PMAMB_OLD
                                         WHERE PM_OLD.CODOBIECT   = PM.CODOBIECT
                                           AND PM_OLD.CODCATPRET  = PM.CODCATPRET
                                           AND PM_OLD.SUBUNITATEA = PM.SUBUNITATEA
                                           AND PMAMB_OLD.CODPRETM = PM_OLD.CODPRETM
                                           AND PMAMB_OLD.CODAMB   = PMAMB.CODAMB
                                        ) AS PRETOLD
                                 FROM TMP_PRETMAMB PMAMB,
                                      TMP_PRETM PM,
                                      POSTRETAIL P,
                                      NARTOBJ O,
                                      NART A,
                                      NCATPRET CP
                                 WHERE PMAMB.CODPRETM = PM.CODPRETM
                                   AND PM.SUBUNITATEA = (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL, NULL))
                                   AND P.SUBUNITATEA  = (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL, NULL))
                                   AND PM.CODOBIECT = O.CODOBIECT
                                   AND O.CODOBIECT = aCODOBIECT
                                   AND A.CODARTICOL = O.CODARTICOL
                                   AND COALESCE(A.CASADEMARCAT, 0) = 1
                                   AND PM.CODCATPRET = CP.CODCATPRET
                                   AND CP.TIP IN (1, 2)
                                ) A_PG
                  WHERE PRETOLD &lt;&gt; PRETNOU)
    LOOP
      BEGIN
        SELECT CODSYNC INTO aCODSYNC
        FROM SYNCPRETRETAIL
        WHERE CODPOSTRETAIL = V_REC.CODPOSTRETAIL
          AND CODOBIECT     = V_REC.CODOBIECT
          AND CODCATPRET    = V_REC.CODCATPRET;
      EXCEPTION WHEN OTHERS THEN
        aCODSYNC := 0;
      END;

      IF coalesce(aCODSYNC, 0) = 0 THEN
        INSERT INTO SYNCPRETRETAIL (CODSYNC, CODPOSTRETAIL, CODOBIECT, CODCATPRET, PRETNOU, DATA, SINCRONIZAT)
        VALUES (NEXTVAL('SEQ_SYSNPRETRETAIL_CODSYNC'), V_REC.CODPOSTRETAIL, V_REC.CODOBIECT, V_REC.CODCATPRET, V_REC.PRETNOU, CURRENT_TIMESTAMP, 0);
      ELSE
        UPDATE SYNCPRETRETAIL
        SET
          PRETNOU     = V_REC.PRETNOU,
          DATA        = CURRENT_TIMESTAMP,
          SINCRONIZAT = 0
        WHERE
          CODSYNC = aCODSYNC;
      END IF;
    END LOOP;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_clonare_pretm_atrib</obj_name>
  <obj_hashval>d0c22cdb086d7c58152f3c4bf1189e42</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_clonare_pretm_atrib(acodobiect numeric, acodsubunit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  aCodArticol numeric;
  aImplicit   numeric;
  CodObjSursa numeric;
  aOrdine     varchar := '';
  MaxOrdine   varchar := '';
  PROC        double precision;
  MAJORARE    double precision := 1;
  MaxGRUPA    varchar := '';
begin
  PERFORM PKG_NOM_ARTICOL_TMPORDINEGRUPEPRET();

  SELECT codArticol     INTO aCodArticol FROM Nartobj WHERE CodObiect = aCodObiect;
  SELECT nobj.codobiect INTO CodObjSursa FROM nartobj nobj
  WHERE (SELECT COUNT( *) FROM NAtrObj AO WHERE AO.CodObiect = NOBJ.CodObiect) = 0 and  nobj.codarticol = aCodArticol;

  IF (COALESCE( CodObjSursa, 0) &gt; 0)  and (CodObjSursa &lt;&gt; aCodObiect) THEN
    FOR V_REC IN (SELECT A.CodValAtr, A1.Grupa
                  FROM NAtrObj A
                       INNER JOIN NATRIB1 A1 ON  A.CODVALATR = A1.CODVALATR
                  WHERE A.CODOBIECT = aCodObiect
                 )
    LOOP
      aOrdine := '';
      BEGIN
        SELECT VALOARE INTO aOrdine FROM TMP_MANEVRA_LISTE WHERE Upper( COALESCE( filtru, '?')) = UPPER( COALESCE( V_Rec.Grupa, ''));
      EXCEPTION WHEN no_data_found THEN
        NULL;
      END;

      IF  COALESCE( aOrdine, '') &lt;&gt; '' THEN
        IF  aOrdine &gt; MaxOrdine THEN
          MaxOrdine := aOrdine;
          MaxGrupa := UPPER( V_Rec.Grupa);
        END IF;
      ELSE
        IF  UPPER( COALESCE( V_Rec.Grupa, '')) &gt; MaxGRUPA THEN
          MaxGrupa := UPPER( V_Rec.Grupa);
        END IF;
      END IF;

      BEGIN
        SELECT COALESCE( PROCMAJ, 0) INTO PROC FROM NATRIB2 WHERE CODVALATR = V_REC.CODVALATR AND  CODARTICOL = ACODARTICOL;
      EXCEPTION WHEN others THEN
        PROC := 0;
      END;

      MAJORARE := MAJORARE * (  1 + PROC / 100) ;
    END LOOP;

    IF  aCodSubunit &gt; 1 THEN
      SELECT Count( *) INTO aImplicit FROM PretM WHERE Subunitatea = aCodSubunit and  CodObiect = aCodObiect and  COALESCE( Grupa, '') &lt;&gt; '';

      IF  aImplicit &gt; 1 THEN
        aImplicit := 1;
      END IF;

      DELETE FROM PretM WHERE Subunitatea = aCodSubunit and  CodObiect = aCodObiect and  COALESCE( Grupa, '') &lt;&gt; '';

      INSERT INTO PRETM(CODPRETM, CODOBIECT, CODCATPRET, LEI, VALUTA, MONEDA, IMPLICIT, PROC, INDEXLOCAL, SUBUNITATEA, GRUPA, ROTUNJIRE)
      SELECT NEXTVAL('SEQ_PRETM_CODPRETM'), aCodObiect, CODCATPRET, Round( LEI * MAJORARE, 2), Round( VALUTA * MAJORARE, 2), MONEDA, aImplicit, PROC, INDEXLOCAL, SUBUNITATEA, GRUPA, ROTUNJIRE
      FROM PRETM
      WHERE CODOBIECT = CodObjSursa and  Subunitatea = aCodSubunit and  UPPER( COALESCE( Grupa, '')) = MaxGRUPA;
    ELSE
      FOR v_rec IN (SELECT * FROM PretM WHERE CODOBIECT = CodObjSursa and  UPPER( COALESCE( Grupa, '')) = MaxGRUPA) LOOP
        SELECT Count( *) INTO aImplicit FROM PretM WHERE Subunitatea = v_rec.Subunitatea and  CodObiect = aCodObiect and  COALESCE( Grupa, '') &lt;&gt; '';

        IF  aImplicit &gt; 1 THEN
          aImplicit := 1;
        END IF;

        DELETE FROM PretM WHERE Subunitatea = v_rec.Subunitatea and  CodObiect = aCodObiect and  COALESCE( Grupa, '') &lt;&gt; '';

        INSERT INTO PRETM (CODPRETM, CODOBIECT, CODCATPRET, LEI, VALUTA, MONEDA, IMPLICIT, PROC, INDEXLOCAL, SUBUNITATEA, GRUPA, ROTUNJIRE)
        SELECT NEXTVAL('SEQ_PRETM_CODPRETM'), aCodObiect, CODCATPRET, Round( LEI * MAJORARE, 2), Round( VALUTA * MAJORARE, 2), MONEDA, aImplicit, PROC, INDEXLOCAL, SUBUNITATEA, GRUPA, ROTUNJIRE
        FROM PRETM
        WHERE CODOBIECT = CodObjSursa and  Subunitatea = v_rec.Subunitatea and  UPPER( COALESCE( Grupa, '')) = MaxGRUPA;
      END LOOP;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_cloneazanartobjext</obj_name>
  <obj_hashval>0b9d1b4af3c48f397a0db1295a67c388</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_cloneazanartobjext(codobiectgeneric numeric, codart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  S varchar;
begin
  S := 'BEGIN ' ||
       'FOR V_REC IN ' ||
       '   (SELECT CODOBIECT ' ||
       '    FROM ' ||
       '      NARTOBJ O ' ||
       '  WHERE ' ||
       '    CODOBIECT &lt;&gt; ' || TO_CHAR( CODOBIECTGENERIC,'9999999999') ||
       '    AND CODARTICOL = ' || TO_CHAR( CODART,'9999999999') ||
       '    AND (SELECT COUNT(*) FROM NARTOBJEXT OE WHERE OE.CODOBIECT = O.CODOBIECT) = 0 ' ||
       '  )  ' ||
       '  LOOP ' ||
       '    INSERT INTO NARTOBJEXT (' || (SELECT PKG_NOM_ARTICOL_GetStrNARTOBJEXT.WME_RESULT FROM PKG_NOM_ARTICOL_GetStrNARTOBJEXT(NULL, 1)) || ') ' ||
       '    SELECT SEQ_NARTOBJEXT_CODNARTOBJEXT.NEXTVAL, V_REC.CODOBIECT, ' || (SELECT PKG_NOM_ARTICOL_GetStrNARTOBJEXT.WME_RESULT FROM PKG_NOM_ARTICOL_GetStrNARTOBJEXT(NULL, 3)) ||
          ' FROM NARTOBJEXT WHERE CODOBIECT = ' || TO_CHAR( CODOBIECTGENERIC,'9999999999') || '; ' ||
       '  END LOOP;' ||
       'END;';
  BEGIN
    EXECUTE S;
  EXCEPTION WHEN OTHERS THEN
    NULL;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_cod_extern_unic</obj_name>
  <obj_hashval>2ae73c6b6c224cbd000491842bdca683</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_cod_extern_unic(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT acodextern character varying, INOUT acodump numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
NR numeric := 0;
begin
 -- Bogdan 11.10.2021 adaugat conditie CodExternUnicAmb
  SELECT SUM(N)INTO NR
    FROM (SELECT COUNT(*) AS N FROM NARTOBJ a  WHERE CODEXTERN = aCODEXTERN AND CODOBIECT &lt;&gt; aCODOBIECT
          union ALL
          SELECT COUNT(*) AS N FROM CODEXTALT aa WHERE CODEXTERN = aCODEXTERN AND CODOBIECT &lt;&gt; aCODOBIECT) A_PG;
  IF coalesce(fnc_getvalconstanta('CodExternUnicAmb', getanlucru(), getlunalucru()), '0') &lt;&gt; '3' THEN
    IF NR = 0 THEN
      SELECT COUNT(*) INTO NR FROM NARTAMB AMB
      WHERE (
              (CODOBIECT = aCODOBIECT AND UMSEC &lt;&gt; aCODUMP) OR  (CODOBIECT &lt;&gt; aCODOBIECT)
            )AND AMB.CODEXTERN IS NOT NULL AND AMB.CODEXTERN = aCODEXTERN;
     end if;
   end if;
   IF NR = 0 THEN
      WME_Result := 1;
      RETURN;
   ELSE
      WME_Result := 0;
      RETURN;
   END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_cod_extern_unic_amb</obj_name>
  <obj_hashval>88a11a3044059df55cbeaa01dcd39de5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_cod_extern_unic_amb(INOUT wme_result numeric, INOUT acodamb numeric, INOUT acodobiect numeric, INOUT acodumsec numeric, INOUT acodextern character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
NR numeric := 0;
begin
  -- Bogdan 11.10.2021 adaugat conditie CodExternUnicAmb
  SELECT COUNT(*)INTO NR FROM NARTAMB WHERE CODEXTERN IS NOT NULL AND CODAMB &lt;&gt; aCODAMB AND UPPER(CODEXTERN) = UPPER(aCODEXTERN);
 IF coalesce(fnc_getvalconstanta('CodExternUnicAmb', getanlucru(), getlunalucru()), '0') = '3' then
   IF NR = 0 THEN
      WME_Result := 1;
       RETURN;
   ELSE
      WME_Result := 0;
        RETURN;
   END IF;
 END IF;
  IF NR = 0 THEN
    SELECT SUM(N) INTO NR
      FROM (SELECT COUNT(*) AS N FROM NARTOBJ O INNER JOIN NART A
                ON A.CODARTICOL = O.CODARTICOL WHERE O.CODEXTERN = aCODEXTERN
                   AND ((CODOBIECT &lt;&gt; aCODOBIECT) OR (CODOBIECT = aCODOBIECT AND A.UM &lt;&gt; aCODUMSEC))
            union ALL
            SELECT COUNT(*) AS N FROM CODEXTALT WHERE CODEXTERN = aCODEXTERN AND CODOBIECT &lt;&gt; aCODOBIECT) A_PG;
    IF NR = 0 THEN
      WME_Result := 1;
      RETURN;
    ELSE
      WME_Result := 0;
      RETURN;
    END IF;
  ELSE
    WME_Result := 0;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_cod_intern_unic</obj_name>
  <obj_hashval>957e4313950352783e57bdeaf3a7b079</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_cod_intern_unic(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT acodintern character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  SELECT COUNT( *) INTO NR FROM NARTOBJ WHERE CODINTERN = aCODINTERN AND  CODOBIECT &lt;&gt; aCODOBIECT;

  IF  NR = 0 THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    WME_Result :=  0;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_cod_plu_unic</obj_name>
  <obj_hashval>d5dce263f5076ed715f558ba9b2b6667</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_cod_plu_unic(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT acodplu numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  SELECT COUNT( *) INTO NR FROM NARTOBJ WHERE CODPLU = aCODPLU AND  CODOBIECT &lt;&gt; aCODOBIECT;

  IF  NR = 0 THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    WME_Result :=  0;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_copie_categ_preturi</obj_name>
  <obj_hashval>7b24f97157d2b8bccb92bf527fd88ec9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_copie_categ_preturi()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aIMPLICIT        NUMERIC(1) := 0;
  aSyncPretRetail  VARCHAR(10);
  aMemoModiPret    VARCHAR(10);
  CodSubCurent     NUMERIC(20);
  V_REC_I          record;
  V_REC_C          record;
BEGIN
  --Florin 14.02.2025 - sinc. Oracle
   --Florin 29.01.2025 - sinc. Oracle
   CodSubCurent :=  getSUBUNITATE();
  BEGIN
     SELECT fnc_getvalconstanta('SyncPretRetail') INTO aSyncPretRetail;
     EXCEPTION WHEN OTHERS THEN aSyncPretRetail := '0';
  END;

  BEGIN
     SELECT fnc_getvalconstanta('MemoModiPret') INTO aMemoModiPret;
     EXCEPTION WHEN OTHERS THEN aMemoModiPret := '0';
  END;
  FOR V_REC_I IN (SELECT * FROM TMP_CPPRETINFO)
  LOOP

    FOR V_REC_C IN ( SELECT
                       PMB.*,
                       NVL(PMS.CODPRETM, 0) AS CODPRETMS,
                       NVL(PMS.LEI, 0) AS PMSLEI,
                       NVL(PMS.VALUTA, 0) AS PMSVALUTA,
                       NVL(PMS.MONEDA, 0) AS PMSMONEDA,
                       NVL(PMS.IMPLICIT, 0) AS PMSIMPLICIT,
                       NVL(PMSI.CODPRETM, 0) AS CODPRETMSI
                     FROM
                       PRETM PMB
                       LEFT JOIN PRETM PMS  ON PMS.CODOBIECT = PMB.CODOBIECT
                                                             AND PMS.CODCATPRET = V_REC_I.CODCATPRET_DEST
                                                             AND PMS.SUBUNITATEA = V_REC_I.CODSUBUNIT_DEST
                       LEFT JOIN PRETM PMSI ON PMSI.CODOBIECT = PMB.CODOBIECT
                                               AND PMSI.SUBUNITATEA = V_REC_I.CODSUBUNIT_DEST
                                               AND PMSI.IMPLICIT = 1
                     WHERE
                       PMB.SUBUNITATEA = CODSUBCURENT
                       AND PMB.CODCATPRET = V_REC_I.CODCATPRET_SURSA
     )
     LOOP
           aIMPLICIT := 0;
           IF (coalesce(V_REC_I.suprascrie_implicit, 0) = 1) THEN
               aIMPLICIT := 1;
               IF (V_REC_C.CODPRETMSI &gt; 0) AND (V_REC_C.CODPRETMSI &lt;&gt; V_REC_C.CODPRETMS) THEN
                 UPDATE PRETM SET IMPLICIT = 0 WHERE CODPRETM = V_REC_C.CODPRETMSI;
               END IF;
           ELSE
             IF V_REC_C.IMPLICIT = 1 AND V_REC_C.CODPRETMSI = 0 THEN
                aIMPLICIT := 1;
             END IF;

           end if;
           IF V_REC_C.CODPRETMS = 0 THEN
             INSERT INTO PRETM(CODPRETM, CODOBIECT, CODCATPRET, LEI, VALUTA, MONEDA, PROC, IMPLICIT, SUBUNITATEA, ROTUNJIRE, GRUPA, SUMAFIXAIMPLICIT)
                       VALUES(NEXTVAL('SEQ_PRETM_CODPRETM'), V_REC_C.CODOBIECT, V_REC_I.CODCATPRET_DEST,  V_REC_C.LEI,
                                    V_REC_C.VALUTA, V_REC_C.MONEDA, V_REC_C.PROC, aIMPLICIT, V_REC_I.CODSUBUNIT_DEST, V_REC_C.ROTUNJIRE,
                                    V_REC_C.GRUPA, V_REC_C.SUMAFIXAIMPLICIT);

           IF aSyncPretRetail = '1' THEN
             PERFORM PKG_POSTRETAIL_MEMO_MODIF_PRET_RETAIL(V_REC_C.CODOBIECT, V_REC_I.CODSUBUNIT_DEST);
           END IF;

           IF aMemoModiPret = '1' THEN
             PERFORM PKG_GLOBALS_MEMO_MODIFICARE_PRET(V_REC_C.CODOBIECT, V_REC_I.CODSUBUNIT_DEST);
           END IF;

         ELSE
           IF V_REC_C.LEI    &lt;&gt; V_REC_C.PMSLEI OR
              V_REC_C.VALUTA &lt;&gt; V_REC_C.PMSVALUTA OR
              V_REC_C.MONEDA &lt;&gt; V_REC_C.PMSMONEDA OR
              aIMPLICIT      &lt;&gt; V_REC_C.PMSIMPLICIT
           THEN
             UPDATE PRETM
             SET
               LEI    = V_REC_C.LEI,
               VALUTA = V_REC_C.VALUTA,
               MONEDA = V_REC_C.MONEDA,
               IMPLICIT = aIMPLICIT
             WHERE
               CODPRETM = V_REC_C.CODPRETMS;

             IF aSyncPretRetail = '1' THEN
               PERFORM PKG_POSTRETAIL_MEMO_MODIF_PRET_RETAIL(V_REC_C.CODOBIECT, V_REC_I.CODSUBUNIT_DEST);
             END IF;

             IF aMemoModiPret = '1' THEN
               PERFORM PKG_GLOBALS_MEMO_MODIFICARE_PRET(V_REC_C.CODOBIECT, V_REC_I.CODSUBUNIT_DEST);
             END IF;

           END IF;

         END IF;
     END LOOP;
   END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_ct_monitor</obj_name>
  <obj_hashval>8306a21c506b073bec9aaeea8fbc356e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_NOM_ARTICOL.CT_MONITOR'));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_6';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_denumire_unica_articol</obj_name>
  <obj_hashval>c6f420f66e4c3d996cdede736c63ee8b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_denumire_unica_articol(INOUT wme_result numeric, INOUT acodarticol numeric, INOUT adenumire character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  SELECT COUNT( *) INTO NR FROM NART WHERE DEN_ARTICOL = aDENUMIRE AND  CODARTICOL &lt;&gt; aCODARTICOL;

  IF  NR = 0 THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    WME_Result :=  0;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_denumire_unica_obiect</obj_name>
  <obj_hashval>74c05009979f0bba872453adfbb81ef3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_denumire_unica_obiect(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT adenumire character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  SELECT COUNT( *) INTO NR FROM NARTOBJ WHERE DENUMIRE = aDENUMIRE AND  CODOBIECT &lt;&gt; aCODOBIECT;

  IF  NR = 0 THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    WME_Result :=  0;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_export_preturi_pe_subunit</obj_name>
  <obj_hashval>3e1cf9b8857e0af055539e5272b3306b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_export_preturi_pe_subunit(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  SUBUNIT_REF numeric;
  IRES        numeric;
begin
  SUBUNIT_REF := (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL));
  IRES := 1;

  BEGIN
    DELETE FROM TMP_PRETM;
    INSERT INTO TMP_PRETM(CODPRETM, CODOBIECT, CODCATPRET, LEI, VALUTA, MONEDA, IMPLICIT, GRUPA, PROC, INDEXLOCAL, SUBUNITATEA, ROTUNJIRE)
    SELECT CODPRETM, CODOBIECT, CODCATPRET, LEI, VALUTA, MONEDA, IMPLICIT, GRUPA, PROC, INDEXLOCAL, SUBUNITATEA, ROTUNJIRE
    FROM PRETM
    WHERE SUBUNITATEA = SUBUNIT_REF;

    DELETE FROM PRETM;

    FOR V_REC IN (SELECT SUB.CODSUBUNIT FROM NSUBUNIT SUB WHERE SUB.CODSUBUNIT &gt; 0) LOOP
      INSERT INTO PRETM(CODPRETM, CODOBIECT, CODCATPRET, LEI, VALUTA, MONEDA, IMPLICIT, GRUPA, PROC, INDEXLOCAL, SUBUNITATEA, ROTUNJIRE)
      SELECT NEXTVAL('SEQ_PRETM_CODPRETM'), CODOBIECT, CODCATPRET, LEI, VALUTA, MONEDA, IMPLICIT, GRUPA, PROC, INDEXLOCAL, V_REC.CODSUBUNIT, ROTUNJIRE
      FROM TMP_PRETM;
    END LOOP;
  EXCEPTION WHEN OTHERS THEN
    IRES := 0;
  END;

  WME_Result :=  IRES;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_exporta_preturi</obj_name>
  <obj_hashval>f499246b2f2f4cf853ed1afb80d45c7f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_exporta_preturi(acodcatimplicita numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC_S RECORD;
  V_REC_C RECORD;
  aCODPRETM       numeric;
  aIMPLICIT       numeric := 0;
  NR              numeric := 0;
  aSyncPretRetail varchar;
  CodSubCurent    numeric;
  aMemoModiPret   varchar;
begin
  --Bogdan 15.05.2023 - 58282 - PG - Export preturi articole pe celelalte subunitati CodSubCurent - numeric
  --Adina 02.02.2021 - aranjat + add aMemoModiPret, dar am comentat liniile 56,73 pt.ca nu exista inca in PG ac.functie
  CodSubCurent := current_setting('PKG_GLOBALS.SUBUNITATE', true) :: numeric;
  BEGIN
    aSyncPretRetail := fnc_GetValConstantaLucru('SyncPretRetail');
  EXCEPTION WHEN OTHERS THEN
    aSyncPretRetail := '0';
  END;

  BEGIN
    aMemoModiPret := fnc_GetValConstantaLucru('MemoModiPret');
  EXCEPTION WHEN OTHERS THEN
    aMemoModiPret := '0';
  END;

  FOR V_REC_S IN (SELECT * FROM TMP_NSUBUNIT) LOOP
    FOR V_REC_C IN (SELECT PMB.*,
                           COALESCE( PMS.CODPRETM, 0)  AS CODPRETMS,
                           COALESCE( PMS.LEI, 0)       AS PMSLEI,
                           COALESCE( PMS.VALUTA, 0)    AS PMSVALUTA,
                           COALESCE( PMS.MONEDA, 0)    AS PMSMONEDA,
                           COALESCE( PMSI.CODPRETM, 0) AS CODPRETMSI
                    FROM PRETM PMB
                         LEFT JOIN PRETM PMS  ON  PMS.CODOBIECT  = PMB.CODOBIECT AND  PMS.CODCATPRET   = PMB.CODCATPRET     AND  PMS.SUBUNITATEA = V_REC_S.CODSUBUNIT
                         LEFT JOIN PRETM PMSI ON  PMSI.CODOBIECT = PMB.CODOBIECT AND  PMSI.SUBUNITATEA = V_REC_S.CODSUBUNIT AND  PMSI.IMPLICIT = 1
                    WHERE PMB.SUBUNITATEA = CODSUBCURENT AND
                          EXISTS (SELECT CODCATPRET FROM TMP_NCATPRET TC WHERE TC.CODCATPRET = PMB.CODCATPRET)
                   )
    LOOP
      IF  V_REC_C.CODPRETMS = 0 THEN
        aIMPLICIT := 0;
        IF  V_REC_C.IMPLICIT = 1 AND  V_REC_C.CODPRETMSI = 0 THEN
          aIMPLICIT := 1;
        END IF;

        INSERT INTO PRETM(CODPRETM, CODOBIECT, CODCATPRET, LEI, VALUTA, MONEDA, PROC, IMPLICIT, SUBUNITATEA, ROTUNJIRE)
        VALUES(NEXTVAL('SEQ_PRETM_CODPRETM'), V_REC_C.CODOBIECT, V_REC_C.CODCATPRET, V_REC_C.LEI, V_REC_C.VALUTA, V_REC_C.MONEDA, V_REC_C.PROC, aIMPLICIT, V_REC_S.CODSUBUNIT, V_REC_C.ROTUNJIRE);

        IF  aSyncPretRetail = '1' THEN
          PERFORM PKG_POSTRETAIL_MEMO_MODIF_PRET_RETAIL( V_REC_C.CODOBIECT, V_REC_S.CODSUBUNIT);
        END IF;

--        IF aMemoModiPret = '1' THEN
--          PERFORM PKG_GLOBALS_MEMO_MODIFICARE_PRET(V_REC_C.CODOBIECT, V_REC_S.CODSUBUNIT);
--        END IF;
      ELSE
        IF  V_REC_C.LEI &lt;&gt; V_REC_C.PMSLEI OR  V_REC_C.VALUTA &lt;&gt; V_REC_C.PMSVALUTA OR  V_REC_C.MONEDA &lt;&gt; V_REC_C.PMSMONEDA THEN
          UPDATE PRETM
          SET
            LEI    = V_REC_C.LEI,
            VALUTA = V_REC_C.VALUTA,
            MONEDA = V_REC_C.MONEDA
          WHERE
           CODPRETM = V_REC_C.CODPRETMS;

          IF  aSyncPretRetail = '1' THEN
            PERFORM PKG_POSTRETAIL_MEMO_MODIF_PRET_RETAIL( V_REC_C.CODOBIECT, V_REC_S.CODSUBUNIT);
          END IF;

--          IF aMemoModiPret = '1' THEN
--            PERFORM PKG_GLOBALS_MEMO_MODIFICARE_PRET(V_REC_C.CODOBIECT, V_REC_S.CODSUBUNIT);
--          END IF;
        END IF;
      END IF;
    END LOOP;
  END LOOP;

  IF  aCODCATIMPLICITA &lt;&gt; 0 THEN
    UPDATE PRETM
    SET
      IMPLICIT = 0
    WHERE CODCATPRET &lt;&gt; aCODCATIMPLICITA AND  SUBUNITATEA &lt;&gt; CodSubCurent;

    UPDATE PRETM
    SET
      IMPLICIT = 1
    WHERE CODCATPRET = aCODCATIMPLICITA AND  SUBUNITATEA &lt;&gt; CodSubCurent;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_getgcodobiect</obj_name>
  <obj_hashval>3a1a0cd2adbe45213ec4023b93652ffc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_getgcodobiect(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOM_ARTICOL.gCodObiect')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_getstrnartobjext</obj_name>
  <obj_hashval>ede543badde874be439a6cd9ba0fe652</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_getstrnartobjext(INOUT wme_result character varying, INOUT dela numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  STRUCT varchar := '';
  NR     numeric := 0;
  I      numeric := 0;
  sFIRMANAME varchar;
BEGIN
  --Adina 02.06.2021 - scos upper + sFIRMANAME
  --Bogdan 21.10.2020
  sFIRMANAME := lower(current_setting('PKG_GLOBALS.FIRMANAME', true));

  SELECT COUNT( *) INTO NR
  FROM information_schema.Columns
  WHERE TABLE_NAME = 'nartobjext' and TABLE_SCHEMA = sFIRMANAME;

  IF  NR &gt; 0 THEN
    FOR V_REC IN
    (    SELECT COLUMN_NAME  FROM information_schema.Columns
        WHERE TABLE_NAME = 'nartobjext' and TABLE_SCHEMA = sFIRMANAME
        ORDER BY ORDINAL_POSITION
    ) LOOP
        I := I + 1;
        IF  I &gt;= DeLa THEN
          STRUCT := STRUCT || V_REC.COLUMN_NAME;
          IF  I &lt; NR THEN
            STRUCT := STRUCT || ',';
          END IF;
        END IF;
    END LOOP;
  END IF;
  WME_Result :=  STRUCT;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_memomodipret</obj_name>
  <obj_hashval>175a5d343396e8daf1ad253b3ac06fce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_memomodipret(acodobiect numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  aVAlue varchar;
BEGIN
  --Adina 02.02.2021
  BEGIN
    SELECT fnc_GetValConstanta('MemoModiPret', getANLUCRU(), getLUNALUCRU()) INTO aValue;
  EXCEPTION WHEN OTHERS THEN
    aValue := '0';
  END;

  IF  aVALUE = '1' THEN
    FOR V_REC IN
    (
      SELECT O.CODOBIECT, PM.LEI AS PRETNOU, PM.CODCATPRET, PM.SUBUNITATEA
      FROM TMP_PRETM PM
           LEFT JOIN PRETM PM_OLD ON PM_OLD.CODOBIECT  = PM.CODOBIECT  AND
                                     PM_OLD.CODCATPRET = PM.CODCATPRET AND
                                     PM_OLD.SUBUNITATEA = PM.SUBUNITATEA,
           NARTOBJ O, NART A, NCATPRET CP
      WHERE
         PM.SUBUNITATEA = getSUBUNITATE() AND
         PM.CODOBIECT   = O.CODOBIECT     AND
         A.CODARTICOL   = O.CODARTICOL    AND
         O.CODOBIECT    = aCODOBIECT      AND
         PM.CODCATPRET  = CP.CODCATPRET   AND
         CP.TIP IN (1, 2)                 AND
         COALESCE(PM_OLD.LEI, 0) &lt;&gt; COALESCE(PM.LEI, 0)
    )
    LOOP
      INSERT INTO MODIFICARIPRET(CODMODIF, CODOBIECT, CODCATPRET, PRETNOU, DATA, SUBUNITATEA)
      VALUES(NEXTVAL('SEQ_MODIFICARIPRET_CODMODIF'), V_REC.CODOBIECT, V_REC.CODCATPRET, V_REC.PRETNOU, CURRENT_TIMESTAMP, V_REC.SUBUNITATEA);
    END LOOP;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_multiplica_preturi</obj_name>
  <obj_hashval>6e9adc9ae0ffa36c2eaf27a7d389e5f1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_multiplica_preturi(acodobiect numeric, acodsubunit numeric, suprascriu_pret_zero numeric, doarcategsursa numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC           RECORD;
  V_REC1          RECORD;
  V_REC_PRETM     RECORD;
  PRET_PROPUS     double precision := 0;
  CATIMPLICITDEST numeric;
  aSyncPretRetail varchar;
begin
  --Adina 02.02.2021 - aranjat
  BEGIN
    SELECT fnc_GetValConstanta('SyncPretRetail', getANLUCRU(), getLUNALUCRU()) INTO aSyncPretRetail;
  EXCEPTION WHEN OTHERS THEN
    aSyncPretRetail := '0';
  END;

  IF  SUPRASCRIU_PRET_ZERO = 1 THEN
    FOR V_REC IN (SELECT CODSUBUNIT FROM NSUBUNIT
                  WHERE (CODSUBUNIT &lt;&gt; ACODSUBUNIT)  AND CODSUBUNIT NOT IN (0, 1) AND CODSUBUNIT IN (SELECT CODUNIC FROM TMP_MANEVRA)
                 )
    LOOP
      BEGIN
        SELECT COALESCE( CODCATPRET, 0) INTO CATIMPLICITDEST
        FROM PRETM
        WHERE SUBUNITATEA = V_REC.CODSUBUNIT AND  CODOBIECT = aCODOBIECT AND  COALESCE( IMPLICIT, 0) = 1;
      EXCEPTION WHEN OTHERS THEN
        CATIMPLICITDEST := 0;
      END;

      IF  COALESCE( DoarCategSursa, 0) = 0 THEN
        DELETE FROM PRETMAMB PAMB
        WHERE EXISTS (SELECT P.CODPRETM FROM PRETM P WHERE P.CODPRETM = PAMB.CODPRETM AND  P.SUBUNITATEA = V_REC.CODSUBUNIT AND  P.CODOBIECT = ACODOBIECT);

        DELETE FROM PRETM WHERE SUBUNITATEA = V_REC.CODSUBUNIT AND  CODOBIECT = ACODOBIECT;
      END IF;

      FOR V_REC1 IN (SELECT * FROM PRETM WHERE CODOBIECT = ACODOBIECT AND  SUBUNITATEA = ACODSUBUNIT) LOOP
        IF  COALESCE( DoarCategSursa, 0) = 1 THEN
          FOR V_REC_PRETM IN (SELECT * FROM PRETM WHERE SUBUNITATEA = V_REC.CODSUBUNIT AND  CODOBIECT = ACODOBIECT AND  CODCATPRET = V_REC1.CODCATPRET) LOOP
            DELETE FROM PRETMAMB WHERE CODPRETM = V_REC_PRETM.CODPRETM;
            DELETE FROM PRETM    WHERE CODPRETM = V_REC_PRETM.CODPRETM;
          END LOOP;
        END IF;

        INSERT INTO PRETM(CODPRETM, CODOBIECT, CODCATPRET, LEI, VALUTA, MONEDA, IMPLICIT, PROC, INDEXLOCAL, SUBUNITATEA)
        VALUES(NEXTVAL('SEQ_PRETM_CODPRETM'), ACODOBIECT, V_REC1.CODCATPRET, V_REC1.LEI, V_REC1.VALUTA, V_REC1.MONEDA, (SELECT PKG_NOM_ARTICOL_ANALIZA_IMPLICIT.WME_RESULT FROM PKG_NOM_ARTICOL_ANALIZA_IMPLICIT(NULL, COALESCE( V_REC1.IMPLICIT, 0), COALESCE( DoarCategSursa, 0), COALESCE( V_REC1.CODCATPRET, 0), COALESCE( CATIMPLICITDEST, 0))), V_REC1.PROC, V_REC1.INDEXLOCAL, V_REC.CODSUBUNIT);

        INSERT INTO PRETMAMB(CODPRETMAMB, CODPRETM, CODAMB, LEI, VALUTA)
        SELECT NEXTVAL('SEQ_PRETMAMB_CODPRETMAMB'), CURRVAL('SEQ_PRETM_CODPRETM'), CODAMB, LEI, VALUTA
        FROM PRETMAMB PAMB WHERE PAMB.CODPRETM = V_REC1.CODPRETM;
      END LOOP;

      IF  aSyncPretRetail = '1' THEN
        PERFORM PKG_POSTRETAIL_MEMO_MODIF_PRET_RETAIL( aCODOBIECT, V_REC.CODSUBUNIT);
      END IF;
    END LOOP;
  ELSE
    FOR V_REC IN (SELECT CODSUBUNIT FROM NSUBUNIT
                  WHERE (CODSUBUNIT &lt;&gt; ACODSUBUNIT) AND CODSUBUNIT NOT IN (0, 1) AND CODSUBUNIT IN (SELECT CODUNIC FROM TMP_MANEVRA )
                 )
    LOOP
      FOR V_REC1 IN (SELECT * FROM PRETM WHERE SUBUNITATEA = V_REC.CODSUBUNIT AND  CODOBIECT = aCODOBIECT) LOOP
        BEGIN
          SELECT COALESCE( CODCATPRET, 0) INTO CATIMPLICITDEST
          FROM PRETM
          WHERE SUBUNITATEA = V_REC.CODSUBUNIT AND  CODOBIECT = aCODOBIECT AND  COALESCE( IMPLICIT, 0) = 1;
        EXCEPTION WHEN OTHERS THEN
          CATIMPLICITDEST := 0;
        END;

        PRET_PROPUS := -1;
        IF  COALESCE( V_REC1.MONEDA, 0) = 0 THEN
          BEGIN
            SELECT LEI INTO PRET_PROPUS FROM PRETM WHERE SUBUNITATEA = aCODSUBUNIT AND  CODOBIECT = ACODOBIECT AND  CODCATPRET = V_REC1.CODCATPRET;
          EXCEPTION WHEN OTHERS THEN
            PRET_PROPUS := -1;
          END;
        ELSE
          BEGIN
            SELECT VALUTA INTO PRET_PROPUS FROM PRETM WHERE SUBUNITATEA = aCODSUBUNIT AND  CODOBIECT = ACODOBIECT AND  CODCATPRET = V_REC1.CODCATPRET;
          EXCEPTION WHEN OTHERS THEN
            PRET_PROPUS := -1;
          END;
        END IF;

        IF  PRET_PROPUS &lt;&gt; 0 THEN
          DELETE FROM PRETM    WHERE CODPRETM = V_REC1.CODPRETM;
          DELETE FROM PRETMAMB WHERE CODPRETM = V_REC1.CODPRETM;
        END IF;
      END LOOP;

      FOR V_REC1 IN (SELECT * FROM PRETM WHERE CODOBIECT = ACODOBIECT AND  SUBUNITATEA = ACODSUBUNIT) LOOP
        IF  COALESCE( V_REC1.MONEDA, 0) = 0 THEN
          PRET_PROPUS := COALESCE( V_REC1.LEI, 0);
        ELSE
          PRET_PROPUS := COALESCE( V_REC1.VALUTA, 0);
        END IF;

        IF  PRET_PROPUS &lt;&gt; 0 THEN
          INSERT INTO PRETM(CODPRETM, CODOBIECT, CODCATPRET, LEI, VALUTA, MONEDA, IMPLICIT, PROC, INDEXLOCAL, SUBUNITATEA)
          VALUES(NEXTVAL('SEQ_PRETM_CODPRETM'), ACODOBIECT, V_REC1.CODCATPRET, V_REC1.LEI, V_REC1.VALUTA, V_REC1.MONEDA, (SELECT PKG_NOM_ARTICOL_ANALIZA_IMPLICIT.WME_RESULT FROM PKG_NOM_ARTICOL_ANALIZA_IMPLICIT(NULL, COALESCE( V_REC1.IMPLICIT, 0), COALESCE( DoarCategSursa, 0), COALESCE( V_REC1.CODCATPRET, 0), COALESCE( CATIMPLICITDEST, 0))), V_REC1.PROC, V_REC1.INDEXLOCAL, V_REC.CODSUBUNIT);

          INSERT INTO PRETMAMB(CODPRETMAMB, CODPRETM, CODAMB, LEI, VALUTA)
          SELECT NEXTVAL('SEQ_PRETMAMB_CODPRETMAMB'), CURRVAL('SEQ_PRETM_CODPRETM'), CODAMB, LEI, VALUTA
          FROM PRETMAMB PAMB
          WHERE PAMB.CODPRETM = V_REC1.CODPRETM;
        END IF;
      END LOOP;

      IF  aSyncPretRetail = '1' THEN
        PERFORM PKG_POSTRETAIL_MEMO_MODIF_PRET_RETAIL( aCODOBIECT, V_REC.CODSUBUNIT);
      END IF;
    END LOOP;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_propaga_preturi_la_subunitati</obj_name>
  <obj_hashval>85d587c52fffe9682cf36bf2a5b5e346</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_propaga_preturi_la_subunitati()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  V_REC_S     RECORD;
  aCODPRETM   numeric;
  NRIMPLICITE numeric;
  aIMPLICIT   numeric;
begin
  --Adina 02.02.2021 - aranjat
  FOR V_REC IN (SELECT * FROM PRETM PM WHERE PM.CODOBIECT IN (SELECT CODUNIC FROM TMP_MANEVRA ) AND  SUBUNITATEA = TO_NUMBER((current_setting('PKG_GLOBALS.SUBUNITATE_DOC', true)),'999999999999999999'))
  LOOP
    FOR V_REC_S IN (SELECT CODSUBUNIT FROM NSUBUNIT WHERE CODSUBUNIT &gt; 1 AND  CODSUBUNIT &lt;&gt; TO_NUMBER((current_setting('PKG_GLOBALS.SUBUNITATE_DOC', true)),'999999999999999999'))
    LOOP
      BEGIN
        SELECT CODPRETM INTO aCODPRETM
        FROM PRETM
        WHERE CODOBIECT = V_REC.CODOBIECT AND  SUBUNITATEA = V_REC_S.CODSUBUNIT AND  CODCATPRET = V_REC.CODCATPRET;
      EXCEPTION WHEN OTHERS THEN
        aCODPRETM := 0;
      END;

      IF  aCODPRETM &lt;&gt; 0 THEN
        UPDATE PRETM
        SET
          CODCATPRET  = V_REC.CODCATPRET,
          LEI         = V_REC.LEI,
          VALUTA      = V_REC.VALUTA,
          MONEDA      = V_REC.MONEDA,
          PROC        = V_REC.PROC,
          SUBUNITATEA = V_REC_S.CODSUBUNIT
        WHERE
         CODPRETM = aCODPRETM;
      ELSE
        aIMPLICIT := 0;
        IF  V_REC.IMPLICIT = 1 THEN
          SELECT COUNT( *) INTO NRIMPLICITE
          FROM PRETM
          WHERE CODOBIECT = V_REC.CODOBIECT AND  SUBUNITATEA = V_REC_S.CODSUBUNIT AND  IMPLICIT = 1;

          IF  NRIMPLICITE &gt; 0 THEN
            aIMPLICIT := 0;
          ELSE
            aIMPLICIT := 1;
          END IF;
        END IF;

        INSERT INTO PRETM(CODPRETM, CODOBIECT, CODCATPRET, LEI, VALUTA, MONEDA, PROC, IMPLICIT, INDEXLOCAL, SUBUNITATEA, ROTUNJIRE)
        VALUES(NEXTVAL('SEQ_PRETM_CODPRETM'), V_REC.CODOBIECT, V_REC.CODCATPRET, V_REC.LEI, V_REC.VALUTA, V_REC.MONEDA, V_REC.PROC, aIMPLICIT, V_REC.INDEXLOCAL, V_REC_S.CODSUBUNIT, V_REC.ROTUNJIRE);
      END IF;
    END LOOP;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_propagaoptionale</obj_name>
  <obj_hashval>298ec9d55d8051bac52744885c77562a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_propagaoptionale(acodsursa numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
  DECLARE
    V_REC RECORD;
  begin
    --Bogdan 26.10.2020
    FOR v_rec IN (SELECT valoare::numeric CODOBIECT
                  FROM tmp_manevra_liste
                  WHERE filtru = 'CODOBIECT' and valoare::numeric &lt;&gt; aCodSursa
                 )
    LOOP
      DELETE FROM nartopt WHERE codobiect = v_rec.codobiect;

      INSERT INTO nartopt (codopt,
          codobiect,
          codobiectopt,
          CodTipLocatie,
          ForceLei,
          standard,
          cant,
          obs)
      SELECT NEXTVAL ('SEQ_NARTOPT_CODOPT') ,
        v_rec.codobiect,
        codobiectopt,
        CodTipLocatie,
        ForceLei,
        standard,
        cant,
        obs
      FROM nartopt
      WHERE
        codobiect = aCodSursa;

      DELETE FROM tmp_nartopt WHERE codobiect = v_rec.codobiect;

      INSERT INTO TMP_NARTOPT (CODOPT,
          CODOBIECT,
          codobiectopt,
          CodTipLocatie,
          ForceLei,
          CANT,
          STANDARD,
          OBS,
          DENOBIECTOPT,
          CODEXTERN,
          CODINTERN,
          SELECTAT)
      (SELECT CODOPT,
            A.CODOBIECT,
            codobiectopt,
            CodTipLocatie,
            ForceLei,
            CANT,
            STANDARD,
            A.OBS,
            O.DENUMIRE,
            O.CODEXTERN,
            O.CODINTERN,
            0
        FROM NARTOPT          A
            LEFT JOIN NARTOBJ O ON O.CODOBIECT = A.codobiectopt
        WHERE
            A.CODOBIECT IN (SELECT CODOBIECT FROM TMP_NARTOBJ)
            AND A.CODOBIECT = V_REC.CODOBIECT
      );

    END LOOP;
  end;
  $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_setgcodobiect</obj_name>
  <obj_hashval>e2c70718c33b7862c7a7acf3ffe5132a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_setgcodobiect(agcodobiect numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOM_ARTICOL.gCodObiect',to_char(agCodObiect,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_sp_deleterecord</obj_name>
  <obj_hashval>893ce0c9d090194400572db768759d37</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC      RECORD;
  V_RECPRETM RECORD;
  aDoc       varchar;
BEGIN
  --Florin 01.06.2023 - monitor
  --Adina 02.02.2021 - aranjat + add linia 56
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_nom_articol_setct_monitor('MON_6');
  PERFORM PKG_NOM_ARTICOL_SP_LOCKRECORD( RecId);

  IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_NOM_ARTICOL.CT_MONITOR', true))))
  THEN
    SELECT 'Articol "' || DEN_ARTICOL || '"' INTO aDoc
    FROM nart
    WHERE codarticol = recid;

    PERFORM pkg_userfirme_postlogcucommit( 'NART', (current_setting('PKG_GLOBALS.USERNAME', true)), 'S', RECID, (current_setting('PKG_GLOBALS.FIRMANAME', true)), TO_NUMBER((current_setting('PKG_GLOBALS.SUBUNITATE', true)),'999999999999999999'), null, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  FOR V_REC IN (SELECT * FROM NARTOBJ WHERE COALESCE( CodArticol, 0) = RecID) LOOP
    FOR V_RECPRETM IN (SELECT * FROM PRETM WHERE CODOBIECT = V_REC.CODOBIECT) LOOP
      DELETE FROM PRETMAMB WHERE CODPRETM = V_RECPRETM.CODPRETM;
      DELETE FROM PRETM    WHERE CODPRETM = V_RECPRETM.CODPRETM;
    END LOOP;

    DELETE FROM NARTAMB  WHERE CODOBIECT = V_REC.CODOBIECT OR  CODOBIECTRETURN = V_REC.CODOBIECT;
    DELETE FROM NARTOPT  WHERE CODOBIECT = V_REC.CODOBIECT OR  codobiectopt    = V_REC.CODOBIECT;
    DELETE FROM NECHIV   WHERE CODOBIECT = V_REC.CODOBIECT;
    DELETE FROM NATROBJ  WHERE CODOBIECT = V_REC.CODOBIECT;
    DELETE FROM NARTOBJ1 WHERE CODOBIECT = V_REC.CODOBIECT;

    IF  (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(NULL, 'NARTOBJEXT')) = 1 THEN
      EXECUTE 'DELETE FROM NARTOBJEXT WHERE CODOBIECT =  ' || TO_CHAR( V_REC.CODOBIECT,'9999999999');
    END IF;

  -- traduceri denumiri obiecte
    DELETE FROM NARTOBJTRAD     WHERE CODOBIECT = V_REC.CODOBIECT;
    DELETE FROM DISCPROMORETAIL WHERE CODOBIECT = V_REC.CODOBIECT;
    DELETE FROM NARTCLI         WHERE CODOBIECT = V_REC.CODOBIECT;
    DELETE FROM NARTOBJSUBUNIT  WHERE CODOBIECT = V_REC.CODOBIECT;
    DELETE FROM NARTOBJCOLET    WHERE CODOBIECT = V_REC.CODOBIECT;
    DELETE FROM CODEXTALT       WHERE CODOBIECT = V_REC.CODOBIECT;
    DELETE FROM CODINTALT       WHERE CODOBIECT = V_REC.CODOBIECT;
    DELETE FROM NSERII          WHERE CODOBIECT = V_REC.CODOBIECT;
    DELETE FROM DISCART         WHERE CODOBIECT = V_REC.CODOBIECT;

    BEGIN  --TABELA DINAMICA PT. LISTE CU VALORILE ANUMITOR ATRIBUTE
      EXECUTE 'DELETE FROM NARTOBJATR WHERE CODOBIECT = ' || V_REC.CODOBIECT;
    EXCEPTION WHEN OTHERS THEN
      NULL;   -- PROBABIL NU EXISTA TABELA
    END;

    DELETE FROM NARTOBJ    WHERE CODOBIECT = V_REC.CODOBIECT;  -- musai la urma
    DELETE FROM NARTOBJIMP WHERE CODOBIECT = V_REC.CODOBIECT;
  END LOOP;

  DELETE FROM NART1         WHERE CodArticol = RecId;
  DELETE FROM NARTIMPLICITE WHERE CodArticol = RecId;
  DELETE FROM NARTATR       WHERE CodArticol = RecId;
  DELETE FROM NARTDIM       WHERE CodArticol = RecId;
  DELETE FROM NART          WHERE CodArticol = RecId;

  INSERT INTO NARTDELETED(CODARTICOL) VALUES(RECID);

  PERFORM NotifyModif( 2, RECID, 'NART');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_sp_insertrecord</obj_name>
  <obj_hashval>ae60f3b702f37d84889dd9072bbc08f7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 12.04.2023 - sinc. Oracle (11.04.2023)
  --Adina 02.02.2021 - aranjat
  PERFORM PKG_CFGTABLES_CHECK_STRUCT_EXTENSIE_X_TIPDOC(501);

  INSERT INTO TMP_NART(CodArticol, ParitateD1, ParitateD2, ParitateD3)
  VALUES(0, 1, 1, 1);

-- Detail DISCOUNT
  INSERT INTO TMP_DISCOUNT(CodDiscount, CodCriteriu)
  SELECT CodDiscount, CodCriteriu
  FROM DISCOUNT;

--Detail DISCINTERVAL
  INSERT INTO TMP_DISCINTERVAL(CodDiscInterval, CodDiscount, LimInf, LimSup, Procent)
  SELECT CodDiscInterval, CodDiscount, LimInf, LimSup, Procent
  FROM DISCINTERVAL
  WHERE CODDISCOUNT IN (SELECT CODDISCOUNT FROM TMP_DISCOUNT);

--actualizez campul DISCOUNTINFO in TMP_DISCOUNT - musai dupa ce am DISCINTERVAL COMPLETAT
  UPDATE TMP_DISCOUNT D
  SET
  DISCOUNTINFO = (SELECT PKG_CRITERIIDISCOUNT_GETDISCINTERVALE.WME_RESULT FROM PKG_CRITERIIDISCOUNT_GETDISCINTERVALE(NULL, D.CODDISCOUNT));
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(501);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_test</obj_name>
  <obj_hashval>302d78e28a7b3da7ecc64fc2dea669e8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_test(operation numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
aRECID numeric;
begin
aRECID := 667;
PERFORM PKG_GLOBALS_SETLUNALUCRU_SIMPLA( 2012, 8);
PERFORM PKG_STOC_GENERARE_FACTURI_make_config_luna();
PERFORM PKG_NOM_ARTICOL_SP_GOTORECORD( aRecID);
PERFORM PKG_NOM_ARTICOL_SP_POSTRECORDS( Operation, aRecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_tmpordinegrupepret</obj_name>
  <obj_hashval>29ed63a626ead36201b64491294653cc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_tmpordinegrupepret()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAn   numeric;
  vLuna numeric;
  pOrd  varchar;
  xDen  varchar;
  xVal  varchar;
  vPos  NUMERIC;
begin
  vAn   := TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU'  , true)),'999999999999999999');
  vLuna := TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999');
  pOrd  := Trim(fnc_GetValConstanta('OrdineGrupePret', vAN, vLUNA));

  DELETE FROM TMP_MANEVRA_LISTE;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_umpletmpstoc</obj_name>
  <obj_hashval>3ddbeeafce214a5c20255a01ed0309b8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_umpletmpstoc()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 15.05.2023 - sinc. Oracle (11.05.2023)
  delete FROM tmp_nartobjsubunit;
  delete FROM tmp_nartobjsubunit_sec;
  insert into tmp_nartobjsubunit_sec(subunitate, densubunit)
  select codsubunit, den_subunit from nsubunit where codsubunit &gt; 1;
  insert into tmp_nartobjsubunit(subunitate, densubunit, codgest, den_gest)
  select s.codsubunit, s.den_subunit, g.codgest, g.den_gest
  from nsubunit s
       inner join ngest g on g.codsubunit = s.codsubunit
  where s.codsubunit &gt; 1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_update_contserv</obj_name>
  <obj_hashval>974f9dca2248fe8106aba5adc27d46a5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_update_contserv()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Adina 18.02.2021
  FOR v_rec IN
  (
    SELECT i1.codintr1, tmp.codplu, i.codintr CODDOC, i.tipdoc
    FROM tmp_nartobj tmp
      INNER JOIN nartobj  o  ON  o.codarticol = tmp.codarticol
      INNER JOIN intrari1 i1 ON  i1.codobiect = o.codobiect
      INNER JOIN intrari  i  ON  i.codintr    = i1.codintr
    WHERE
       i.operat = 1 and  i.anulat = 0 and  i.an * 12 + i.luna = getANLUCRU() * 12 + getLUNALUCRU()
  )
  LOOP
    UPDATE intrari1 SET contserv = v_rec.codplu WHERE codintr1 = v_rec.codintr1;
    UPDATE jurnal1  SET dirty    = 1            WHERE coddoc   = v_rec.coddoc and  tipdoc = v_rec.tipdoc;
  END LOOP;

  FOR v_rec IN
  (
    SELECT i1.codies1, tmp.codplu, i.codies CODDOC, i.tipdoc
    FROM tmp_nartobj tmp
      INNER JOIN nartobj o  ON  o.codarticol = tmp.codarticol
      INNER JOIN iesiri1 i1 ON  i1.codobiect = o.codobiect
      INNER JOIN iesiri  i  ON  i.codies     = i1.codies
    WHERE
       i.operat = 1 and  i.anulat = 0 and  i.an * 12 + i.luna = getANLUCRU() * 12 + getLUNALUCRU()
  )
  LOOP
    UPDATE iesiri1 SET contserv = v_rec.codplu WHERE codies1 = v_rec.codies1;
    UPDATE jurnal1 SET dirty    = 1            WHERE coddoc  = v_rec.coddoc and  tipdoc = v_rec.tipdoc;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_update_nartobjgest</obj_name>
  <obj_hashval>5027c9947679f64b6b19be007d41eba7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_update_nartobjgest(azi numeric, acodgest numeric, acodobiect numeric, astoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCount numeric;
  sSQL   varchar;
begin
  SELECT count(*) INTO aCount FROM nartobjgest WHERE codgest = acodgest and  codobiect = acodobiect;
  IF  aCount = 0 THEN
    INSERT INTO nartobjgest(codobiect, codgest)
    VALUES(acodobiect, acodgest);
  END IF;

  sSQL := 'update nartobjgest set D' || (aZi::INTEGER)::VARCHAR || ' = ' || aStoc || ' where codgest = ' || aCodGest || ' and codobiect = ' || acodobiect;
  EXECUTE sSQL;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_updateduriret</obj_name>
  <obj_hashval>254dd5797490b7ea8d155189caa07f82</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_updateduriret()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_ART    RECORD;
  V_REC    RECORD;
  tmp      numeric;
  aDataDoc date;
  aDoc     varchar;
begin
  --Adina 02.02.2021 - aranjat
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  FOR v_art IN (SELECT codarticol, D1, D2, D3, RelatieUM1 FROM nart WHERE codarticol &gt; 0) LOOP
    FOR v_rec IN (SELECT pc.codprodcomp, pc.DATA DATADOC, 'OBJ:' || o.denumire || ' VER:' || pc.OBS || ' (' || pc.CODPRODCOMP || ')' DOC
                  FROM prodcomp pc
                       INNER JOIN nartobj o ON  o.codobiect = pc.codobiect
                  WHERE EXISTS (SELECT obj.codobiect FROM nartobj obj WHERE pc.codobiect = obj.codobiect and  obj.codarticol = v_art.codarticol)
                 )
    LOOP
      BEGIN
        SELECT CodProdComp INTO Tmp FROM prodcomp WHERE CodProdComp = v_rec.codprodcomp FOR UPDATE NOWAIT;

        IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_NOM_ARTICOL.CT_MONITOR', true))))
        THEN
          PERFORM pkg_userfirme_postlogcucommit( 'PRODCOMP', (current_setting('PKG_GLOBALS.USERNAME', true)), 'M', v_rec.codprodcomp, (current_setting('PKG_GLOBALS.FIRMANAME', true)), (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL)), v_rec.DataDoc, v_rec.Doc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
        END IF;

        UPDATE prodcomp pc
        SET
          D1 = CASE WHEN  v_art.RELATIEUM1 = 0 THEN NULL ELSE v_art.D1 END ,
          D2 = CASE WHEN  v_art.RELATIEUM1 = 0 THEN NULL ELSE v_art.D2 END ,
          D3 = CASE WHEN  v_art.RELATIEUM1 = 0 THEN NULL ELSE v_art.D3 END
        WHERE
         pc.codprodcomp = v_Rec.Codprodcomp;

        UPDATE prodcomp pc
        SET
        cantum1 = round( CASE
                           WHEN v_art.RELATIEUM1 IN (1, 7) AND  COALESCE( v_art.D1, 0) &lt;&gt; 0 THEN cant / v_art.D1
                           WHEN v_art.RELATIEUM1 IN (2, 8) AND  COALESCE( v_art.D1, 0) * COALESCE( v_art.D2, 0) &lt;&gt; 0 THEN cant / (  COALESCE( v_art.D1, 0) * COALESCE( v_art.D2, 0))
                           WHEN v_art.RELATIEUM1 IN (3, 9) AND  COALESCE( v_art.D1, 0) * COALESCE( v_art.D2, 0) * COALESCE( v_art.D3, 0) &lt;&gt; 0 THEN cant / (  COALESCE( v_art.D1, 0) * COALESCE( v_art.D2, 0) * COALESCE( v_art.D3, 0))
                           WHEN v_art.RELATIEUM1 IN (4, 10) THEN cant * COALESCE( v_art.D1, 0)
                           WHEN v_art.RELATIEUM1 IN (5, 11) THEN cant * COALESCE( v_art.D1, 0) * COALESCE( v_art.D2, 0)
                           WHEN v_art.RELATIEUM1 IN (6, 12) THEN cant * COALESCE( v_art.D1, 0) * COALESCE( v_art.D2, 0) * COALESCE( v_art.D3, 0)
                           ELSE NULL
                         END , 7)
        WHERE EXISTS (SELECT obj.codobiect FROM nartobj obj WHERE pc.codobiect = obj.codobiect and  obj.codarticol = v_art.codarticol);

        PERFORM NotifyModif( 0, v_rec.codprodcomp, 'PRODCOMP');
      EXCEPTION WHEN others THEN
        --&lt;sstunknown&gt;
      END;
    END LOOP;

    FOR v_rec IN (SELECT pm.codprodcomp, pm.codmat, pc.DATA DATADOC, 'OBJ:' || o.denumire || ' VER:' || pc.OBS || ' (' || pc.CODPRODCOMP || ')' DOC
                  FROM prodmat pm
                       INNER JOIN prodcomp pc ON  pc.codprodcomp = pm.codprodcomp
                       INNER JOIN nartobj o ON  o.codobiect = pc.codobiect
                  WHERE EXISTS (SELECT obj.codobiect FROM nartobj obj WHERE pm.codobiect = obj.codobiect and  obj.codarticol = v_art.codarticol)
                 )
    LOOP
      BEGIN
        SELECT CodProdComp INTO Tmp FROM prodcomp WHERE CodProdComp = v_rec.codprodcomp FOR UPDATE NOWAIT;

        IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_NOM_ARTICOL.CT_MONITOR', true))))
        THEN
          PERFORM pkg_userfirme_postlogcucommit( 'PRODCOMP', (current_setting('PKG_GLOBALS.USERNAME', true)), 'M', v_rec.codprodcomp, (current_setting('PKG_GLOBALS.FIRMANAME', true)), (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL)), v_rec.DataDoc, v_rec.Doc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
        END IF;

        UPDATE prodmat pc
        SET
          D1 = CASE WHEN  v_art.RELATIEUM1 = 0 THEN NULL ELSE v_art.D1 END ,
          D2 = CASE WHEN  v_art.RELATIEUM1 = 0 THEN NULL ELSE v_art.D2 END ,
          D3 = CASE WHEN  v_art.RELATIEUM1 = 0 THEN NULL ELSE v_art.D3 END
        WHERE
         codmat = v_rec.codmat;

        UPDATE prodmat pc
        SET
        cantum1 = round( CASE
         WHEN v_art.RELATIEUM1 IN (1, 7) AND  COALESCE( v_art.D1, 0) &lt;&gt; 0 THEN cant / v_art.D1
         WHEN v_art.RELATIEUM1 IN (2, 8) AND  COALESCE( v_art.D1, 0) * COALESCE( v_art.D2, 0) &lt;&gt; 0 THEN cant / (  COALESCE( v_art.D1, 0) * COALESCE( v_art.D2, 0))
         WHEN v_art.RELATIEUM1 IN (3, 9) AND  COALESCE( v_art.D1, 0) * COALESCE( v_art.D2, 0) * COALESCE( v_art.D3, 0) &lt;&gt; 0 THEN cant / (  COALESCE( v_art.D1, 0) * COALESCE( v_art.D2, 0) * COALESCE( v_art.D3, 0))
         WHEN v_art.RELATIEUM1 IN (4, 10) THEN cant * COALESCE( v_art.D1, 0)
         WHEN v_art.RELATIEUM1 IN (5, 11) THEN cant * COALESCE( v_art.D1, 0) * COALESCE( v_art.D2, 0)
         WHEN v_art.RELATIEUM1 IN (6, 12) THEN cant * COALESCE( v_art.D1, 0) * COALESCE( v_art.D2, 0) * COALESCE( v_art.D3, 0)
         ELSE NULL
         END , 7)
        WHERE
         codmat = v_rec.codmat;

        PERFORM NotifyModif( 0, v_rec.codprodcomp, 'PRODCOMP');
      EXCEPTION WHEN others THEN
        --&lt;sstunknown&gt;
      END;
    END LOOP;

    FOR v_rec IN (SELECT pm.codprodcomp, pm.codrez, pc.DATA DATADOC, 'OBJ:' || o.denumire || ' VER:' || pc.OBS || ' (' || pc.CODPRODCOMP || ')' DOC
                  FROM prodrez pm
                       INNER JOIN prodcomp pc ON  pc.codprodcomp = pm.codprodcomp
                       INNER JOIN nartobj o ON  o.codobiect = pc.codobiect
                  WHERE EXISTS (SELECT obj.codobiect FROM nartobj obj WHERE pm.codobiect = obj.codobiect and  obj.codarticol = v_art.codarticol)
                 )
    LOOP
      BEGIN
        SELECT CodProdComp INTO Tmp FROM prodcomp WHERE CodProdComp = v_rec.codprodcomp FOR UPDATE NOWAIT;

        IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_NOM_ARTICOL.CT_MONITOR', true))))
        THEN
          PERFORM pkg_userfirme_postlogcucommit( 'PRODCOMP', (current_setting('PKG_GLOBALS.USERNAME', true)), 'M', v_rec.codprodcomp, (current_setting('PKG_GLOBALS.FIRMANAME', true)), (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL)), v_rec.DataDoc, v_rec.Doc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
        END IF;

        UPDATE prodrez pc
        SET
          D1 = CASE WHEN  v_art.RELATIEUM1 = 0 THEN NULL ELSE v_art.D1 END ,
          D2 = CASE WHEN  v_art.RELATIEUM1 = 0 THEN NULL ELSE v_art.D2 END ,
          D3 = CASE WHEN  v_art.RELATIEUM1 = 0 THEN NULL ELSE v_art.D3 END
        WHERE
         codrez = v_rec.codrez;

        UPDATE prodrez pc
        SET
        cantum1 = round( CASE
         WHEN v_art.RELATIEUM1 IN (1, 7) AND  COALESCE( v_art.D1, 0) &lt;&gt; 0 THEN cant / v_art.D1
         WHEN v_art.RELATIEUM1 IN (2, 8) AND  COALESCE( v_art.D1, 0) * COALESCE( v_art.D2, 0) &lt;&gt; 0 THEN cant / (  COALESCE( v_art.D1, 0) * COALESCE( v_art.D2, 0))
         WHEN v_art.RELATIEUM1 IN (3, 9) AND  COALESCE( v_art.D1, 0) * COALESCE( v_art.D2, 0) * COALESCE( v_art.D3, 0) &lt;&gt; 0 THEN cant / (  COALESCE( v_art.D1, 0) * COALESCE( v_art.D2, 0) * COALESCE( v_art.D3, 0))
         WHEN v_art.RELATIEUM1 IN (4, 10) THEN cant * COALESCE( v_art.D1, 0)
         WHEN v_art.RELATIEUM1 IN (5, 11) THEN cant * COALESCE( v_art.D1, 0) * COALESCE( v_art.D2, 0)
         WHEN v_art.RELATIEUM1 IN (6, 12) THEN cant * COALESCE( v_art.D1, 0) * COALESCE( v_art.D2, 0) * COALESCE( v_art.D3, 0)
         ELSE NULL
         END , 7)
        WHERE
         codrez = v_rec.codrez;

        PERFORM NotifyModif( 0, v_rec.codprodcomp, 'PRODCOMP');
      EXCEPTION WHEN others THEN
        --&lt;sstunknown&gt;
      END;
    END LOOP;

    FOR v_rec IN (SELECT pm.codprodcomp, pm.codnormemat, pc.DATA DATADOC, 'OBJ:' || o.denumire || ' VER:' || pc.OBS || ' (' || pc.CODPRODCOMP || ')' DOC
                  FROM normemat pm
                       INNER JOIN prodcomp pc ON  pc.codprodcomp = pm.codprodcomp
                       INNER JOIN nartobj  o  ON  o.codobiect = pc.codobiect
                  WHERE EXISTS (SELECT obj.codobiect FROM nartobj obj WHERE pm.codobiect = obj.codobiect and  obj.codarticol = v_art.codarticol)
                 )
    LOOP
      BEGIN
        IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_NOM_ARTICOL.CT_MONITOR', true))))
        THEN
          PERFORM pkg_userfirme_postlogcucommit( 'PRODCOMP', (current_setting('PKG_GLOBALS.USERNAME', true)), 'M', v_rec.codprodcomp, (current_setting('PKG_GLOBALS.FIRMANAME', true)), (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL)), v_rec.DataDoc, v_rec.Doc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
        END IF;

        SELECT CodProdComp INTO Tmp FROM prodcomp WHERE CodProdComp = v_rec.codprodcomp FOR UPDATE NOWAIT;

        UPDATE normemat pc
        SET
          D1 = CASE WHEN  v_art.RELATIEUM1 = 0 THEN NULL ELSE v_art.D1 END ,
          D2 = CASE WHEN  v_art.RELATIEUM1 = 0 THEN NULL ELSE v_art.D2 END ,
          D3 = CASE WHEN  v_art.RELATIEUM1 = 0 THEN NULL ELSE v_art.D3 END
        WHERE
         codnormemat = v_rec.codnormemat;

        UPDATE normemat pc
        SET
        cantum1 = round( CASE
         WHEN v_art.RELATIEUM1 IN (1, 7) AND  COALESCE( v_art.D1, 0) &lt;&gt; 0 THEN cant / v_art.D1
         WHEN v_art.RELATIEUM1 IN (2, 8) AND  COALESCE( v_art.D1, 0) * COALESCE( v_art.D2, 0) &lt;&gt; 0 THEN cant / (  COALESCE( v_art.D1, 0) * COALESCE( v_art.D2, 0))
         WHEN v_art.RELATIEUM1 IN (3, 9) AND  COALESCE( v_art.D1, 0) * COALESCE( v_art.D2, 0) * COALESCE( v_art.D3, 0) &lt;&gt; 0 THEN cant / (  COALESCE( v_art.D1, 0) * COALESCE( v_art.D2, 0) * COALESCE( v_art.D3, 0))
         WHEN v_art.RELATIEUM1 IN (4, 10) THEN cant * COALESCE( v_art.D1, 0)
         WHEN v_art.RELATIEUM1 IN (5, 11) THEN cant * COALESCE( v_art.D1, 0) * COALESCE( v_art.D2, 0)
         WHEN v_art.RELATIEUM1 IN (6, 12) THEN cant * COALESCE( v_art.D1, 0) * COALESCE( v_art.D2, 0) * COALESCE( v_art.D3, 0)
         ELSE NULL
         END , 7)
        WHERE
         codnormemat = v_rec.codnormemat;

        PERFORM NotifyModif( 0, v_rec.codprodcomp, 'PRODCOMP');
      EXCEPTION WHEN others THEN
        --&lt;sstunknown&gt;
      END;
    END LOOP;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_updateimpsubunit</obj_name>
  <obj_hashval>fe933d0472f5bfafe4c6d516ee34efdf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_updateimpsubunit()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  V_XXX RECORD;
BEGIN
  --Florin 09.04.2021 - fixat 47025
  FOR v_rec IN (SELECT codsubunit FROM nsubunit WHERE codsubunit &gt; 1) LOOP
    FOR v_xxx IN (SELECT COALESCE( imp.codsubunit, 0) CODSUBUNIT, obj.codarticol
                  FROM nartobj obj
                       LEFT JOIN nartimplicite imp ON  obj.codarticol = imp.codarticol and  imp.codsubunit = v_rec.codsubunit
                  WHERE obj.CODOBIECT::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODOBIECT')
                )
    LOOP
      IF  v_xxx.codsubunit = 0 THEN
        INSERT INTO nartimplicite(codimplicit, codarticol, codsubunit)
        VALUES(NEXTVAL('SEQ_NARTIMPLICITE_CODIMPLICIT'), v_xxx.codarticol, v_rec.codsubunit);
      END IF;
    END LOOP;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_updatenart1integer</obj_name>
  <obj_hashval>0d6dd87cb2e0460e0c67a603f1236ddf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_updatenart1integer(camp character varying, valoare numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
  DECLARE
    V_REC      RECORD;
    sString    varchar;
    vRecId     numeric;
    execString varchar;
  begin
    --Florin 05.08.2025 - sinc. Oracle
    --Bogdan 01.11.2023 - getAnLucru, getLunaLucru
    --Florin 29.08.2023 - sinc. Oracle
    --Florin 08.01.2022 - sinc. Oracle (29.12.2021)
    --Florin 24.06.2021 - 50627
    --Adina 10.03.2021 - add prc_al_refresh
    --Bogdan 22.1.2021
    sString := 'UPDATE Nart1 SET '||Camp||' = '||valoare||' WHERE codarticol1 = ';
  FOR v_rec in (
    SELECT distinct a1.codarticol1, a1.codarticol, a1.codtva, a1.codaccize, a1.TaxCode, a1.codtaxa1, a1.codtaxa2, a1.CodAccizeDVI, a1.anstart, a1.lunastart
    FROM NARTOBJ O INNER JOIN NART1 A1 ON A1.CODARTICOL = O.CODARTICOL
    WHERE O.CODOBIECT::varchar IN (SELECT tmp.VALOARE FROM TMP_MANEVRA_LISTE tmp WHERE FILTRU = 'CODOBIECT')
      AND getanlucru()*12+getanlunalucru() BETWEEN a1.alstart AND a1.alstop
  ) LOOP
    if v_rec.CodArticol1 &gt; 0 then
      IF v_rec.anstart*12+v_rec.lunastart &lt;&gt; GetANLUCRU()*12+GetlunaLUCRU() THEN
        vRecId := NEXTVAL('seq_nart1_codarticol1');
        INSERT INTO nart1 (codarticol1, codarticol, codtva, codaccize, TaxCode, codtaxa1, codtaxa2, anstart, lunastart, CodAccizeDVI)
        VALUES (vRecID, v_Rec.codarticol, v_Rec.codtva, v_Rec.codaccize, v_Rec.TaxCode, v_Rec.codtaxa1, v_Rec.codtaxa2, getanlucru(), getlunalucru(), v_Rec.CodAccizeDVI);
      ELSE
        vRecId := v_rec.CodArticol1;
      END IF;
    end if;

      execString := sString||vRecId::varchar;
      EXECUTE execString;

      CALL PRC_AL_REFRESH('nart1', v_Rec.codarticol);
    END LOOP;
  end;
  $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_updatenartobj1string</obj_name>
  <obj_hashval>e922176d8363e955bb8cb4e5579cf87c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_updatenartobj1string(camp character varying, pvaloare character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
  DECLARE
    V_REC   RECORD;
    sString varchar;
  BEGIN
    --Florin 22.11.2024 - sinc. Oracle
    --Adina 12.03.2021 - prc_al_refresh
    FOR v_rec IN (SELECT obj1.*
                  FROM nartobj1 obj1 INNER JOIN TMP_MANEVRA_LISTE tmp ON VALOARE::numeric = obj1.CODOBIECT AND FILTRU = 'CODOBIECT'
                  WHERE getanlucru()*12 + getlunalucru() BETWEEN obj1.alstart AND obj1.alstop
                    AND getanlucru()   &lt;&gt; anstart
                    AND GetlunaLUCRU() &lt;&gt; lunastart
                  ORDER BY obj1.codobiect
                 )
    LOOP
      INSERT INTO nartobj1 (
        codobiect1, codobiect, pretmaximal, procadaosmaximal, adaosla,
        anstart, lunastart, tippretmax, compensat, tipcompensare,
        grupa, uplift, codmoneda, puncte, umiditate, corpuri_straine, incoltit,
        hectolitrica, gluten, fuzaritate, cadere, deformare, sticlozitate, sparturi,
        punctesectie, proteina, aflatoxina, atac_plosnita, continut_ulei, aciditate,
        sistave, refractie, indice_w, toxina_don, boabe_toxice, pretprod)
      VALUES (
        NEXTVAL ('SEQ_NARTOBJ1_CODOBIECT1') , v_Rec.codobiect, v_Rec.pretmaximal, v_Rec.procadaosmaximal,
        v_Rec.adaosla, GetANLUCRU() , GetLunaLUCRU() , v_Rec.tippretmax, v_Rec.compensat, v_Rec.tipcompensare,
        v_Rec.grupa, v_Rec.uplift, v_Rec.codmoneda, v_Rec.puncte,
        v_Rec.umiditate, v_Rec.corpuri_straine, v_Rec.incoltit, v_Rec.hectolitrica,
        v_Rec.gluten, v_Rec.fuzaritate, v_Rec.cadere, v_Rec.deformare,
        v_Rec.sticlozitate, v_Rec.sparturi, v_Rec.punctesectie, v_Rec.proteina,
        v_Rec.aflatoxina, v_Rec.atac_plosnita, v_Rec.continut_ulei, v_Rec.aciditate,
         v_Rec.sistave, v_Rec.refractie, v_Rec.indice_w, v_Rec.toxina_don, v_Rec.boabe_toxice, v_rec.pretprod);

      CALL prc_al_refresh('nartobj1', v_Rec.codobiect);
    END LOOP;

    FOR v_rec IN (SELECT obj1.codobiect1
                  FROM nartobj1 obj1 INNER JOIN TMP_MANEVRA_LISTE ON VALOARE::numeric = obj1.CODOBIECT AND FILTRU = 'CODOBIECT'
                  WHERE getanlucru()*12+getlunalucru() BETWEEN obj1.alstart AND obj1.alstop
                  ORDER BY obj1.codobiect
                 )
    LOOP
      sString := 'update nartobj1 set ' || Camp || ' = ' || coalesce(pValoare,'') || ' where codobiect1 = ' || v_Rec.codobiect1;
      EXECUTE sString;
    END LOOP;
  end;
  $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_verifica_obiect_existent</obj_name>
  <obj_hashval>cb3d5bdadb8a469f5e224fa51af1e9fc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_verifica_obiect_existent(INOUT wme_result numeric, INOUT acodarticol numeric, acodatribut numeric, acodprodus numeric, OUT vcodatribut numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  V_TMP record;
  NR1 numeric;
  NR2 numeric;
BEGIN
  vcodatribut := aCodAtribut;
  FOR V_REC IN (SELECT  DISTINCT CODOBIECT FROM NARTOBJ WHERE CODARTICOL = aCOdARTICOL) LOOP
    SELECT COUNT(*) INTO NR1 FROM (SELECT CODUNIC FROM TMP_MANEVRA
                                   EXCEPT
                                   SELECT ATROBJ.CODVALATR FROM NARTATR ATR INNER JOIN NATROBJ ATROBJ ON  ATR.CODARTATR = ATROBJ.CODARTATR
                                   WHERE ATROBJ.CODOBIECT = V_REC.CODOBIECT
                                  ) A_PG;

    SELECT COUNT(*) INTO NR2 FROM (SELECT ATROBJ.CODVALATR FROM NARTATR ATR INNER JOIN NATROBJ ATROBJ ON  ATR.CODARTATR = ATROBJ.CODARTATR
                                   WHERE ATROBJ.CODOBIECT = V_REC.CODOBIECT
                                   EXCEPT
                                   SELECT CODUNIC FROM TMP_MANEVRA
                                  ) B_PG;
  IF  NR1 + NR2 = 0 then
    if aCodAtribut = 0 then
      wme_result := V_REC.CODOBIECT;
     return;
    else
      FOR V_TMP IN (
        SELECT PN.CODATRIBUT
        FROM NATROBJ N
             INNER JOIN NARTATR PN ON PN.CODARTATR = N.CODARTATR
             INNER JOIN TMP_MANEVRA T ON T.CODUNIC = N.CODVALATR
             INNER JOIN NATRIB1 NB1 ON NB1.CODVALATR = N.CODVALATR
             INNER JOIN NATRIB1 NP1 ON NP1.VALOARE = NB1.VALOARE
             INNER JOIN NATROBJ P ON NP1.CODVALATR = P.CODVALATR
             INNER JOIN NARTATR PA ON PA.CODARTATR = P.CODARTATR
        WHERE PA.CODATRIBUT = aCodAtribut AND P.CODOBIECT = aCodProdus AND N.CODOBIECT = V_REC.CODOBIECT
      ) loop
        vcodatribut := v_tmp.codatribut;
        WME_Result :=  V_REC.CODOBIECT;
        RETURN;
      END LOOP;
    end if;
    END IF;
  END LOOP;
  WME_Result :=  -1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_parcaut_auto_implicat_in_tranzactii</obj_name>
  <obj_hashval>57b2a56d9aca07da3fad337df3b80352</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_parcaut_auto_implicat_in_tranzactii(INOUT wme_result numeric, INOUT acodauto numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
BEGIN
  --Florin 20.05.2025 - sinc. Oracle
  NR := pkg_nom_parcaut_CHECK_TABLE_FOR_AUTO( 'INTRARI', aCODAUTO);
  IF  NR &gt; 0 THEN
    WME_Result :=  1;
    RETURN;
  END IF;

  NR := pkg_nom_parcaut_CHECK_TABLE_FOR_AUTO( 'IESIRI', aCODAUTO);
  IF  NR &gt; 0 THEN
    WME_Result :=  1;
    RETURN;
  END IF;

  NR := pkg_nom_parcaut_CHECK_TABLE_FOR_AUTO( 'INTRARI1', aCODAUTO);
  IF  NR &gt; 0 THEN
    WME_Result :=  1;
    RETURN;
  END IF;

  NR := pkg_nom_parcaut_CHECK_TABLE_FOR_AUTO( 'IESIRI1', aCODAUTO);
  IF  NR &gt; 0 THEN
    WME_Result :=  1;
    RETURN;
  END IF;

  NR := pkg_nom_parcaut_CHECK_TABLE_FOR_AUTO( 'COMANDA', aCODAUTO, 'MIJLTRANSP');
  IF  NR &gt; 0 THEN
    WME_Result :=  1;
    RETURN;
  END IF;

  NR := pkg_nom_parcaut_CHECK_TABLE_FOR_AUTO( 'CONTRACT1', aCODAUTO);
  IF  NR &gt; 0 THEN
    WME_Result :=  1;
    RETURN;
  END IF;

  NR := pkg_nom_parcaut_CHECK_TABLE_FOR_AUTO('COMANDA2', aCODAUTO, 'CODNPARCAUT');
  IF  NR &gt; 0 THEN
    WME_Result :=  1;
    RETURN;
  END IF;

  WME_Result :=  0;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_parcaut_check_table_for_auto</obj_name>
  <obj_hashval>f4ba1fdd3d8efdf3858b1bb1e7779c39</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_parcaut_check_table_for_auto(atablename character varying, acodauto numeric, afldname character varying DEFAULT 'CODAUTO'::character varying)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
BEGIN
  --Florin 22.05.2025 - fixat 65712
  EXECUTE 'SELECT COUNT(*) FROM ' || aTABLENAME || ' WHERE ' || aFLDNAME::varchar || ' = ' || trim(TO_CHAR(aCODAUTO,'9999999999')) INTO NR;
  RETURN NR;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_parcaut_check_table_for_auto</obj_name>
  <obj_hashval>83b138ac2d0fdf6d76aa2329ed525e01</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_parcaut_check_table_for_auto(INOUT wme_result numeric, INOUT atablename character varying, INOUT acodauto numeric, INOUT afldname character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
BEGIN
  --Florin 22.05.2025 - fixat 65712
  EXECUTE 'SELECT COUNT(*) FROM ' || aTABLENAME || ' WHERE ' || aFLDNAME::varchar || ' = ' || trim(TO_CHAR(aCODAUTO,'9999999999')) INTO NR;
  WME_Result :=  NR;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_parcaut_ct_monitor</obj_name>
  <obj_hashval>70a122a96c10e23c5ceee551f293a6af</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_parcaut_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_NOM_PARCAUT.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_72';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_parcaut_empty_nparcaut_temptables</obj_name>
  <obj_hashval>662f34820db9d2a96e21dbc359a04f09</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_parcaut_empty_nparcaut_temptables(ptipprel numeric, sdataref character varying, ptipdataref numeric, plocalit numeric, pclasa numeric, pagent numeric, pioart numeric, pgest numeric, sdatafact character varying, ppersoanafizica numeric, ptipsediu numeric, ptraseu numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 26.05.2022
    Delete FROM TMP_NPARCAUT;
    Delete FROM TMP_NPARcG;
    Delete FROM TMP_NPARc0;
    Delete FROM TMP_NPARc1;
    Delete FROM TMP_NPARc2;
    Delete FROM TMP_NPARc3;
    Delete FROM TMP_NPARCCOM;
    Delete FROM TMP_NPARCCOM1;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_parcaut_getultimacitire</obj_name>
  <obj_hashval>88a7790aaaa5e432bb529daf127544b7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_parcaut_getultimacitire(INOUT wme_result numeric, INOUT acodnparcaut numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  V_REC0 RECORD;
  aRez   numeric;
begin
  aRez := 0;
  FOR v_rec IN (SELECT databord FROM nparc0 WHERE codnparcaut = acodnparcaut ORDER BY databord desc) LOOP
    FOR v_rec0 IN (SELECT codnparc0 FROM nparc0 WHERE databord = v_rec.databord and  codnparcaut = acodnparcaut ORDER BY codnparc0 desc) LOOP
      aRez := v_rec0.codnparc0;
      WME_Result :=  aRez;
      RETURN;
    END LOOP;
  END LOOP;

  WME_Result :=  aRez;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_parcaut_setct_monitor</obj_name>
  <obj_hashval>3113b7f68c7914ab2a452ccb403a58ab</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_parcaut_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOM_PARCAUT.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_parcaut_sp_deleterecord</obj_name>
  <obj_hashval>47293a5d5b6268a26cb44e9d2fb7f088</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_parcaut_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDoc varchar;
BEGIN
  --Florin 20.05.2025 - sinc. Oracle
  --Florin 31.10.2023 - sinc. Oracle
  --Florin 01.06.2023 - monitor
  perform pkg_nom_parcaut_setct_monitor('MON_72');
  PERFORM PKG_CFGTABLES_EXT_DELETERECORD (recId, 505);
  PERFORM PKG_NOM_PARCAUT_SP_LOCKRECORD( RecId);

  SELECT 'Nr.auto: ' || NrInreg INTO aDoc FROM nparcAut WHERE CodnparcAut = recid;

  PERFORM ValidPostLog( 'MON_72', 'S', recid, getsubunitate() , null, aDoc);

  UPDATE MIFIX1 SET CODAUTO = NULL WHERE CODAUTO = RECID;

  DELETE FROM NPARC0   WHERE CodNPArcAUT = RecId;
  DELETE FROM NPARCG   WHERE CodNPArcAUT = RecId;
  DELETE FROM NPARC1   WHERE Cod = RecId;
  DELETE FROM NPARC2   WHERE Cod = RecId;
  DELETE FROM NPARC3   WHERE Cod = RecId;
  DELETE FROM COMANDA3 C3 WHERE C3.CodComanda2 in (Select C2.CodComanda2 from Comanda2 C2 where C2.CodNParcAut = recid);
  DELETE FROM COMANDA2 WHERE CodNParcAut = recid;
  DELETE FROM NPARCAUT WHERE CodNParcAut = RecId;

  PERFORM NotifyModif( 2, RECID, 'NPARCAUT');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_parcaut_sp_insertrecord</obj_name>
  <obj_hashval>41fc479a1b383b7a109289fcc5c9241e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_parcaut_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 31.10.2023 - sinc. Oracle
  INSERT INTO TMP_NPARCAUT(CodNParcAut) VALUES(0);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(505);


end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_parcaut_sp_lockrecord</obj_name>
  <obj_hashval>0eea5cc8a3a4e2f92cfe5e8946f5a9ba</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_parcaut_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodNParcAut INTO Tmp FROM NPARCAUT WHERE CodNParcAut = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_parcaut_test</obj_name>
  <obj_hashval>c6427de18c79626f8ae8bb66365a9b44</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_parcaut_test()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  cod numeric;
begin
  DELETE FROM TMP_NPARCAUT;
  DELETE FROM TMP_NPARcG;
  DELETE FROM TMP_NPARc0;
  DELETE FROM TMP_NPARc1;
  DELETE FROM TMP_NPARc2;
  DELETE FROM TMP_NPARc3;
  DELETE FROM TMP_NPARCCOM;
  DELETE FROM TMP_NPARCCOM1;

  SELECT count( *) INTO cod FROM nparcaut WHERE codnparcaut = 149;
  IF  Cod = 1 THEN
    PERFORM PKG_NOM_PARCAUT_SP_GOTORECORD( 149);
    PERFORM PKG_NOM_PARCAUT_SP_POSTRECORDS( 0, cod);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_parcaut_update_auto</obj_name>
  <obj_hashval>2126c33f14e5b9477b0e429f5e345e16</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_parcaut_update_auto()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  aCod      numeric(20);
  vcodmodel NUMERIC(20);
  vcodmarca NUMERIC(20);
BEGIN
  --Florin 19.09.2025 - fixat 66715
  --Florin 30.09.2024 - from dual
  --Florin 20.08.2024 - sinc. Oracle
  --Florin 26.05.2022 - sinc. Oracle
  --Florin 30.10.2020
  BEGIN
  for v_rec in (select * from tmp_nparcaut_man) loop
    vCodmodel := 0;
    if Length(v_rec.den_model) &gt; 0 then
      begin
        select CODMODELEAUTO into vcodmodel from nmodeleauto where model = v_rec.den_model;
        exception when others then
          select Nextval('seq_nmodeleauto_codmodeleauto') into vcodmodel;
          insert into nmodeleauto(codmodeleauto,model)
          values(vcodmodel, v_rec.den_model);
      end;
    end if;
    vcodmarca := 0;
    if Length(v_rec.den_model) &gt; 0 then
      begin
        select CODMARCIAUTO into vcodmarca from nmarciauto where marca = v_rec.den_marca;
        exception when others then
          select Nextval('seq_nmarciauto_CODMARCIAUTO') into vcodmarca;
          insert into nmarciauto(CODMARCIAUTO,marca)
          values(vcodmarca, v_rec.den_marca);
      end;
    end if;
    DELETE FROM tmp_nparcaut;
    Delete FROM TMP_NPARcG;
    DELETE FROM TMP_NPARc0;
    Delete FROM TMP_NPARc1;
    Delete FROM TMP_NPARc2;
    Delete FROM TMP_NPARc3;
    Delete FROM TMP_NPARCCOM;
    Delete FROM TMP_NPARCCOM1;
    INSERT INTO tmp_nparcaut(NrInreg, Marca, Model, CodArt, SerieC, SerieM, Cilindree, MasaM, LocT, PartLeas, AnF, RataRCA, RataCASCO, RataLEAS, NrContr, Transmisie, Tractiune, LimitaKm, CodDealer, CuloareC, CodGest)
    values (v_rec.NrInreg,vCodMarca,vCodModel,v_rec.CodArt,v_rec.SerieC,v_rec.SerieM,v_rec.Cilindree,v_rec.MasaM,
    v_rec.LocT, v_rec.PartLeas, v_rec.AnF, v_rec.RataRCA, v_rec.RataCASCO, v_rec.RataLEAS, v_rec.NrContr, v_rec.Transmisie, v_rec.Tractiune, v_rec.LimitaKm, v_rec.CodDealer, v_rec.CuloareC, v_rec.CodGest);
    PERFORM pkg_nom_parcaut_SP_POSTRECORDS(1, aCod);
  END LOOP;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_parcaut_update_bordauto</obj_name>
  <obj_hashval>001e6921b94743387cd8440881e2600c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_parcaut_update_bordauto()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 26.05.2022 - sinc. Oracle
  insert into nparc0(codnparc0,codnparcaut,databord,kmbord,an,luna,obs,codpers)
  select nextval('seq_nparc0_codnparc0'), codnparcaut,databord,kmbord,extract(year from databord),extract(month from databord),obs,codpers
  from tmp_nparc0_man;

  delete from tmp_nparc0_man;
  delete FROM tmp_nparc0_man;
--  commit;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomactivit_ct_monitor</obj_name>
  <obj_hashval>add098f549869699589bc679574a0873</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomactivit_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_NOMACTIVIT.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_7';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomactivit_getct_monitor</obj_name>
  <obj_hashval>827e09098d97ab482efb574d5fe137c4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomactivit_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_NOMACTIVIT.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_7';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomactivit_sp_deleterecord</obj_name>
  <obj_hashval>9a08f4a782181dd323f406c74adb639b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomactivit_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  AdoC varchar;
BEGIN
  --Florin 01.06.2023 - monitor
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_nomactivit_setct_monitor('MON_7');
  IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_NOMACTIVIT.CT_MONITOR', true))))
  THEN
    SELECT 'activitate "' || n.den_activit || '"' INTO aDoc FROM NACTIVIT n WHERE N.CODACTIVIT = RECID;
    PERFORM pkg_userfirme_postlogcucommit( 'NACTIVIT', (current_setting('PKG_GLOBALS.USERNAME', true)), 'S', RECID, (current_setting('PKG_GLOBALS.FIRMANAME', true)), TO_NUMBER((current_setting('PKG_GLOBALS.SUBUNITATE', true)),'999999999999999999'), null, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  PERFORM PKG_NOMACTIVIT_SP_LOCKRECORD( RecId);
  DELETE FROM NACTIVIT WHERE codactivit = RecId;
  PERFORM NotifyModif( 2, RECID, 'NACTIVIT');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomactivit_sp_postrecords</obj_name>
  <obj_hashval>66aca05e134e9113f47c52e782348986</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomactivit_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vRecNo NUMERIC := 0;
  vAn    NUMERIC := 0;
  vLuna  NUMERIC := 0;
  vCod   numeric;
  aDoc   varchar;
BEGIN
  --Florin 01.06.2023 - monitor
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_nomactivit_setct_monitor('MON_7');
  IF  Operation = 0 THEN
    SELECT codactivit INTO RecId FROM TMP_NACTIVIT;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_NOMACTIVIT.CT_MONITOR', true))))
    THEN
      SELECT 'activitate "' || n.den_activit || '"' INTO aDoc FROM TMP_NACTIVIT n WHERE N.CODACTIVIT = RECID;
      PERFORM pkg_userfirme_postlogcucommit( 'NACTIVIT', (current_setting('PKG_GLOBALS.USERNAME', true)), 'M', RECID, (current_setting('PKG_GLOBALS.FIRMANAME', true)), TO_NUMBER((current_setting('PKG_GLOBALS.SUBUNITATE', true)),'999999999999999999'), null, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    UPDATE NACTIVIT SET (den_activit)  = (SELECT den_activit FROM TMP_NACTIVIT) WHERE codactivit = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_NACTIVIT_CODACTIVIT') INTO RecId;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_NOMACTIVIT.CT_MONITOR', true))))
    THEN
      SELECT 'activitate "' || n.den_activit || '"' INTO aDoc FROM TMP_NACTIVIT n;
      PERFORM pkg_userfirme_postlogcucommit( 'NACTIVIT', (current_setting('PKG_GLOBALS.USERNAME', true)), 'A', RECID, (current_setting('PKG_GLOBALS.FIRMANAME', true)), TO_NUMBER((current_setting('PKG_GLOBALS.SUBUNITATE', true)),'999999999999999999'), null, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    INSERT INTO NACTIVIT(codactivit, den_activit)
    (SELECT RecId, den_activit FROM TMP_NACTIVIT);
  END IF;

  PERFORM NotifyModif( OPERATION, RECID, 'NACTIVIT');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomatribute_addnewvalatrib</obj_name>
  <obj_hashval>35e240983bf16e81f3409c79c47c6de6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomatribute_addnewvalatrib(INOUT newval character varying, INOUT recid numeric, INOUT acod numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCount numeric;
begin
  SELECT COUNT( CodValAtr) INTO aCount FROM NATRIB1 WHERE UPPER( NewVal) = UPPER( Valoare);

  IF  aCount = 0 THEN
    SELECT NEXTVAL('SEQ_NATRIB1_CODVALATR') INTO aCOD;

    INSERT INTO NATRIB1(CodValAtr, CodAtribut, Valoare)
    VALUES(aCOD, RecId, NewVal);
  END IF;

  IF  aCount = 1 THEN
    SELECT CODVALATR INTO aCod FROM NATRIB1 WHERE UPPER( NewVal) = UPPER( Valoare);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomatribute_am_date_nartobjatr</obj_name>
  <obj_hashval>83ffd7e83783ea864889da567a06ff23</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomatribute_am_date_nartobjatr(vtip numeric DEFAULT 0, vcod numeric DEFAULT 0)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  cSql    TEXT;
  vResult INTEGER;
  sSchema VARCHAR := Lower(current_setting('PKG_GLOBALS.FIRMANAME', true));
BEGIN
  --Stef 10.12.2024
  IF NULLIF(sSchema, '') IS NULL THEN
    sSchema := public.get_schema();
  END IF;
  cSql :=
  'SELECT
     CASE
       WHEN EXISTS (
          SELECT 1
          FROM '||sSchema||'.natrobj ao
            INNER JOIN '||sSchema||'.nartobj o  ON o.codobiect  = ao.codobiect
            INNER JOIN '||sSchema||'.natrib1 av ON av.codvalatr = ao.codvalatr
            INNER JOIN '||sSchema||'.natrib a   ON a.codatribut = av.codatribut
            INNER JOIN '||sSchema||'.nartatr aa ON aa.codartatr = ao.codartatr
          WHERE Trim(a.colsuplim) IS NOT NULL '||CASE
                                                   WHEN vTip = 1 THEN ' AND o.codarticol = '||To_Char(vCod)
                                                   WHEN vTip = 2 THEN ' AND a.codatribut = '||To_Char(vCod)
                                                   ELSE ''
                                                 END||'
       )
       THEN 1
       ELSE 0
      END AmDate';
  EXECUTE cSql INTO vResult;
  RETURN vResult;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomatribute_repara_nartobjatr</obj_name>
  <obj_hashval>26de755c2b01d65a2fc6f95317c1edb8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomatribute_repara_nartobjatr(vtip numeric DEFAULT 0, vcod numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  VREC      RECORD;
  vExistTab numeric := 0;
  vExistCol numeric;
  vCount    numeric;
  cSQL      text;
  sSchema   varchar := Lower(current_setting('PKG_GLOBALS.FIRMANAME', true));
  vBulk     RECORD;
BEGIN
  --Stef 10.12.2024
  IF NULLIF(sSchema, '') IS NULL THEN
    sSchema := public.get_schema();
  END IF;
  SELECT count(1) INTO vExistTab FROM information_schema.tables WHERE table_name =  'nartobjatr' AND table_schema = sSchema;
  IF vExistTab = 1 AND vTip = 0 THEN
    BEGIN
      EXECUTE 'DROP TABLE '||sSchema||'.nartobjatr';
      vExistTab := 0;
    EXCEPTION
      WHEN OTHERS THEN NULL;
    END;
  END IF;

  CREATE TEMPORARY TABLE if not EXISTS tmp_repara_nartobjatr (
    codatribut NUMERIC(20),
    colname    VARCHAR(50),
    existcol   NUMERIC(1)
  ) ON COMMIT PRESERVE ROWS;
  TRUNCATE TABLE tmp_repara_nartobjatr;

  cSql :=
  'INSERT INTO tmp_repara_nartobjatr
  SELECT
    a.codatribut, a.colname,
    CASE WHEN b.COLNAME IS NULL THEN 0 ELSE 1 END existcol
  FROM (SELECT codatribut, lower(Trim(colsuplim)) colname FROM natrib WHERE Trim(colsuplim) IS NOT NULL) a
    LEFT JOIN (SELECT column_name colname FROM information_schema.columns WHERE table_name = ''nartobjatr'' AND column_name &lt;&gt; ''codobiect'') b ON b.colname = a.colname
  WHERE EXISTS (
    SELECT 1
    FROM natrobj ao
      INNER JOIN nartobj o  ON o.codobiect  = ao.codobiect
      INNER JOIN natrib1 av ON av.codvalatr = ao.codvalatr
      INNER JOIN nartatr aa ON aa.codartatr = ao.codartatr
    WHERE aa.codatribut = a.CODATRIBUT'||CASE WHEN vTip = 1 THEN ' AND o.codarticol = '||To_Char(vCod) ELSE '' END||'
  )'||CASE WHEN vTip = 2 THEN 'AND a.codatribut = '||To_Char(vCod) ELSE '' END||'
  ORDER BY 1';
  EXECUTE cSql;

  SELECT Count(1) INTO vCount FROM tmp_repara_nartobjatr;
  IF vCount &gt; 0 AND vExistTab = 0 THEN
    EXECUTE 'CREATE TABLE '||sSchema||'.NARTOBJATR (CODOBIECT NUMERIC(20) NOT NULL)';
    EXECUTE 'ALTER  TABLE '||sSchema||'.NARTOBJATR ADD CONSTRAINT FK_NARTOBJATR_CODOBIECT FOREIGN KEY (CodObiect) REFERENCES '||sSchema||'.NARTOBJ(CodObiect)';
    vExistTab := 1;
  END IF;

  FOR vBulk IN (SELECT codatribut, colname, existcol FROM tmp_repara_nartobjatr ) LOOP
    vExistCol := vBulk.ExistCol;
    IF vExistCol = 0 THEN
      BEGIN
        EXECUTE 'ALTER TABLE NARTOBJATR ADD COLUMN '||vBulk.colname||' VARCHAR(50)';
        vExistCOL := 1;
      EXCEPTION
        WHEN OTHERS THEN NULL;
      END;
    END IF;

    IF vExistCol = 1 THEN
      cSQL := 'DO $$
      DECLARE
        vRec RECORD;
      BEGIN
        FOR vRec IN (
          SELECT ao.codobiect, av.valoare, CASE WHEN aoa.codobiect IS NULL THEN 1 ELSE 0 END NewVal
          FROM '||sSchema||'.natrobj ao
            INNER JOIN '||sSchema||'.nartobj    o   ON o.codobiect   = ao.codobiect
            INNER JOIN '||sSchema||'.natrib1    av  ON av.codvalatr  = ao.codvalatr
            INNER JOIN '||sSchema||'.nartatr    aa  ON aa.codartatr  = ao.codartatr
            LEFT  JOIN '||sSchema||'.nartobjatr aoa ON aoa.codobiect = ao.codobiect
          WHERE aa.codatribut = '||TO_CHAR(vBulk.codatribut)||CASE WHEN vTip = 1 THEN ' AND o.codarticol = '||To_Char(vCod) ELSE '' END||'
        ) LOOP
          IF vRec.NewVal = 0
          THEN UPDATE '||sSchema||'.nartobjatr b SET '||vBulk.colname||' = vRec.valoare WHERE b.codobiect = vRec.codobiect;
          ELSE INSERT INTO '||sSchema||'.nartobjatr AS b (codobiect, '||vBulk.colname||') VALUES (vRec.codobiect, vRec.valoare) ;
          END IF;
        END LOOP;
      END$$;';
      EXECUTE cSQL;
    END IF;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomatribute_sp_deleterecord</obj_name>
  <obj_hashval>d2437d7f18021fef9cb5914b2e6c751e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomatribute_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  oldColSuplim varchar;
  sSchema      varchar;
BEGIN
  --Adina 02.06.2021 - add schema
  sSchema := Lower(current_setting('PKG_GLOBALS.FIRMANAME', true));
  IF NULLIF(sSchema, '') IS NULL THEN
    sSchema := public.get_schema();
  END IF;

  PERFORM PKG_NOMATRIBUTE_SP_LOCKRECORD( RecId);

  FOR V_REC IN (SELECT * FROM NATRIB1 WHERE CODATRIBUT = RECID) LOOP
    DELETE FROM VALATREXCEPTII WHERE CODVALATR  = V_REC.CODVALATR;
    DELETE FROM NATRIB1        WHERE CodAtribut = V_REC.CODATRIBUT;
    DELETE FROM NATRIB2        WHERE CODVALATR  = V_REC.CODVALATR;
    DELETE FROM NATRIB1TRAD    WHERE CODVALATR  = V_REC.CODVALATR;
  END LOOP;

  SELECT lower( ColSuplim) INTO oldColSuplim FROM NATRIB WHERE CodAtribut = RecId;

  IF oldColSuplim IS NOT NULL THEN
    FOR v_rec IN (SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE table_schema = sSchema AND TABLE_NAME = 'nartobjatr' AND COLUMN_NAME = oldColSuplim) LOOP
      EXECUTE 'ALTER TABLE NARTOBJATR DROP COLUMN ' || v_rec.COLUMN_NAME;
    END LOOP;
  END IF;

  DELETE FROM NATRIB WHERE CodAtribut = RecId;

  PERFORM NotifyModif( 2, RECID, 'NATRIB');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomatribute_sp_gotorecord</obj_name>
  <obj_hashval>90d58e2196c1581485cc860a40cb1aed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomatribute_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NATRIB ( CodAtribut, Denumire, TipValoare, Prefix, ColSuplim )
  SELECT CodAtribut, Denumire, TipValoare, Prefix, ColSuplim FROM NATRIB WHERE CodAtribut = RecId;

  INSERT INTO TMP_NATRIB1 (
    CodValAtr,
    CodAtribut,
    Valoare,
    Codobiectasoc,
    Codextern,
    GRUPA,
    PROCMAJPU,
    INACTIV,
    INACTIVCMDONLINE,
    MESAJINACTIV,
    DenObiectAsoc )
  select
    a.CodValAtr,
    a.CodAtribut,
    a.Valoare,
    a.Codobiectasoc,
    a.Codextern,
    A.GRUPA,
    A.PROCMAJPU,
    A.INACTIV,
    A.INACTIVCMDONLINE,
    A.MESAJINACTIV,
    O.DENUMIRE
  from
    NATRIB1 A left join NartObj o ON o.CodObiect = A.CodObiectAsoc
  where
    CodAtribut = RecId;

  INSERT INTO TMP_VALATREXCEPTII ( CODEXCEPTIE, CODVALATR, CODARTICOL, DENARTICOL, CODEXTERNART )
  SELECT VE.CODEXCEPTIE, VE.CODVALATR, VE.CODARTICOL, DEN_ARTICOL, A.CODEXTERNART
  FROM VALATREXCEPTII VE inner join NART A ON A.CODARTICOL = VE.CODARTICOL
  WHERE exists (SELECT CODVALATR FROM TMP_NATRIB1 WHERE CODVALATR = VE.CODVALATR );

  INSERT INTO TMP_NATRIB2 ( CODATRIB2, CODVALATR, CODARTICOL, PROCMAJ, DENARTICOL, CODEXTERNART )
  SELECT NA.CODATRIB2, NA.CODVALATR, NA.CODARTICOL, NA.PROCMAJ, DEN_ARTICOL, A.CODEXTERNART
  FROM NATRIB2 NA inner join NART A ON A.CODARTICOL = NA.CODARTICOL
  WHERE exists (SELECT CODVALATR FROM TMP_NATRIB1 WHERE CODVALATR = NA.CODVALATR );

  INSERT INTO TMP_NATRIB1TRAD ( CODATRIB1TRAD, CODVALATR, CODLIMBA, MESAJINACTIV, DENUMIRE, DENLIMBA )
  SELECT CODATRIB1TRAD, CODVALATR, CODLIMBA, MESAJINACTIV, DENUMIRE,
         (SELECT DENLIMBA FROM NLIMBA NL WHERE NL.CODLIMBA = A1T.CODLIMBA )
  FROM NATRIB1TRAD A1T
  WHERE exists (SELECT CODVALATR FROM TMP_NATRIB1 A1 WHERE A1.CODVALATR = A1T.CODVALATR );
 end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomautorizatiiauto_sp_gotorecord</obj_name>
  <obj_hashval>b8627ce3782b61afffc3cc2c78737964</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomautorizatiiauto_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_nautorizatiiauto(codautorizatii, denumire, Atentionare, codserviciu)
  (SELECT codautorizatii, denumire, atentionare, codserviciu FROM nautorizatiiauto WHERE codautorizatii = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomautorizatiiauto_sp_insertrecord</obj_name>
  <obj_hashval>a80405f4229db4ebca02220452cd2642</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomautorizatiiauto_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_nautorizatiiauto(codautorizatii) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomautorizatiiauto_sp_postrecords</obj_name>
  <obj_hashval>8fd5088528de4bae92085805be3a0c13</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomautorizatiiauto_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    SELECT codautorizatii INTO RecId FROM TMP_nautorizatiiauto;

    UPDATE nautorizatiiauto
    SET
    (denumire, Atentionare, codserviciu) = (SELECT denumire, atentionare, codserviciu FROM TMP_nautorizatiiauto)
    WHERE
     codautorizatii = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_AUTORIZATII_CODAUTORIZATII') INTO RecId;

    INSERT INTO nautorizatiiauto(codautorizatii, denumire, atentionare, codserviciu)
    (SELECT RecId, denumire, atentionare, codserviciu FROM TMP_nautorizatiiauto);
  END IF;

  PERFORM NotifyModif( OPERATION, RECID, 'NAUTORIZATIIAUTO');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomcarsupart_get_code</obj_name>
  <obj_hashval>b6145d18141201a4f10f5faf5b28d077</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomcarsupart_get_code(INOUT wme_result numeric, INOUT den character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  cod numeric;
begin
  cod := -1;
  SELECT count( *) INTO cod FROM NCARSUPART WHERE upper( den_CARSUPART) = upper( den);

  IF  cod = 0 THEN
    SELECT NEXTVAL('SEQ_NCARSUPART_CODCARSUPART') INTO cod;

    INSERT INTO NCARSUPART(CODCARSUPART, DEN_CARSUPART)
    VALUES(cod, den);
  ELSE
    SELECT codcarsupart INTO cod FROM NCARSUPART WHERE upper( den_carsupart) = upper( den);
  END IF;

  WME_Result :=  cod;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomcarsupart_isunicat</obj_name>
  <obj_hashval>b626041d7394c2294ba3570d7764b7a9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomcarsupart_isunicat(INOUT wme_result numeric, INOUT den character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  RecCount numeric;
begin
  SELECT count( *) INTO RecCount FROM ncarsupart WHERE upper( den_carsupart) = upper( den);

  WME_Result :=  RecCount;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomcarsupart_sp_deleterecord</obj_name>
  <obj_hashval>dd14f1382e18fc29dd3d3edcd4137ce3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomcarsupart_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_NOMCARSUPART_SP_LOCKRECORD( RecId);
  DELETE FROM NCARSUPART WHERE codcarsupart = RecId;
  PERFORM NotifyModif( 2, RECID, 'NCARSUPART');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomcarsupart_sp_gotorecord</obj_name>
  <obj_hashval>e73cec76da992486b1d92f40d9725980</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomcarsupart_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO  TMP_NCARSUPART ( codcarsupart,den_carsupart, Culoare )
  (SELECT codcarsupart,den_carsupart, Culoare FROM NCARSUPART WHERE codcarsupart = RecId ) ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomcarsupart_sp_lockrecord</obj_name>
  <obj_hashval>a26e97688451aca23bce1ed0768c3260</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomcarsupart_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT codcarsupart INTO Tmp FROM NCARSUPART WHERE codcarsupart = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomcarsupart_sp_postrecords</obj_name>
  <obj_hashval>3126366e07357685064c647a27fe227e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomcarsupart_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF Operation = 0 THEN  -- UPDATE

    SELECT  codcarsupart INTO RecId FROM TMP_NCARSUPART;
    UPDATE NCARSUPART
    SET
    ( den_carsupart, Culoare ) = ( SELECT den_carsupart, Culoare FROM TMP_NCARSUPART )
    WHERE codcarsupart = RecId ;

  ELSE  -- INSERT

    SELECT NEXTVAL('SEQ_NCARSUPART_CODCARSUPART') INTO RecId;

    INSERT INTO  NCARSUPART ( codcarsupart,den_carsupart, Culoare )
     ( SELECT  RecId ,den_carsupart, Culoare FROM TMP_NCARSUPART  ) ;
 END IF;

 PERFORM NotifyModif( OPERATION, RECID, 'NCARSUPART');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomcasemarcat_sp_deleterecord</obj_name>
  <obj_hashval>0846256f832f67422e255adabba468a7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomcasemarcat_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_NOMCASEMARCAT_SP_LOCKRECORD( RecId);
  DELETE FROM NCASEMARCAT1 WHERE CodCaseMarcat = RecId;
  DELETE FROM NCASEMARCAT2 WHERE CodCaseMarcat = RecId;
  DELETE FROM NCASEMARCAT  WHERE CodCaseMarcat = RecId;
  PERFORM NotifyModif( 2, RECID, 'NCASEMARCAT');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomcasemarcat_sp_gotorecord</obj_name>
  <obj_hashval>48bf051e814eb84a9196b9b8ac1295f5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomcasemarcat_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  RC RECORD;
  aTIP  numeric := 0;
  nrRows NUMERIC := 0;
BEGIN
  --Florin 11.04.2024 - sinc. Oracle
  INSERT INTO  TMP_NCASEMARCAT(CodCaseMarcat, Denumire, Numar, Port, Tip, Model, CodFiscal, CodBareCantar, PLUMaxCantar, NrMaxPLU, LUNGIMETEXT, TIPDRIVER, RATA, SUBUNITATEA, GESTDESTTRANSF, CODIOARTDESTTRANSF, TIPINFOART, CODCARNETTRANSF, TEXTPROMO, CODCARNETNIR )
  (SELECT CodCaseMarcat, Denumire, Numar, Port, Tip, Model, CodFiscal , CodBareCantar, PLUMaxCantar, NrMaxPLU, LUNGIMETEXT, TIPDRIVER, RATA, SUBUNITATEA, GESTDESTTRANSF, CODIOARTDESTTRANSF, NVL(TIPINFOART, 0), CODCARNETTRANSF, TEXTPROMO, CODCARNETNIR  FROM NCASEMARCAT
  WHERE CodCaseMarcat = RecId
  );

  INSERT INTO TMP_NCASEMARCAT1(CodCaseMarcat1, CodCaseMarcat, CodGestiune, DenGestiune)
  (
  SELECT c.CodCaseMarcat1, c.CodCaseMarcat, c.CodGestiune, g.den_gest
  FROM NCASEMARCAT1 c INNER JOIN ngest g ON  c.codgestiune = g.codgest
  WHERE CodCaseMarcat = RecId
  );

  INSERT INTO TMP_NCASEMARCAT2(CodCaseMarcat2, CodCaseMarcat, Procent_Tva, ParamCasa)
  (SELECT CodCaseMarcat2, CodCaseMarcat, Procent_Tva, ParamCasa FROM NCASEMARCAT2 WHERE CodCaseMarcat = RecId);

  FOR v_rec IN (SELECT  DISTINCT Procent FROM NTVA1 WHERE Procent NOT IN (SELECT Procent_Tva FROM TMP_NCASEMARCAT2)) LOOP
    INSERT INTO TMP_NCASEMARCAT2(CodCaseMarcat2, Procent_Tva)
    VALUES(-1, v_rec.Procent);
  END LOOP;

  BEGIN
    SELECT TIP INTO aTIP FROM TMP_NCASEMARCAT;
  EXCEPTION WHEN OTHERS THEN
    aTIP := 0;
  END;

 INSERT INTO TMP_TIPURIPLATI SELECT * FROM TIPURIPLATI WHERE TIPCASA = aTIP;


end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomcasemarcat_sp_insertrecord</obj_name>
  <obj_hashval>f2e0769b15eebf48c423383322bbd843</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomcasemarcat_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  INSERT INTO TMP_NCASEMARCAT (CodCaseMarcat) VALUES(0);

  FOR v_rec IN (SELECT  DISTINCT Procent FROM NTVA1 ORDER BY Procent) LOOP
    INSERT INTO TMP_NCASEMARCAT2(CodCaseMarcat2, Procent_Tva)
    VALUES(-1, v_rec.Procent);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomcasemarcat_sp_lockrecord</obj_name>
  <obj_hashval>d0a92c25485dc27a4d590a59362ffac1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomcasemarcat_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodCaseMarcat INTO Tmp FROM NCASEMARCAT WHERE CodCaseMarcat = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomcasemarcat_sp_postrecords</obj_name>
  <obj_hashval>edf33507562f5932250b5050106bc9ba</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomcasemarcat_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aTIP  numeric := 0;
  aCOD  numeric;
BEGIN
  --Florin 11.04.2024 - sinc. Oracle
  BEGIN
    SELECT TIP INTO aTIP FROM TMP_NCASEMARCAT;
  EXCEPTION WHEN OTHERS THEN
    aTIP := 0;
  END;

  IF  OPERATION = 0 THEN
    SELECT CodCaseMarcat INTO RecId FROM TMP_NCASEMARCAT;

    UPDATE NCASEMARCAT SET ( Denumire,
                            Numar,
                            Port,
                            Tip,
                            Model,
                            CodFiscal,
                            CodBareCantar,
                            PLUMaxCantar,
                            NrMaxPLU,
                            LUNGIMETEXT,
                            TIPDRIVER,
                            RATA,
                            SUBUNITATEA,
                            GESTDESTTRANSF,
                            CODIOARTDESTTRANSF,
                            TIPINFOART,
                            CODCARNETTRANSF,
                            TEXTPROMO,
                            CODCARNETNIR )
                          =
                      (SELECT Denumire,
                              Numar,
                              Port,
                              Tip,
                              Model,
                              CodFiscal,
                              CodBareCantar,
                              PLUMaxCantar,
                              NrMaxPLU,
                              LUNGIMETEXT,
                              TIPDRIVER,
                              RATA,
                              SUBUNITATEA,
                              GESTDESTTRANSF,
                              CODIOARTDESTTRANSF,
                              TIPINFOART,
                              CODCARNETTRANSF,
                              TEXTPROMO,
                              CODCARNETNIR
                      FROM
                        TMP_NCASEMARCAT )
    WHERE
    CodCaseMarcat = RecId ;


    DELETE FROM NCASEMARCAT1 WHERE CodCaseMarcat = RecId and CodCaseMarcat1 NOT IN (SELECT CodCaseMarcat1 FROM TMP_NCASEMARCAT1);

    INSERT INTO NCASEMARCAT1(CodCaseMarcat1, CodCaseMarcat, CodGestiune)
    (SELECT NEXTVAL('SEQ_NCASEMARCAT1_CODCASE1'), RecId, CodGestiune FROM TMP_NCASEMARCAT1 WHERE CodCaseMarcat1 &lt; 0);

    FOR v_rec IN (SELECT * FROM TMP_NCASEMARCAT1 WHERE COALESCE( CodCaseMarcat1, -1) &gt; 0 ORDER BY CodCaseMarcat1) LOOP
      UPDATE NCASEMARCAT1 SET CodGestiune = v_rec.CodGestiune WHERE CodCaseMarcat1 = v_rec.CodCaseMarcat1;
    END LOOP;

    DELETE FROM NCASEMARCAT2
    WHERE CodCaseMarcat = RecId and CodCaseMarcat2 NOT IN (SELECT CodCaseMarcat2 FROM TMP_NCASEMARCAT2);

    INSERT INTO NCASEMARCAT2(CodCaseMarcat2, CodCaseMarcat, Procent_Tva, ParamCasa)
    (SELECT NEXTVAL('SEQ_NCASEMARCAT2_CODCASE2'), RecId, Procent_Tva, ParamCasa FROM TMP_NCASEMARCAT2 WHERE CodCaseMarcat2 &lt; 0);

    FOR v_rec IN (SELECT * FROM TMP_NCASEMARCAT2 WHERE COALESCE( CodCaseMarcat2, -1) &gt; 0 ORDER BY CodCaseMarcat2) LOOP
      UPDATE NCASEMARCAT2
      SET
      Procent_Tva = v_rec.Procent_Tva,
      ParamCasa   = v_rec.Paramcasa
      WHERE
       CodCaseMarcat2 = v_rec.CodCaseMarcat2;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_NCASEMARCAT_CODCASE') INTO RecId;

        INSERT INTO  NCASEMARCAT ( CodCaseMarcat, Denumire, Numar, Port, Tip, Model, CodFiscal, CodBareCantar, PLUMaxCantar, NrMaxPLU, LUNGIMETEXT, TIPDRIVER, RATA, SUBUNITATEA, GESTDESTTRANSF, CODIOARTDESTTRANSF, TIPINFOART, CODCARNETTRANSF, TEXTPROMO, CODCARNETNIR )
        (SELECT RecId, Denumire, Numar, Port, Tip, Model, CodFiscal, CodBareCantar, PLUMaxCantar, NrMaxPLU, LUNGIMETEXT, TIPDRIVER, RATA, SUBUNITATEA, GESTDESTTRANSF, CODIOARTDESTTRANSF, TIPINFOART, CODCARNETTRANSF, TEXTPROMO, CODCARNETNIR  FROM TMP_NCASEMARCAT
    );

    INSERT INTO NCASEMARCAT1(CodCaseMarcat1, CodCaseMarcat, CodGestiune)
    (SELECT NEXTVAL('SEQ_NCASEMARCAT1_CODCASE1'), RecId, CodGestiune FROM TMP_NCASEMARCAT1);

    INSERT INTO NCASEMARCAT2(CodCaseMarcat2, CodCaseMarcat, Procent_Tva, ParamCasa)
    (SELECT NEXTVAL('SEQ_NCASEMARCAT2_CODCASE2'), RecId, Procent_Tva, ParamCasa FROM TMP_NCASEMARCAT2);
  END IF;

  DELETE FROM TIPURIPLATI WHERE TIPCASA = aTIP;

  FOR V_REC IN (SELECT * FROM TMP_TIPURIPLATI) LOOP
    IF  V_REC.CODTIPPLATA &lt; 0 THEN
      aCOD := NEXTVAL('SEQ_TIPURIPLATI_CODTIPPLATA');
    ELSE
      aCOD := V_REC.CODTIPPLATA;
    END IF;

    INSERT INTO TIPURIPLATI(CODTIPPLATA, TIPCASA, TIPPLATA, DENPLATA, INVIZIBIL)
    VALUES(aCOD, V_REC.TIPCASA, V_REC.TIPPLATA, V_REC.DENPLATA, V_REC.INVIZIBIL);
  END LOOP;

  PERFORM NotifyModif( OPERATION, RECID, 'NCASEMARCAT');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomelemaeroauto_sp_deleterecord</obj_name>
  <obj_hashval>d7e1f8489dc91ef932b5d6286163f15d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomelemaeroauto_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_NOMELEMAEROAUTO_SP_LOCKRECORD( RecId);
  DELETE FROM NELEMAEROAUTO WHERE CodElemAeroAuto = RecId;
  PERFORM NotifyModif( 2, RECID, 'NELEMAEROAUTO');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomelemaeroauto_sp_gotorecord</obj_name>
  <obj_hashval>88e7c985aa7cdb913b7822fedeaadb5d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomelemaeroauto_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NELEMAEROAUTO(CodElemAeroAuto, Element, Spor)
  (SELECT CodElemAeroAuto, Element, Spor FROM NELEMAEROAUTO WHERE CodElemAeroAuto = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomelemaeroauto_sp_lockrecord</obj_name>
  <obj_hashval>062687dfac463e29280ca3e580cf4889</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomelemaeroauto_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodElemAeroAuto INTO Tmp FROM NELEMAEROAUTO WHERE CodElemAeroAuto = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomelemaeroauto_sp_postrecords</obj_name>
  <obj_hashval>ff207f092fecf993f90b49e0ff9d5f87</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomelemaeroauto_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    SELECT CodElemAeroAuto INTO RecId FROM TMP_NELEMAEROAUTO;

    UPDATE NELEMAEROAUTO
    SET
    (Element, Spor) = (SELECT Element, Spor FROM TMP_NELEMAEROAUTO)
    WHERE
     CodElemAeroAuto = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_NELEMAERO_CODELEMAERO') INTO RecId;

    INSERT INTO NELEMAEROAUTO(CodElemAeroAuto, Element, Spor)
    (SELECT RecId, Element, Spor FROM TMP_NELEMAEROAUTO);
  END IF;

  PERFORM NotifyModif( OPERATION, RECID, 'NELEMAEROAUTO');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgest_ct_monitor</obj_name>
  <obj_hashval>ea85c75b73ed3eeff2c5b4921b6315d3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgest_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_NOMGEST.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_2';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgest_gest_curenta_locatii</obj_name>
  <obj_hashval>5365fb95b266c517da2fc34b09ce72f8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgest_gest_curenta_locatii(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOMGEST.GEST_CURENTA_LOCATII')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgest_gest_filtru_generator</obj_name>
  <obj_hashval>692f8fef4e432812d487036104411aaf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgest_gest_filtru_generator(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOMGEST.GEST_FILTRU_GENERATOR')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgest_gestiune_dedicata</obj_name>
  <obj_hashval>1cf5c1ce40b4042b6e4c81786825c274</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgest_gestiune_dedicata(INOUT wme_result numeric, INOUT acodgest numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  IF  acodgest = 0 THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    SELECT COUNT( CODGEST) INTO NR FROM TMP_GESTDEDICATE;
    IF  NR = 0 THEN
      WME_Result :=  1;
      RETURN;
    ELSE
      SELECT COUNT( CODGEST) INTO NR FROM TMP_GESTDEDICATE WHERE CODGEST = aCODGEST;
      WME_Result :=  NR;
      RETURN;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgest_gestiune_filtru_valida</obj_name>
  <obj_hashval>19a32a2ad1489b28f10abe5f9cca8430</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgest_gestiune_filtru_valida(INOUT wme_result numeric, INOUT acodgest numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF (ACODGEST = 0)  OR (TO_NUMBER((current_setting('PKG_NOMGEST.GEST_FILTRU_GENERATOR', true)),'999999999999999999') = 0)  THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    IF  TO_NUMBER((current_setting('PKG_NOMGEST.GEST_FILTRU_GENERATOR', true)),'999999999999999999') = aCODGEST THEN
      WME_Result :=  1;
      RETURN;
    ELSE
      WME_Result :=  0;
      RETURN;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgest_get_den_locatie</obj_name>
  <obj_hashval>e2593b10a0443e4fb7c23d3f9236ceeb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgest_get_den_locatie(INOUT wme_result character varying, INOUT acodlocatie numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  DEN varchar;
begin
  BEGIN
    SELECT DENUMIRE INTO DEN FROM NLOCATII WHERE CODLOCATIE = aCODLOCATIE;
  EXCEPTION WHEN OTHERS THEN
    DEN := '';
  END;

  WME_Result :=  DEN;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgest_get_gest_curenta_locatii</obj_name>
  <obj_hashval>058295c82a36526ed3106e68933f4cf4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgest_get_gest_curenta_locatii(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER((current_setting('PKG_NOMGEST.GEST_CURENTA_LOCATII', true)),'999999999999999999');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgest_getcoefsectie</obj_name>
  <obj_hashval>e52dd71172fba7d748fd4d9e08daeeeb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgest_getcoefsectie(INOUT wme_result numeric, INOUT acodgest numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCapProd numeric;
  aMasa    numeric;
BEGIN
  --Florin 05.01.2021
  SELECT COALESCE(capprod, 0) INTO aCapProd FROM ngest WHERE codgest = aCodGest;

  IF  aCapProd = 0 THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  BEGIN
    SELECT sum(i1.cant * o.masa)
    INTO aMasa
    FROM intrari i
        INNER JOIN intrari1 i1 ON  i1.codintr  = i.codintr
        INNER JOIN nartobj  o  ON  o.codobiect = i1.codobiect
    WHERE
           i.anulat = 0 and  i.codgestprod = aCodGest and  i.operat = 1
      and  i.tipdoc = 7 and  i.an * 12 + i.luna = current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric * 12 + current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric;
  EXCEPTION WHEN others THEN
    aMasa := 0;
  END;

  WME_Result :=  aMasa / aCapProd;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgest_getgest_curenta_locatii</obj_name>
  <obj_hashval>576efbf7aa95887aec9b76cd56f54752</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgest_getgest_curenta_locatii(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOMGEST.GEST_CURENTA_LOCATII')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgest_getgest_filtru_generator</obj_name>
  <obj_hashval>a9368c92647c331e790e38215188b3ef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgest_getgest_filtru_generator(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOMGEST.GEST_FILTRU_GENERATOR')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgest_getlocatia_curenta</obj_name>
  <obj_hashval>557681b11489d39fed6f0750950a2229</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgest_getlocatia_curenta(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOMGEST.Locatia_CURENTA')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgest_locatia_curenta</obj_name>
  <obj_hashval>ff56b3c8b953a01cf1f89905b908fa2b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgest_locatia_curenta(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOMGEST.Locatia_CURENTA')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgest_set_gest_curenta_locatii</obj_name>
  <obj_hashval>1fcb6093ed499ef50e81b5df6de48d90</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgest_set_gest_curenta_locatii(agest numeric, aloc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMGEST.GEST_CURENTA_LOCATII',to_char(aGEST,'999999999999999999'),false);
perform set_config('PKG_NOMGEST.Locatia_CURENTA',to_char(aLoc,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgest_setgest_curenta_locatii</obj_name>
  <obj_hashval>b51f44fb82e8fcec6dcde48e7140bf0e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgest_setgest_curenta_locatii(agest_curenta_locatii numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMGEST.GEST_CURENTA_LOCATII',to_char(aGEST_CURENTA_LOCATII,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgest_setgest_filtru_generator</obj_name>
  <obj_hashval>561ea20491d8701acf0891e0d81151b5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgest_setgest_filtru_generator(agest_filtru_generator numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMGEST.GEST_FILTRU_GENERATOR',to_char(aGEST_FILTRU_GENERATOR,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgest_setlocatia_curenta</obj_name>
  <obj_hashval>565038871bf76f83b2cbf114cbbc22e9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgest_setlocatia_curenta(alocatia_curenta numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMGEST.Locatia_CURENTA',to_char(aLocatia_CURENTA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgest_sp_deleterecord</obj_name>
  <obj_hashval>eda7f93d70b425500d2dfcb74ed11595</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgest_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDoc varchar;
BEGIN
  --Florin 01.06.2023 - monitor
  --Florin 12.04.2023 - sinc. Oracle
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_nomgest_setct_monitor('MON_2');
  IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_NOMGEST.CT_MONITOR', true))))
  THEN
    SELECT 'Gestiune "' || DEN_GEST || '"' INTO aDoc FROM ngest WHERE CODGEST = RECID;
    PERFORM pkg_userfirme_postlogcucommit( 'NGEST', (current_setting('PKG_GLOBALS.USERNAME', true)), 'S', RECID, (current_setting('PKG_GLOBALS.FIRMANAME', true)), TO_NUMBER((current_setting('PKG_GLOBALS.SUBUNITATE', true)),'999999999999999999'), null, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  PERFORM PKG_NOMGEST_SP_LOCKRECORD( RecId);
  PERFORM PKG_CFGTABLES_EXT_DELETERECORD (recId, 506);

  UPDATE NLOCATII SET CODGEST = 0 WHERE CODGEST = RECID;

  DELETE FROM NGEST1  WHERE CODGEST = RecId;
  DELETE FROM NAGENDA WHERE CODGEST = RECID;
  DELETE FROM NGEST   WHERE CODGEST = RECID;

  PERFORM NotifyModif( 2, RECID, 'NGEST');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgest_sp_gotorecord</obj_name>
  <obj_hashval>2581a0f4c557704e7de4d6df2c281bbe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgest_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aANSFARSIT   numeric;
  aLUNASFARSIT numeric;
BEGIN
  --Florin 12.04.2023 - sinc. Oracle
  --Laura 10.12.2021 - sinc. Oracle (10.12.2021)
  --Bogdan 04.01.2021
  --Florin 16.11.2021 - fixat 52001
  perform pkg_nomgest_setct_monitor('MON_2');
  INSERT INTO TMP_NGEST (codgest, den_gest, GMaster, simbol,
      codclasa, codactivit, codcont, codcatpret,
      codgestionar, custodie, codsubunit, VERDISPLIVR,
      VERDISPLIVRTRANSF, verdispLIVRsubunit, VERNIR, VERNIRTRANSF,
      verNIRsubunit, verEmulare, verFactIes, CODPOSTRETAIL,
      ANALITICCONT, CANTITATE, tip, nrschimburi,
      oreschimb, orastart, Coefcheltmat, Coefcheltman,
      INACTIV, verChitanta, codcaensec, codgesttr,
      ziletermen, zilelucr, CODANTREPOZIT, capprod,
      carnetcmdint, carnetbc, carnetnp, carnetrp, Obs)
  SELECT codgest, den_gest, GMaster, simbol,
    codclasa, codactivit, codcont, codcatpret,
    codgestionar, COALESCE (custodie, 0) , codsubunit, VERDISPLIVR,
    VERDISPLIVRTRANSF, verdispLIVRsubunit, VERNIR, VERNIRTRANSF,
    verNIRsubunit, verEmulare, verFactIes, CODPOSTRETAIL,
    ANALITICCONT, CANTITATE, COALESCE (tip, 0) , nrschimburi,
    oreschimb, COALESCE (orastart, to_date ('01.01.1900', 'dd.mm.yyyy')) , Coefcheltmat, Coefcheltman,
    INACTIV, verChitanta, codcaensec, codgesttr,
    ziletermen, zilelucr, CODANTREPOZIT, capprod,
    carnetcmdint, carnetbc, carnetnp, carnetrp, Obs
  FROM NGEST
  WHERE
    codgest = RecId;

  INSERT INTO TMP_NAGENDA (obs, codagenda, tip, codlocalit,
      sediusocial, telefon, fax, email,
      sector, strada, nr1, nr2,
      bloc, scara, etaj, apart,
      codpostal, km, codbankcont, codpart,
      codgest, codsubunit, adresa, longitudine,
      latitudine, obs2)
  SELECT obs, codagenda, tip, codlocalit,
    sediusocial, telefon, fax, email,
    sector, strada, nr1, nr2,
    bloc, scara, etaj, apart,
    codpostal, km, codbankcont, codpart,
    codgest, codsubunit, (   SELECT GetAdresa.WME_RESULT
      FROM GetAdresa (NULL,sector, strada, nr1, nr2, bloc, scara, etaj, apart, codpostal)) , longitudine, latitudine, obs2
  FROM NAGENDA
  WHERE
    codgest = RecId;

  INSERT INTO TMP_LOCATIIGEST (CODLOCATIE, CODGEST, DENUMIRE, INDEXLOCAL)
  SELECT CODLOCATIE, CODGEST, DENUMIRE, INDEXLOCAL FROM NLOCATII WHERE CODGEST = RECID;

  INSERT INTO TMP_NGEST1 (CODGEST1, CODGEST, TipGest, Cheltuieli,
      CheltuieliAux, CheltuieliInd, CheltuieliAdmin, CheltuieliDesf,
      Venituri, VENITURIK, Suprafata, ANSTART,
      LUNASTART)
  (SELECT CODGEST1, CODGEST, TipGest, Cheltuieli,
        CheltuieliAux, CheltuieliInd, CheltuieliAdmin, CheltuieliDesf,
        Venituri, VENITURIK, Suprafata, ANSTART,
        LUNASTART
   FROM NGEST1
   WHERE CODGEST = RecId);

  aANSFARSIT   := 0;
  aLUNASFARSIT := 0;

  FOR V_REC IN (SELECT CODGEST1, ANSTART, LUNASTART FROM TMP_NGEST1 ORDER BY ANSTART * 12 + LUNASTART desc) LOOP
    IF (aANSFARSIT &lt;&gt; 0) AND (aLUNASFARSIT &lt;&gt; 0) THEN
      UPDATE TMP_NGEST1
      SET ANSFARSIT = aANSFARSIT, LUNASFARSIT = aLUNASFARSIT
      WHERE
        CODGEST1 = V_REC.CODGEST1;
    END IF;

    SELECT NEWAN, NEWLUNA
    INTO
      aANSFARSIT, aLUNASFARSIT
    FROM PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA (V_REC.ANSTART, V_REC.LUNASTART, aANSFARSIT, aLUNASFARSIT);
  END LOOP;
  PERFORM PKG_CFGTABLES_EXT_GOTORECORD(506);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgest_sp_lockrecord</obj_name>
  <obj_hashval>255600f9e9b507f50ffbe17eb8ee0476</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgest_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT codgest INTO Tmp FROM NGEST WHERE codgest = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgrupeauto_sp_deleterecord</obj_name>
  <obj_hashval>753cdb00ababa73afb54b5e0279764e0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgrupeauto_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_NOMGRUPEAUTO_SP_LOCKRECORD( RecId);
  DELETE FROM NGRUPEAUTO WHERE CodGrupeAuto = RecId;
  PERFORM NotifyModif( 2, RECID, 'NGRUPEAUTO');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgrupeauto_sp_gotorecord</obj_name>
  <obj_hashval>cd3189acd8946072fafbc787123add8e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgrupeauto_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NGRUPEAUTO(CodGrupeAuto, Grupa, SporB, SporRes, SporAlte)
  (SELECT CodGrupeAuto, Grupa, SporB, SporRes, SporAlte FROM NGRUPEAUTO WHERE CodGrupeAuto = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgrupeauto_sp_insertrecord</obj_name>
  <obj_hashval>57bea9cb4d45f40fd10e79a58182abbb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgrupeauto_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NGRUPEAUTO(CodGrupeAuto) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgrupeauto_sp_lockrecord</obj_name>
  <obj_hashval>42969f725a807e303c02b2961b8a18cc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgrupeauto_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodGrupeAuto INTO Tmp FROM NGRUPEAUTO WHERE CodGrupeAuto = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgrupeauto_sp_postrecords</obj_name>
  <obj_hashval>2e0abe4c3fef7cd679f9080af1c33921</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgrupeauto_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    SELECT CodGrupeAuto INTO RecId FROM TMP_NGRUPEAUTO;

    UPDATE NGRUPEAUTO
    SET
    (Grupa, SporB, SporRes, SporAlte) = (SELECT Grupa, SporB, SporRes, SporAlte FROM TMP_NGRUPEAUTO)
    WHERE
     CodGrupeAuto = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_NGRUPEAUTO_CODGRUPEAUTO') INTO RecId;

    INSERT INTO NGRUPEAUTO(CodGrupeAuto, Grupa, SporB, SporRes, SporAlte)
    (SELECT RecId, Grupa, SporB, SporRes, SporAlte FROM TMP_NGRUPEAUTO);
  END IF;

  PERFORM NotifyModif( OPERATION, RECID, 'NGRUPEAUTO');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nominstauto_sp_deleterecord</obj_name>
  <obj_hashval>adf85fac14a0f23fe7ab0ce6eb53b97c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nominstauto_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_NOMINSTAUTO_SP_LOCKRECORD( RecId);
  DELETE FROM NINSTAUTO WHERE CodInstAuto = RecId;
  PERFORM NotifyModif( 2, RECID, 'NINSTAUTO');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nominstauto_sp_gotorecord</obj_name>
  <obj_hashval>ef3e7b399b6d92e838f400585d8ef8f7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nominstauto_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NINSTAUTO(CodInstAuto, Instalatie, Prestatie, Spor)
  (SELECT CodInstAuto, Instalatie, Prestatie, Spor FROM NINSTAUTO WHERE CodInstAuto = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nominstauto_sp_insertrecord</obj_name>
  <obj_hashval>1c7ee0274fe677ca1e74ddbc9740c84f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nominstauto_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NINSTAUTO(CodInstAuto) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nominstauto_sp_lockrecord</obj_name>
  <obj_hashval>b88612c127425452cf0bd300daf03431</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nominstauto_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodInstAuto INTO Tmp FROM NINSTAUTO WHERE CodInstAuto = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nominterventiiauto_ct_monitor</obj_name>
  <obj_hashval>199f57ca3bc70c7a0c1ee19b5281f3f6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nominterventiiauto_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_NOMINTERVENTIIAUTO.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_56';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nominterventiiauto_getct_monitor</obj_name>
  <obj_hashval>891660253f1ad182351dcd7963084db0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nominterventiiauto_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_NOMINTERVENTIIAUTO.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_56';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nominterventiiauto_setct_monitor</obj_name>
  <obj_hashval>db50dd7c1b7866b62813c98b3588f10f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nominterventiiauto_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMINTERVENTIIAUTO.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nominterventiiauto_sp_deleterecord</obj_name>
  <obj_hashval>85f6953c7c50556171f7cc9cc79f43fb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nominterventiiauto_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDoc varchar;
BEGIN
  --Florin 01.06.2023 - monitor
  perform pkg_nominterventiiauto_setct_monitor('MON_56');
  PERFORM PKG_NOMINTERVENTIIAUTO_SP_LOCKRECORD( RecId);
  SELECT 'Interventi "' || denumire || '"' INTO aDoc FROM NINTERVENTIIAUTO WHERE  codinterventiiauto = recid;
  PERFORM ValidPostLog(  'MON_56',
                         'S', recid, TO_NUMBER((CURRENT_SETTING('PKG_GLOBALS.SUBUNITATE', TRUE)), '999999999999999999'),
                         NULL,aDoc);
  DELETE FROM NINTERVENTIIAUTO WHERE CodInterventiiAuto = RecId;
  PERFORM NotifyModif( 2, RECID, 'NINTERVENTIIAUTO');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nominterventiiauto_sp_gotorecord</obj_name>
  <obj_hashval>145ccf9e4d9bbcce2eb3f74ad59679ca</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nominterventiiauto_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Florin 16.11.2021 - fixat 52001
  perform pkg_nominterventiiauto_setct_monitor('MON_56');
  INSERT INTO TMP_NINTERVENTIIAUTO(CodInterventiiAuto, Denumire, PerTip, PerDurata, PerKm, AtentionareZile, AtentionareKm, Tip, Serviciu, CodReteta, Accidentala, Clasa)
  (SELECT CodInterventiiAuto, Denumire, PerTip, PerDurata, PerKm, AtentionareZile, AtentionareKm, COALESCE( Tip, 0), Serviciu, CodReteta, Accidentala, Clasa
   FROM NINTERVENTIIAUTO
   WHERE CodInterventiiAuto = RecId
  );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nominterventiiauto_sp_insertrecord</obj_name>
  <obj_hashval>bcfed8df88fd3f04c0d6d4814a287866</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nominterventiiauto_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NINTERVENTIIAUTO(CodInterventiiAuto) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nominterventiiauto_sp_lockrecord</obj_name>
  <obj_hashval>b3131cfdde07f60f8f22a67f48a926bb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nominterventiiauto_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodInterventiiAuto INTO Tmp FROM NINTERVENTIIAUTO WHERE CodInterventiiAuto = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nominterventiiauto_sp_postrecords</obj_name>
  <obj_hashval>26f21848df499b3404a4e14d5fd0da20</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nominterventiiauto_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDoc VARCHAR;
BEGIN
  --Florin 01.06.2023 - monitor
  --Florin 25.01.2021 - fixat 42445
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_nominterventiiauto_setct_monitor('MON_56');
  IF  Operation = 0 THEN
    SELECT CodInterventiiAuto INTO RecId FROM TMP_NINTERVENTIIAUTO;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_NOMINTERVENTIIAUTO.CT_MONITOR', true)))
    THEN
      SELECT 'Interventi "' || coalesce(denumire,'') || '"' INTO aDoc FROM NINTERVENTIIAUTO WHERE codinterventiiauto = recid;
      PERFORM pkg_userfirme_postlogcucommit('NINTERVENTIIAUTO', current_setting('PKG_GLOBALS.USERNAME', true), 'M', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, null, aDoc, null, current_setting('PKG_GLOBALS.EXE_VERSION', true));
    END IF;

    UPDATE NINTERVENTIIAUTO
    SET
    (Denumire, PerTip, PerDurata, PerKm, AtentionareZile, AtentionareKm, Tip, Serviciu, CodReteta, Accidentala, Clasa)
    =
    (SELECT Denumire, PerTip, PerDurata, PerKm, AtentionareZile, AtentionareKm, Tip, Serviciu, CodReteta, Accidentala, Clasa FROM TMP_NINTERVENTIIAUTO)
    WHERE
     CodInterventiiAuto = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_NINTERV_CODINTERV') INTO RecId;

    INSERT INTO NINTERVENTIIAUTO (Denumire, CodInterventiiAuto, PerTip, PerDurata, PerKm, AtentionareZile, AtentionareKm, Tip, Serviciu, CodReteta, Accidentala, Clasa)
    SELECT Denumire, RecId, PerTip, PerDurata, PerKm, AtentionareZile, AtentionareKm, Tip, Serviciu, CodReteta, Accidentala, Clasa FROM TMP_NINTERVENTIIAUTO;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_NOMINTERVENTIIAUTO.CT_MONITOR', true)))
    THEN
      SELECT 'Interventi "' || coalesce(denumire,'') || '"' INTO aDoc FROM NINTERVENTIIAUTO WHERE codinterventiiauto = recid;
      PERFORM pkg_userfirme_postlogcucommit('NINTERVENTIIAUTO', current_setting('PKG_GLOBALS.USERNAME', true), 'A', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, null, aDoc, null, current_setting('PKG_GLOBALS.EXE_VERSION', true));
    END IF;
  END IF;

  PERFORM NotifyModif(OPERATION, RECID, 'NINTERVENTIIAUTO');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomlocatii_sp_deleterecord</obj_name>
  <obj_hashval>c2ee963b76e0361d913aae937e304368</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomlocatii_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  AdoC varchar;
begin
  PERFORM PKG_NOMLOCATII_SP_LOCKRECORD( RecId);
  DELETE FROM NLOCATII WHERE CodLocatie = RecId;
  PERFORM NotifyModif( 2, RECID, 'NLOCATII');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomlocatii_sp_gotorecord</obj_name>
  <obj_hashval>9b502f4361613574fee44f2d396e0832</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomlocatii_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NLOCATII(CodLocatie, denumire, NrCelule, DESCRIERE, COORDX, TIPLOCATIE, CODLOCFIXA, CODVECINLEFT, CODVECINRIGHT, CODEXTERN, INDEXLOCAL, Codgest)
  (
  SELECT CodLocatie, denumire, NrCelule, DESCRIERE, COORDX, TIPLOCATIE, CODLOCFIXA, CODVECINLEFT, CODVECINRIGHT, CODEXTERN, INDEXLOCAL, COALESCE( Codgest, 0)
  FROM NLOCATII
  WHERE CodLocatie = RecId
  );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomlocatii_sp_lockrecord</obj_name>
  <obj_hashval>e9dc171417407cc2d12af99a0c6180d2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomlocatii_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodLocatie INTO Tmp FROM NLOCATII WHERE CodLocatie = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomlocatii_sp_postrecords</obj_name>
  <obj_hashval>8576d42ecf32187d25cd8e1cf3da5158</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomlocatii_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vRecNo NUMERIC := 0;
  vAn    NUMERIC := 0;
  vLuna  NUMERIC := 0;
  vCod   numeric;
  aDoc   varchar;
begin
  IF  Operation = 0 THEN
    SELECT CodLocatie INTO RecId FROM TMP_NLOCATII;

    UPDATE NLOCATII
    SET
    (denumire, NrCelule, DESCRIERE, COORDX, TIPLOCATIE, CODLOCFIXA, CODVECINLEFT, CODVECINRIGHT, CODEXTERN, INDEXLOCAL, Codgest)
    =
    (SELECT denumire, NrCelule, DESCRIERE, COORDX, TIPLOCATIE, CODLOCFIXA, CODVECINLEFT, CODVECINRIGHT, CODEXTERN, INDEXLOCAL, Codgest FROM TMP_NLOCATII)
    WHERE
     CodLocatie = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_NLOCATII_CODLOCATIE') INTO RecId;

    INSERT INTO NLOCATII(CodLocatie, denumire, NrCelule, DESCRIERE, COORDX, TIPLOCATIE, CODLOCFIXA, CODVECINLEFT, CODVECINRIGHT, CODEXTERN, INDEXLOCAL, Codgest)
    (SELECT RecId, denumire, NrCelule, DESCRIERE, COORDX, TIPLOCATIE, CODLOCFIXA, CODVECINLEFT, CODVECINRIGHT, CODEXTERN, INDEXLOCAL, Codgest
     FROM TMP_NLOCATII
    );
  END IF;

  PERFORM NotifyModif( OPERATION, RECID, 'NLOCATII');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nommarciauto_sp_deleterecord</obj_name>
  <obj_hashval>1c26b63424e838ea7ed6a7a5d4072286</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nommarciauto_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_NOMMARCIAUTO_SP_LOCKRECORD( RecId);
  DELETE FROM NMARCIAUTO WHERE CodMarciAuto = RecId;
  PERFORM NotifyModif( 2, RECID, 'NMARCIAUTO');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nommarciauto_sp_gotorecord</obj_name>
  <obj_hashval>bcc88f8607c18d7d740ff00876095c1b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nommarciauto_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NMARCIAUTO(CodMarciAuto, Marca) (SELECT CodMarciAuto, Marca FROM NMARCIAUTO WHERE CodMarciAuto = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nommarciauto_sp_insertrecord</obj_name>
  <obj_hashval>0ef8566c3be27eea40717f96f8ba47f2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nommarciauto_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NMARCIAUTO(CodMarciAuto) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nommarciauto_sp_lockrecord</obj_name>
  <obj_hashval>a7819c4c1f5a5823738b1ed2733ac71f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nommarciauto_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodMarciAuto INTO Tmp FROM NMARCIAUTO WHERE CodMarciAuto = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nommarciauto_sp_postrecords</obj_name>
  <obj_hashval>afcc2e806d813816b85fb4dd6069bb7c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nommarciauto_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    SELECT CodMarciAuto INTO RecId FROM TMP_NMARCIAUTO;

    UPDATE NMARCIAUTO SET (Marca)  = (SELECT Marca FROM TMP_NMARCIAUTO) WHERE CodMarciAuto = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_NMARCIAUTO_CODMARCIAUTO') INTO RecId;

    INSERT INTO NMARCIAUTO(CodMarciAuto, Marca)
    (SELECT RecId, Marca FROM TMP_NMARCIAUTO);
  END IF;

  PERFORM NotifyModif( OPERATION, RECID, 'NMARCIAUTO');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nommodeleauto_sp_deleterecord</obj_name>
  <obj_hashval>b7f3e981a4d99258add80b0faeb8dc71</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nommodeleauto_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_NOMMODELEAUTO_SP_LOCKRECORD( RecId);
  DELETE FROM NMODELEAUTO WHERE CodModeleAuto = RecId;
  PERFORM NotifyModif( 2, RECID, 'NMODELEAUTO');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nommodeleauto_sp_gotorecord</obj_name>
  <obj_hashval>e6116d8b6188a9f31606a680ba274088</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nommodeleauto_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NMODELEAUTO(CodModeleAuto, Model, CodMarciAuto)
  SELECT CodModeleAuto, Model, CodMarciAuto FROM NMODELEAUTO WHERE CodModeleAuto = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nommodeleauto_sp_lockrecord</obj_name>
  <obj_hashval>3fba5f351773211c344329d508a84388</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nommodeleauto_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodModeleAuto INTO Tmp FROM NMODELEAUTO WHERE CodModeleAuto = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nommodeleauto_sp_postrecords</obj_name>
  <obj_hashval>8d4cc284776f39e1a13b505607c6ddc5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nommodeleauto_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    SELECT CodModeleAuto INTO RecId FROM TMP_NMODELEAUTO;

    UPDATE NMODELEAUTO
    SET
    (Model, CodMarciAuto) = (SELECT Model, CodMarciAuto FROM TMP_NMODELEAUTO)
    WHERE
     CodModeleAuto = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_NMODELEAUTO_CODMODELEAUTO') INTO RecId;

    INSERT INTO NMODELEAUTO(CodModeleAuto, Model, CodMarciAuto)
    SELECT RecId, Model, CodMarciAuto FROM TMP_NMODELEAUTO;
  END IF;

  PERFORM NotifyModif( OPERATION, RECID, 'NMODELEAUTO');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_checkpart1crm</obj_name>
  <obj_hashval>d37a3125a3c469db3115d7c985c27c83</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_checkpart1crm(acodpart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC    RECORD;
  aCount   numeric;
  vcod     numeric;
  aAnIni   numeric;
  aLunaIni numeric;
begin
  BEGIN
    SELECT aninitial, lunainitiala INTO aAnIni, aLunaIni FROM firmaluni;
  EXCEPTION WHEN others THEN
    aAnIni := 0;
  END;

  IF  aAnIni = 0 THEN END IF;

  IF  aCodPart = 0 THEN
    FOR v_rec IN (SELECT p.* FROM npart p WHERE (SELECT count( *) FROM npart1crm crm WHERE crm.codpart = p.codpart) = 0) LOOP
      SELECT NEXTVAL('SEQ_NPART1CRM_CODPART1CRM') INTO vcod;

      INSERT INTO npart1crm(codpart1crm, codpart, anstart, lunastart, cifraafaceri, nrangajati, lead, sursalead, codresponsabil)
      SELECT vcod, v_rec.codpart, aAnIni, aLunaIni, cifraafaceri, nrangajati, lead, sursalead, codresponsabil
      FROM npart WHERE codpart = v_rec.codpart;

      UPDATE npartactivit    SET codpart1crm = vcod WHERE codpart = v_rec.codpart;
      UPDATE npartdomact     SET codpart1crm = vcod WHERE codpart = v_rec.codpart;
      UPDATE npartconcurenti SET codpart1crm = vcod WHERE codpart = v_rec.codpart;
    END LOOP;
  ELSE
    SELECT count( *) INTO aCount FROM npart1crm crm WHERE crm.codpart = aCodPart;

    IF  aCount = 0 THEN
      SELECT NEXTVAL('SEQ_NPART1CRM_CODPART1CRM') INTO vcod;

      INSERT INTO npart1crm(codpart1crm, codpart, anstart, lunastart, cifraafaceri, nrangajati, lead, sursalead, codresponsabil)
      SELECT vcod, acodpart, aAnIni, aLunaIni, cifraafaceri, nrangajati, lead, sursalead, codresponsabil
      FROM npart WHERE codpart = aCodPart;

      UPDATE npartactivit    SET codpart1crm = vcod WHERE codpart = aCodPart;
      UPDATE npartdomact      SET codpart1crm = vcod WHERE codpart = aCodPart;
      UPDATE npartconcurenti SET codpart1crm = vcod WHERE codpart = aCodPart;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_clasa_part</obj_name>
  <obj_hashval>f77f3d21539a4b6d2feeb92a75c69027</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_clasa_part(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOMPART.CLASA_PART')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_clone_part_as_delegat</obj_name>
  <obj_hashval>7a7cef88e0f0137ad66a2a618354292d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_clone_part_as_delegat(INOUT wme_result numeric, INOUT acodpart numeric, INOUT acodparttr numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  RecId       numeric;
  aDelegat    varchar;
  acnp        varchar;
  vCodFiscal  numeric;
  vCodlocalit numeric;
  vAdresa     varchar;
BEGIN
  --Florin 12.04.2024 - sinc. Oracle
  --Adina 11.03.2021 - add prc_al_refresh
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  RECID := 1;
  BEGIN
    SELECT Delegat, Codlocalit, Adresa, cnp
    INTO aDelegat, vCodlocalit, vAdresa, acnp
    FROM NPARTTR
    WHERE
       CodPArtTr = aCodPArtTr;
  EXCEPTION WHEN OTHERS THEN
    RECID := 0;
  END;

  IF (aCodPArtTr = 0)  or (RECID = 0) THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  RECID := 0;
  BEGIN
    SELECT CodPart INTO RECID FROM NPARTCODFISC WHERE CODFISCAL = aCNP;
  EXCEPTION WHEN OTHERS THEN
    RECID := 0;
  END;

  IF  RECID &gt; 0 THEN
    WME_Result :=  RECID;
    RETURN;
  END IF;

  SELECT NEXTVAL('SEQ_NPART_CODPART') INTO RecId;

  INSERT INTO NPART(CodPart, Den_part, CodExtern, CodMoneda, PERSOANAFIZICA, TVALAINCASARE)
  SELECT RecId, aDelegat, CodExtern, CodMoneda, 1, (SELECT WME_RESULT FROM PKG_NOMPART_TVALAINCASARE(NULL,NULL,NULL))
  FROM NPART WHERE CodPart = aCodPart;

  IF PKG_USERFIRME_ValidPostLog( TO_NUMBER((current_setting('PKG_GLOBALS.USERID')),'999999999999999999'), (current_setting('PKG_NOMPART.CT_MONITOR')))
  THEN
    PERFORM pkg_userfirme_postlogcucommit( 'NPART', (current_setting('PKG_GLOBALS.USERNAME')), 'A', RECID, (current_setting('PKG_GLOBALS.FIRMANAME')), TO_NUMBER((current_setting('PKG_GLOBALS.SUBUNITATE')),'999999999999999999'), null, 'Part.automat"' || aDelegat || '"', null, (SELECT WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  INSERT INTO NPART1(CodPart, CodIOPART, CodPart1, anstart, lunastart)
  SELECT RecId, CodIOPART, NEXTVAL('SEQ_NPART1_CODPART1'), anstart, lunastart
  FROM NPART1 WHERE CodPart = aCodPart;

  CALL PRC_AL_REFRESH('npart1', RECID);

  SELECT NEXTVAL('SEQ_NPARTCODFISC_COD_CODFISCAL') INTO vCodFiscal;

  INSERT INTO NPARTCODFISC(COD_CODFISCAL, CODPART, CODFISCAL, PRINCIPAL)
  VALUES(vCodFiscal, RecId, trim(aCNP), 1);

  INSERT INTO NAGENDA(codagenda, obs, tip, codlocalit, STRADA, sediusocial, codpart, COD_CODFISCAL)
  SELECT NEXTVAL('SEQ_NAGENDA_CODAGENDA'), obs, tip, vCodlocalit, vAdresa, sediusocial, RecID, vCodFiscal
  FROM NAGENDA WHERE CodPart = aCodPart LIMIT 1;

  INSERT INTO NPARTTR(CodPartTr, CodPart, Delegat, cnp, doc, SerieDoc, NrDoc, Eliberat, MijlTransp, NrTransp, ACTIV, DATADOC, IMPLICIT, OBS, PERMIS, NRPASS, CODTARA, ADRESA, CODLOCALIT, TELEFON, EMAIL)
  SELECT NEXTVAL('SEQ_NPARTTR_CODPARTTR'), RecId, Delegat, cnp, doc, SerieDoc, NrDoc, Eliberat, MijlTransp, NrTransp, ACTIV, DATADOC, IMPLICIT, OBS, PERMIS, NRPASS, CODTARA, ADRESA, CODLOCALIT, TELEFON, EMAIL
  FROM NPARTTR WHERE CodPArtTr = aCodPArtTr;

  WME_Result :=  RECID;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_cod_extern_unic</obj_name>
  <obj_hashval>a903be34610aecc3100ed2a25b900ba6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_cod_extern_unic(INOUT wme_result numeric, INOUT acodpart numeric, INOUT acodextern character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  SELECT COUNT( *) INTO NR FROM NPART WHERE CODEXTERN = aCODEXTERN AND  CODPART &lt;&gt; aCODPART;

  IF  NR = 0 THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    WME_Result :=  0;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_cod_fiscal_unic</obj_name>
  <obj_hashval>fc10c09c48e8d20561c8a7af49db3bba</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_cod_fiscal_unic(INOUT wme_result numeric, INOUT acodpart numeric, INOUT acodfiscal character varying, INOUT apartener character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  NR    numeric := 0;
begin
    --Bogdan 11.05.2022 54102 : sa nu se valideze de unicitate codul fiscal fara parte numerica
  --Bogdan 06.05.2022 54102 : adaugare partener - nu ar trebui sa ma lase sa ii dublez
  --Bogdan 17.09.2020
  aPartener := '';

  if regexp_replace(aCODFISCAL, '[^0-9]', '','g') = '' then
      WME_Result := 1;
      RETURN;
    end if;

  SELECT COUNT(*) INTO NR FROM NPARTCODFISC
  WHERE regexp_replace(CODFISCAL, '[^0-9]', '','g') = regexp_replace(aCODFISCAL, '[^0-9]', '','g') AND CODPART &lt;&gt; aCODPART;

  IF NR = 0 THEN
    WME_Result := 1;
    RETURN;
  ELSE
    FOR v_rec IN (SELECT p.den_part FROM npart p INNER JOIN npartcodfisc f ON f.codpart = p.codpart
                  WHERE regexp_replace(f.CODFISCAL, '[^0-9]', '','g') = regexp_replace(aCODFISCAL, '[^0-9]', '','g') AND p.CODPART &lt;&gt; aCODPART)
    LOOP
      aPartener := v_rec.den_part;
      EXIT;
    END LOOP;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_cod_intern_unic</obj_name>
  <obj_hashval>4a55874b096e8bb844ce057566fc98e7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_cod_intern_unic(INOUT wme_result numeric, INOUT acodpart numeric, INOUT acodintern character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  SELECT COUNT( *) INTO NR FROM NPART WHERE CODINTERN = aCODINTERN AND  CODPART &lt;&gt; aCODPART;

  IF  NR = 0 THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    WME_Result :=  0;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_codpart_part_editat_valid</obj_name>
  <obj_hashval>5d41b54e70b0d7ecfd23ce942a46996d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_codpart_part_editat_valid(INOUT wme_result numeric, INOUT acodpart numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  TO_NUMBER((current_setting('PKG_NOMPART.PARTENER_EDITAT',true)),'999999999999999999') &lt;= 0 THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    IF  aCODPART = TO_NUMBER((current_setting('PKG_NOMPART.PARTENER_EDITAT',true)),'999999999999999999') THEN
      WME_Result :=  1;
      RETURN;
    ELSE
      WME_Result :=  0;
      RETURN;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_codpart_sold_analizat_valid</obj_name>
  <obj_hashval>c4d6e6f9361435eb2c2aa5e1084c956c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_codpart_sold_analizat_valid(INOUT wme_result numeric, INOUT acodpart numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan - 60219 - PG - Lista Nomenclator parteneri - coloana : Sold real
  IF   (current_setting('PKG_NOMPART.PARTENER_SOLD_ANALIZAT', true) is null)
        or (current_setting('PKG_NOMPART.PARTENER_SOLD_ANALIZAT', true)::numeric = 0) THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    IF  aCODPART = current_setting('PKG_NOMPART.PARTENER_SOLD_ANALIZAT', true)::NUMERIC THEN
      WME_Result :=  1;
      RETURN;
    ELSE
      WME_Result :=  0;
      RETURN;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_ct_monitor</obj_name>
  <obj_hashval>78fdedb30b3cb11c34d8e5458beb3624</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_NOMPART.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_4';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_dosyncpartretail</obj_name>
  <obj_hashval>9835d9f5fadd7235632ecadabdbfc9a0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_dosyncpartretail(acodpart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
V_REC RECORD;
begin

for V_REC in (select
              coalesce(cv.valoare::numeric, 0) CODPOSTRETAIL
            from
              const1 c1,
              Constluna cl,
              constval cv
            where
              upper(c1.simbol) = 'SYNCPARTRETAIL'
              and c1.codconst1 = cl.codconst1
              and cv.codconstluna = cl.codconstluna
              and cl.userid = current_setting('pkg_globals.userid', true)::numeric
              and current_setting('pkg_globals.anlucru', true)::numeric * 12 + current_setting('pkg_globals.lunalucru', true)::numeric &gt;= alstart
              and current_setting('pkg_globals.anlucru', true)::numeric * 12 + current_setting('pkg_globals.lunalucru', true)::numeric &lt;= alstop
  ) loop
  update
    SYNCPARTRETAIL
  set
    SINCRONIZAT = 0, data = CURRENT_TIMESTAMP
  where
    CODPART = aCODPART
    and CODPOSTRETAIL = V_REC.CODPOSTRETAIL ;

if not found then
insert
  into
    SYNCPARTRETAIL ( CODSYNCPART, CODPART, CODPOSTRETAIL, SINCRONIZAT, data )
  values ( NEXTVAL('SEQ_SYNCPARTRETAIL_CODSYNCPART'), aCODPART, V_REC.CODPOSTRETAIL, 0, CURRENT_TIMESTAMP );
end if;
end loop;

end;

$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_get_cod_npart1</obj_name>
  <obj_hashval>5ed8448fdefbe5956d513308e157bb53</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_get_cod_npart1(INOUT wme_result numeric, INOUT acodpart numeric, INOUT aan numeric, INOUT aluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  CPART1 numeric := -1;
begin
  --Florin 11.01.2022 - sinc. Oracle (29.12.2021)
  BEGIN
    SELECT Coalesce( CodPart1, 0)
    INTO CPart1
    FROM NPart1 n1
      WHERE n1.CodPart = aCodPart AND aAn * 12 + aLuna BETWEEN n1.alstart AND n1.alstop;
  EXCEPTION WHEN OTHERS THEN
    CPart1 := -1;
  END;

  WME_Result :=  CPart1;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_get_denpart</obj_name>
  <obj_hashval>678429a46abae9643a205ed325c5c232</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_get_denpart(INOUT wme_result character varying, INOUT acodpart numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  DEN varchar := '';
begin
  BEGIN
    SELECT DEN_PART INTO DEN FROM NPART WHERE CODPART = aCODPART;
  EXCEPTION WHEN OTHERS THEN
    DEN := '';
  END;

  WME_Result :=  DEN;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_get_fact_furn</obj_name>
  <obj_hashval>57f74580d0354f5f951e6e001a373794</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_get_fact_furn(INOUT wme_result refcursor, INOUT acodpart numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMPCURSOR REFCURSOR;
begin
  BEGIN
    OPEN tmpCursor FOR
    SELECT O.CodObligPIF, O.CodPart PARTENER, O.Termen, P.ScadentaC, E.PREFIXDOC, E.NRDOC, E.DATADOC, m.simbol MONEDA, O.VALOARE, O.REST, 0 AS EXCLUSPLATA, E.CodIntr CODDOC, E.TipDoc
    FROM ObligPIF O
        INNER JOIN General G ON  G.CodGeneral = O.CodGeneral
        INNER JOIN NPART   P ON  P.CodPart    = O.CodPart
        INNER JOIN INTRARI E ON  E.CodINTR    = G.CodDoc
        LEFT  JOIN nmonede m ON  m.codmoneda  = Coalesce( e.moneda, 0)
    WHERE (O.Codpart = aCodPart or aCodPart = 0) and ((O.Valoare &gt; 0 and  O.Rest &gt; 0) or (O.Valoare &lt; 0 and  O.Rest &lt; 0))
      and G.TipDoc IN (1, 5, 9) and  NOT o.semnificatie IN (310, 140);
  EXCEPTION WHEN OTHERS THEN
    OPEN tmpCursor FOR
    SELECT O.CodObligPIF, O.CodPart PARTENER, O.Termen, 0 SCADENTAC, '?' PREFIXDOC, 0 NRDOC, O.Termen DATADOC, '...nedefinit...' MONEDA, O.VALOARE, o.REST, 0 AS EXCLUSPLATA
    FROM obligpif O
    WHERE 1 = 2;
  END;

  WME_Result :=  tmpcursor;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_get_fact_part</obj_name>
  <obj_hashval>a8ecc7c12d638654c32c6c040102470f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_get_fact_part(INOUT wme_result refcursor, INOUT acodpart numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMPCURSOR REFCURSOR;
begin
  BEGIN
    OPEN tmpCursor FOR
    SELECT O.CodObligPIF, O.CodPart PARTENER, O.Termen, P.ScadentaV, E.PREFIXDOC, E.NRDOC, E.DATADOC, m.simbol MONEDA, O.VALOARE, O.REST, 0 AS EXCLUSPLATA, E.CodIes CODDOC, E.TipDoc
    FROM ObligPIF O
      INNER JOIN General G ON  G.CodGeneral = O.CodGeneral
      INNER JOIN NPART   P ON  P.CodPart    = O.CodPart
      INNER JOIN Iesiri  E ON  E.CodIes     = G.CodDoc
      LEFT  JOIN nmonede m ON  m.codmoneda  = Coalesce( e.moneda, 0)
    WHERE
       (O.Codpart = aCodPart or aCodPart = 0) and (  (   O.Valoare &gt; 0 and  O.Rest &gt; 0)  or (   O.Valoare &lt; 0 and  O.Rest &lt; 0) )  and (   G.TipDoc = 19 or  G.TipDoc = 26)  and  NOT o.semnificatie IN (210, 240);
  EXCEPTION WHEN OTHERS THEN
    OPEN tmpCursor FOR
    SELECT O.CodObligPIF, O.CodPart PARTENER, O.Termen, 0 SCADENTAV, '?' PREFIXDOC, 0 NRDOC, O.Termen DATADOC, '...nedefinit...' MONEDA, O.VALOARE, o.REST, 0 AS EXCLUSPLATA
    FROM obligpif O
    WHERE 1 = 2;
  END;

  WME_Result :=  tmpcursor;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_get_part_cod_caract_luna</obj_name>
  <obj_hashval>7b0b9a3fd6572391733444ea6918f0e5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_get_part_cod_caract_luna(acodpart numeric, aan numeric, aluna numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODIoPart  numeric := -1;
  aCODIoPart1 numeric := -1;
BEGIN
  --Florin 04.08.2020
  --Florin 11.01.2022 - sinc. Oracle (29.01.2021)
  BEGIN
    SELECT Coalesce( CodIoPart, 0) INTO aCodIoPart
    FROM NPart1 n1
      WHERE n1.CodPart = aCodPart AND aAn * 12 + aLuna BETWEEN n1.alstart AND n1.alstop;
  EXCEPTION WHEN OTHERS THEN
    aCodIoPart1 := -1;
  END;

  IF  aCODIOPART &gt; 0 THEN
    BEGIN
      SELECT Coalesce( CodIoPart1, 0) INTO aCodIoPart1
      FROM IoPart1 i1
        WHERE i1.CodIoPart = aCodIoPart AND aAn * 12 + aLuna BETWEEN i1.alstart AND i1.alstop;
    EXCEPTION WHEN OTHERS THEN
      aCodIoPart1 := -1;
    END;
  END IF;

  RETURN aCodIoPart1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_get_part_cod_caract_luna</obj_name>
  <obj_hashval>723dbe12def587d73d85ad094a7805d4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_get_part_cod_caract_luna(INOUT wme_result numeric, INOUT acodpart numeric, INOUT aan numeric, INOUT aluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODIoPart  numeric := -1;
  aCODIoPart1 numeric := -1;
begin
  --Florin 11.01.2022 - sinc. Oracle (29.01.2021)
  BEGIN
    SELECT Coalesce( CodIoPart, 0) INTO aCodIoPart
    FROM NPart1 n1
      WHERE n1.CodPart = aCodPart AND aAn * 12 + aLuna BETWEEN n1.alstart AND n1.alstop;
  EXCEPTION WHEN OTHERS THEN
    aCodIoPart1 := -1;
  END;

  IF  aCODIOPART &gt; 0 THEN
    BEGIN
      SELECT Coalesce( CodIoPart1, 0) INTO aCodIoPart1
      FROM IoPart1 i1
        WHERE i1.CodIoPart = aCodIoPart AND aAn * 12 + aLuna BETWEEN i1.alstart AND i1.alstop;
    EXCEPTION WHEN OTHERS THEN
      aCodIoPart1 := -1;
    END;
  END IF;

  WME_Result :=  aCodIoPart1;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_get_part_curent</obj_name>
  <obj_hashval>59ff109b23a58c1e164895e8fa9f7d3d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_get_part_curent(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER((current_setting('PKG_NOMPART.PARTENER_CURENT',true)),'999999999999999999');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_get_part_curent</obj_name>
  <obj_hashval>527cb4fe9b798b45570d9ab7c3651891</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_get_part_curent()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 23 septembrie 2020
  RETURN  CASE WHEN length(current_setting('PKG_NOMPART.PARTENER_CURENT',true))=0 THEN -1
               ELSE TO_NUMBER(current_setting('PKG_NOMPART.PARTENER_CURENT',true),'999999999999999999')
          END;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_get_part_curent_locatii</obj_name>
  <obj_hashval>7fa75821d7c5911fb1a3db37e7b6dd61</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_get_part_curent_locatii(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  Coalesce(current_setting('PKG_NOMPART.PARTENER_CURENT_LOCATII', True)::numeric, 0);
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_get_part_docrosu</obj_name>
  <obj_hashval>f392d8eda40072d1546c0c4fe80058d2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_get_part_docrosu(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER((current_setting('PKG_NOMPART.PART_DOC_ROSU',true)),'999999999999999999');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_get_part_icont_analizat</obj_name>
  <obj_hashval>3510b1ebbb94bcf0a375ed3865b22ef2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_get_part_icont_analizat(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER((current_setting('PKG_NOMPART.PARTENER_ICONT_ANALIZAT',true)),'999999999999999999');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_get_partactivit</obj_name>
  <obj_hashval>350ccb2a9d0540620c720c59ac50a4b9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_get_partactivit(INOUT wme_result character varying, INOUT acodpart numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vLimita numeric := 3200;
  vLMax   numeric;
  vRes    varchar;
begin

  SELECT String_agg(Coalesce(den, ''), ''), Max(LMAX) INTO vRes, vLMax
  FROM (
    SELECT den_activit den, Sum(Length(den_activit)) OVER () LMAX, Sum(Length(den_activit)) OVER (ORDER BY den_activit ROWS UNBOUNDED PRECEDING) LCUR
    FROM NPARTACTIVIT PA INNER JOIN NACTIVIT A ON a.codactivit = pa.codactivit
    WHERE pa.codpart = aCodPart
  ) aPG
  WHERE LCUR &lt;= vLimita;

  IF vLMax &gt; vLimita THEN
    vRes := SubString(vRes, 1, vLimita - 3) ||'...';
  END IF;
  WME_Result :=  vRes;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_get_record_part_caract_luna</obj_name>
  <obj_hashval>e391e336d7255943bc30f504dc5d32c1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_get_record_part_caract_luna(INOUT wme_result refcursor, INOUT acodpart numeric, INOUT an numeric, INOUT luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMPCURSOR REFCURSOR;
  IoPartCod numeric;
begin
  --Florin 11.01.2021 - sinc. Oracle (29.01.2021)
  BEGIN
    SELECT Coalesce( CodIoPart, -1)
    INTO IoPartCod
    FROM NPart1 n1
        WHERE n1.CodPart = aCodPart AND An * 12 + Luna BETWEEN n1.alstart AND n1.alstop;
  EXCEPTION WHEN OTHERS THEN
    IoPartCod := -1;
  END;

  IF  IoPartCod &gt; 0 THEN
    BEGIN
      OPEN tmpCursor FOR
      SELECT *
      FROM IoPart1 i1
         WHERE i1.CodIoPart = IoPartCod AND An * 12 + Luna BETWEEN i1.alstart AND i1.alstop;
    EXCEPTION WHEN OTHERS THEN
      OPEN tmpCursor FOR SELECT * FROM IOPART1 WHERE 1 = 2;
    END;
  ELSE
    OPEN tmpCursor FOR SELECT * FROM IOPART1 WHERE 1 = 2;
  END IF;

  WME_Result :=  tmpcursor;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_get_subunit_gest</obj_name>
  <obj_hashval>0b3c454c7902346390435029813afae5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_get_subunit_gest(INOUT wme_result numeric, INOUT acodgest numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODSUBUNIT numeric := 2;
begin
  BEGIN
    SELECT CODSUBUNIT INTO aCODSUBUNIT FROM NGEST WHERE CODGEST = aCODGEST;
  EXCEPTION WHEN OTHERS THEN
    aCODSUBUNIT := 2;
  END;

  WME_Result :=  aCODSUBUNIT;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_getclasa_part</obj_name>
  <obj_hashval>484e9b94eab37c3c5d18c13b69bd5b7a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_getclasa_part(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOMPART.CLASA_PART')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_getct_monitor</obj_name>
  <obj_hashval>ab8a65d276fd8721d85c766f76b6bf75</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_NOMPART.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_4';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_getpart_doc_rosu</obj_name>
  <obj_hashval>a92d6b7a675f3afd61627cb5fe67817b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_getpart_doc_rosu(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOMPART.PART_DOC_ROSU')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_getpartener_curent_cf</obj_name>
  <obj_hashval>bcc65db54dce05367480debb8cfa6648</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_getpartener_curent_cf(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOMPART.PARTENER_CURENT_CF')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_getpartener_curent_locatii</obj_name>
  <obj_hashval>8a99b51ea361bae51e9b900bce07a4c2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_getpartener_curent_locatii(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOMPART.PARTENER_CURENT_LOCATII')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_getpartener_icont_analizat</obj_name>
  <obj_hashval>0600743cb59dab0c376d52cfb14bdb6f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_getpartener_icont_analizat(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOMPART.PARTENER_ICONT_ANALIZAT')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_getpartener_sold_analizat</obj_name>
  <obj_hashval>34dc799075be14f3c8af89bb0fb73143</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_getpartener_sold_analizat(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOMPART.PARTENER_SOLD_ANALIZAT')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_gettipserv_curent</obj_name>
  <obj_hashval>8c0e932b944e8f6fa01b76720792238c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_gettipserv_curent(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_NOMPART.TIPSERV_CURENT', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_make_curs_general_luna</obj_name>
  <obj_hashval>b19f67325e1a2728130537ba15074567</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_make_curs_general_luna(adata character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 06.10.2025 - fixat 6649
  --Adina 17 august 2020
  DELETE FROM TMP_CURS_REGULARIZAT_LUNA;

insert into x (view_name, test) values ('adata', adata);
  INSERT INTO TMP_CURS_REGULARIZAT_LUNA(CODGENERAL, CURS)
  --SELECT  DISTINCT R1.CODGENERAL, LAST_VALUE( R.CURS) OVER (  ORDER BY R.DATADOC )  CURS
  --FROM REG R INNER JOIN REG1 R1 ON  R1.CODREG = R.CODREG
  --WHERE R.TIPREG = 46 AND  R.DATADOC &lt;= TO_DATE( aDATA, 'dd.mm.yyyy');
  SELECT DISTINCT ON (R1.CODGENERAL)
      R1.CODGENERAL,
      R.CURS
  FROM REG R
  INNER JOIN REG1 R1 ON R1.CODREG = R.CODREG
  WHERE R.TIPREG = 46
      AND R.DATADOC &lt;= TO_DATE(aDATA, 'dd.mm.yyyy')
  ORDER BY R1.CODGENERAL, R.DATADOC DESC;

--  SELECT x.CODGENERAL, Max(x.CURS) CURS
--  FROM (SELECT R1.CODGENERAL, R.CURS, DENSE_RANK() OVER (PARTITION BY R1.CODGENERAL ORDER BY R.DATADOC DESC) NR
--          FROM REG R INNER JOIN REG1 R1 ON R1.CODREG = R.CODREG
--          WHERE R.TIPREG = 46 AND R.DATADOC &lt;= TO_DATE(aDATA, 'dd.mm.yyyy')
--        ) x WHERE NR=1
--  GROUP BY x.CODGENERAL;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_part_doc_rosu</obj_name>
  <obj_hashval>535aa403e0de455e87c7fbe37f73789d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_part_doc_rosu(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOMPART.PART_DOC_ROSU')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_part_docrosu_valid</obj_name>
  <obj_hashval>0ba0bc06e24c9c64bfb9dd396c962cb7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_part_docrosu_valid(INOUT wme_result numeric, INOUT acodpart numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  TO_NUMBER((current_setting('PKG_NOMPART.PART_DOC_ROSU',true)),'999999999999999999') = 0 THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    IF  aCODPART = TO_NUMBER((current_setting('PKG_NOMPART.PART_DOC_ROSU',true)),'999999999999999999') THEN
      WME_Result :=  1;
      RETURN;
    ELSE
      WME_Result :=  0;
      RETURN;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_partanaf_actro</obj_name>
  <obj_hashval>04e4fbef447abb6a00f77f3f80ad5d0e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_partanaf_actro()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  VREC           RECORD;
  vCOD_CODFISCAL numeric;
  sCODFISCAL     varchar;
BEGIN
  --Florin 12.04.2024 - sinc. Oracle
  --Bogdan 20.10.2020
  FOR vRec IN (SELECT CodPart, CUI, CONTRIBUABIL FROM TMP_NPART_ANAF WHERE OLD_CONTRIB &lt;&gt; CONTRIBUABIL) LOOP
    sCODFISCAL := vRec.CUI;
    IF vRec.CONTRIBUABIL = 1 THEN
      sCODFISCAL := 'RO' || coalesce (sCODFISCAL::varchar ,'');
    END IF;

    UPDATE NPARTCODFISC SET PRINCIPAL = 0 WHERE CodPArt = vRec.CodPart;

    SELECT Coalesce (Max (COD_CODFISCAL) , 0)
    INTO vCOD_CODFISCAL
    FROM NPARTCODFISC
    WHERE CODPART = vRec.CodPart AND Upper (REGEXP_REPLACE(CODFISCAL, '\W+', '','g')) = sCODFISCAL;

    IF vCOD_CODFISCAL = 0 THEN
      INSERT INTO NPARTCODFISC (COD_CODFISCAL, CODPART, CODFISCAL, PRINCIPAL)
      VALUES (NEXTVAL ('SEQ_NPARTCODFISC_COD_CODFISCAL') , vRec.CodPart, trim(sCODFISCAL), 1);
    ELSE
      UPDATE NPARTCODFISC SET PRINCIPAL = 1 WHERE COD_CODFISCAL = vCOD_CODFISCAL;
    END IF;
  END LOOP;

  UPDATE TMP_NPART_ANAF SET OLD_CONTRIB = CONTRIBUABIL WHERE OLD_SPLITTVA &lt;&gt; SPLITTVA;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_partanaf_actsedsoc</obj_name>
  <obj_hashval>b992638ea7c69cf8da8ef6d5d4f14a8a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_partanaf_actsedsoc()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  VREC           RECORD;
  aCodLocalit    NUMERIC(20);
BEGIN
  --Florin 19.07.2023 - sinc. Oracle
  --Bogdan 29.03.2023 - 57800 - PG - Actualizare parteneri de la ANAF
  --Florin 13.03.2023 - sinc. Oracle (10.03.2023)
  --Bogdan 30.01.2023 56926 Actualizare parteneri de la ANAF
  --Bogdan 27.01.2023
  FOR vRec IN (select * from TMP_NPART_ANAF tmp where Coalesce(tmp.CHANGE_ADRESA,0) = 1 and tmp.localitate is not null)
  LOOP
     aCodLocalit := (select WME_RESULT from PKG_IMPORTALTEAPLICATII_GETCODLOCALIT(cast(null as numeric), vRec.LOCALITATE, vRec.JUDET, cast(null as varchar), 'RO'::VARCHAR , 1::numeric));
      if coalesce(aCodLocalit, 0) &lt;&gt; 0  THEN
      BEGIN
        update NAGENDA nag set
          STRADA     = vRec.STRADA,
          NR1        = vRec.NUMAR1,
          NR2        = vRec.NUMAR2,
          ETAJ       = vRec.ETAJ,
          APART      = vRec.APART,
          BLOC       = vRec.BLOC,
          SCARA      = vRec.SCARA,
          CODLOCALIT = aCodLocalit
         where nag.CODPART is not null AND nag.CODPART=vRec.CODPART
            AND nag.SEDIUSOCIAL BETWEEN 4 AND 7
            AND Coalesce(nag.INACTIV, 0) = 0;
      EXCEPTION
       WHEN OTHERS THEN
        update NAGENDA nag set
          STRADA     = vRec.STRADA,
          NR1        = 99999,
          NR2        = vRec.NUMAR2,
          ETAJ       = vRec.ETAJ,
          APART      = vRec.APART,
          BLOC       = vRec.BLOC,
          SCARA      = vRec.SCARA,
          CODLOCALIT = aCodLocalit
         where nag.CODPART is not null AND nag.CODPART=vRec.CODPART
            AND nag.SEDIUSOCIAL BETWEEN 4 AND 7
            AND Coalesce(nag.INACTIV, 0) = 0;
      END;
      end if;
  end loop;

    perform pkg_nompart_partanaf_init();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_partanaf_actsplittva</obj_name>
  <obj_hashval>9ee6483fddf01a3cc9cd2f1c37fd5345</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_partanaf_actsplittva()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  VREC RECORD;
begin
  --Bogdan 20.10.2020
  FOR vRec IN (SELECT CodPart, SPLITTVA FROM TMP_NPART_ANAF WHERE OLD_SPLITTVA &lt;&gt; SPLITTVA) LOOP
    UPDATE NPART SET SPLITTVA = vRec.SPLITTVA WHERE CodPArt = vRec.CodPart;
  END LOOP;

  UPDATE TMP_NPART_ANAF SET OLD_SPLITTVA = SPLITTVA WHERE OLD_SPLITTVA &lt;&gt; SPLITTVA;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_partanaf_init</obj_name>
  <obj_hashval>6edf8fba78985b4007eacadfb6fa3705</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_partanaf_init()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  dData date := DATE_TRUNC ('DAY',CURRENT_TIMESTAMP);
BEGIN
  --Florin 04.11.2025 - sinc. Oracle
  --Florin 25.07.2025 - fixat 66236
  --Stef 21.07.2025
  DELETE FROM WINMADMIN.NPART_ANAF WHERE DATA &lt;&gt; dData;
  DELETE FROM WINMADMIN.NPART_ANAF WHERE STARE = 2;
  DELETE FROM TMP_NPART_ANAF;
  INSERT INTO TMP_NPART_ANAF (
    CODPART, DEN_PART, CUI, DATA, STARE, OLD_CONTRIB, CONTRIBUABIL, OLD_SPLITTVA, SPLITTVA,
    ADRESA,
    LOCALITATE, JUDET, STRADA, BLOC, SCARA, NUMAR1, NUMAR2, ETAJ, APART, OLD_ADRESA, CHANGE_ADRESA,
    OLD_RTVAI, RTVAI, OLD_NRREGCOM, NRREGCOM, DENUMIRE, CHANGE_DEN, OLD_INACTIV, INACTIV
  )
  SELECT DISTINCT
    TMP.CodPart, TMP.Den_Part, TMP.Cui, dData AS Data, Coalesce(PA.Stare, 0) Stare, TMP.AreRO OLD_CONTRIB, PA.CONTRIBUABIL, TMP.OLD_SPLITTVA, Coalesce(PA.SPLITTVA, TMP.OLD_SPLITTVA) SPLITTVA,
    PA.ADRESA,
    PA.LOCALITATE, PA.JUDET, PA.STRADA, PA.BLOC, PA.SCARA, PA.NUMAR1, PA.NUMAR2, PA.ETAJ, PA.APART, TMP.OldAdresa, TMP.CHANGE_ADRESA,
    TMP.OLD_RTVAI, PA.RTVAI, TMP.OLD_NRREGCOM, PA.NRREGCOM, PA.DENUMIRE, 0 CHANGE_DEN, TMP.OLD_INACTIV,
    CASE WHEN PA.CONTRIBUABIL IN (-3, -2) THEN 1 ELSE 0 END AS INACTIV
  FROM (
    SELECT
      CodPart, Den_Part, OLD_NRREGCOM, OLD_SPLITTVA, OLD_RTVAI, OLD_INACTIV,
      CASE WHEN SubStr(CodFiscal, 1, 2) = 'RO' THEN 1 ELSE 0 END AreRO,
      NULLIF(REGEXP_REPLACE(CodFiscal, '\D', '', 'g'), '')::NUMERIC CUI,
      NULLIF(REGEXP_REPLACE(CodFiscal, '\d', '', 'g'), '')          CUI_NonDigit,
      OldAdresa,
      CASE WHEN den_tara = '1' THEN 1 ELSE 0 END AS CHANGE_ADRESA
    FROM (
      SELECT
        NP.CodPart, NP.Den_Part,
        Upper(REGEXP_REPLACE(CF.CodFiscal, '\.|\s', '')) CodFiscal, NP.REGCOM OLD_NRREGCOM,
        LSOC.DEN_LOCALIT ||','||fnc_GetAdresa(SSOC.sector,SSOC.strada,SSOC.nr1,SSOC.nr2,SSOC.bloc,SSOC.scara,SSOC.etaj,SSOC.apart,SSOC.codpostal) AS OldAdresa, tsoc.den_tara,
        Coalesce(NP.SPLITTVA, 0)      OLD_SPLITTVA,
        Coalesce(NP.TVALaIncasare, 0) OLD_RTVAI,
        Coalesce(NP.INACTIV, 0)       OLD_INACTIV
      FROM NPARTCODFISC CF
        INNER JOIN NPART    NP   ON NP.CODPART = CF.CODPART
        INNER JOIN NAGENDA  SSOC ON SSOC.CodPart = NP.CodPart AND SSOC.SEDIUSOCIAL BETWEEN 4 AND 7 AND Coalesce(SSOC.INACTIV, 0) = 0
        INNER JOIN NLOCALIT LSOC ON LSOC.CODLOCALIT = Coalesce(SSOC.CODLOCALIT, 0)
        INNER JOIN NJUDET   JSOC ON JSOC.CODJUDET   = Coalesce(LSOC.CODJUDET, 0)
        INNER JOIN NTARI    TSOC ON TSOC.CODTARA    = Coalesce(LSOC.CODTARA, 0)
      WHERE NP.CodPart &lt;&gt; 0
        AND Coalesce(NP.PersoanaFizica, 0)  IN (0,2,3)
        AND (TSOC.SIMBAUTO = 'RO' OR DEN_TARA = '1')
        AND Coalesce(CF.PRINCIPAL, 0) = 1
    ) A_PG
  ) TMP LEFT JOIN WINMADMIN.NPART_ANAF PA ON PA.CUI = TMP.CUI
  WHERE CASE
          WHEN TMP.AreRO = 1 AND TMP.CUI_NonDigit = 'RO'  THEN 1
          WHEN TMP.AreRO = 0 AND TMP.CUI_NonDigit IS NULL THEN 1
          ELSE 0
        END = 1
    AND Coalesce(Length(TMP.CUI::varchar), 0) BETWEEN 1 AND 20;

  DELETE FROM TMP_NPART_ANAF WHERE Cif_Valid(Cui::varchar)  = 0;
  UPDATE TMP_NPART_ANAF SET CONTRIBUABIL = OLD_CONTRIB WHERE CONTRIBUABIL IS NULL;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_partanaf_sinc</obj_name>
  <obj_hashval>ef334406cb1c935d5bdd527c554b5afd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_partanaf_sinc()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 04.11.2025 - sinc. Oracle
  --Stef 21.07.2025
  INSERT INTO WINMADMIN.NPART_ANAF (
    CUI, DATA, STARE, CONTRIBUABIL, DENUMIRE,
    ADRESA, LOCALITATE, JUDET, STRADA, BLOC, SCARA, NUMAR1, NUMAR2, ETAJ, APART,
    NRREGCOM, SPLITTVA, RTVAI, STAREINREG, STAREINACTIV, MESAJ)
  SELECT DISTINCT
    T.CUI, T.DATA, T.STARE, T.CONTRIBUABIL, T.DENUMIRE,
    T.ADRESA, T.LOCALITATE, T.JUDET, T.STRADA, T.BLOC, T.SCARA, T.NUMAR1, T.NUMAR2, T.ETAJ, T.APART,
    T.NRREGCOM, T.SPLITTVA, T.RTVAI, T.STAREINREG, T.STAREINACTIV, T.MESAJ
  FROM TMP_NPART_ANAF T
  WHERE NOT STARE IN (0, 2, 9)
    AND NOT EXISTS (SELECT 1 FROM WINMADMIN.NPART_ANAF A WHERE A.CUI = T.CUI AND A.DATA = T.DATA);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_partener_curent</obj_name>
  <obj_hashval>71c67170debc17864c085cb2386f6f91</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_partener_curent(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOMPART.PARTENER_CURENT')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_partener_curent_cf</obj_name>
  <obj_hashval>354ea3ca994b417c62d5bdefe38b9c1a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_partener_curent_cf(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOMPART.PARTENER_CURENT_CF')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_partener_curent_locatii</obj_name>
  <obj_hashval>6685c8951a265855fba97f149bbf6576</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_partener_curent_locatii(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOMPART.PARTENER_CURENT_LOCATII')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_partener_editat</obj_name>
  <obj_hashval>c3b5950050189aa0fdacf7e60364f9a0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_partener_editat(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOMPART.PARTENER_EDITAT')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_partener_icont_analizat</obj_name>
  <obj_hashval>55a781b0cc8406e2e09d0cf37240c0a2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_partener_icont_analizat(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOMPART.PARTENER_ICONT_ANALIZAT')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_partener_sold_analizat</obj_name>
  <obj_hashval>739c92ccef7dd968347cc5477d6cd2ac</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_partener_sold_analizat(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOMPART.PARTENER_SOLD_ANALIZAT')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_refresh_oportunitati</obj_name>
  <obj_hashval>b4b7e70692de911c8e1a74a75d4405ee</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_refresh_oportunitati(acodpart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  DELETE FROM TMP_NPARTOPORTUNITATI;
  INSERT INTO TMP_NPARTOPORTUNITATI(CodOportunitate, PrefixDoc, NrDoc, DataDoc, CodCarnetDoc, CodPartener, CodMoneda, Tip, CodAgent, CodCampanie, VenitEst, VenitProb)
  SELECT O.CodOportunitate, O.PrefixDoc, O.NrDoc, O.DataDoc, O.CodCarnetDoc, O.CodPartener, O.CodMoneda, O.Tip, O.CodAgent, CP.CodCampaniePart, O.VenitEst, O.VenitProb
  FROM OPORTUNITATI O
      INNER JOIN CAMPANII     C  ON  O.CODCAMPANIE = C.CODCAMPANIE
      INNER JOIN CAMPANIIPART CP ON  C.CODCAMPANIE = CP.CODCAMPANIE
  WHERE CP.CodPart = aCodPart;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_set_codpart_sold_analizat</obj_name>
  <obj_hashval>f74139fcbced402d930ac850978c3d52</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_set_codpart_sold_analizat(acodpart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  perform set_config('PKG_NOMPART.PARTENER_SOLD_ANALIZAT', aCODPART::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_set_part_curent</obj_name>
  <obj_hashval>d1337901ed2cf65310e78a4f34cf5b67</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_set_part_curent(acodpart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMPART.PARTENER_CURENT',to_char(aCODPART,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_set_part_curent_cf</obj_name>
  <obj_hashval>c2ed07bf6c169e96200cc082415e76e8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_set_part_curent_cf(acodpart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMPART.PARTENER_CURENT_CF',to_char(aCODPART,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_set_part_curent_locatii</obj_name>
  <obj_hashval>a9ca12aaa25b5ba6693e3bfb0634ec7d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_set_part_curent_locatii(acodpart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMPART.PARTENER_CURENT_LOCATII',to_char(aCODPART,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_set_part_docrosu</obj_name>
  <obj_hashval>8c322f2dd0258104aa1f2796385212f3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_set_part_docrosu(acodpart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMPART.PART_DOC_ROSU',to_char(aCODPART,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_set_part_editat</obj_name>
  <obj_hashval>6417fd4adb7b733c80bfc22f5a46b2cd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_set_part_editat(acodpart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMPART.PARTENER_EDITAT',to_char(aCODPART,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_set_part_icont_analizat</obj_name>
  <obj_hashval>f37af35ece5e85132d89f1caa285ab0b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_set_part_icont_analizat(aicont numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMPART.PARTENER_ICONT_ANALIZAT',to_char(aICONT,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_set_tipservire_locatii</obj_name>
  <obj_hashval>0532e81b8b5008496cc10cdbc6155170</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_set_tipservire_locatii(atipservire numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMPART.TIPSERV_CURENT',to_char(aTipServire,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_setclasa_part</obj_name>
  <obj_hashval>5e6d5aa17007cc097d86ad3a46f53be2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_setclasa_part(aclasa_part numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMPART.CLASA_PART',to_char(aCLASA_PART,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_setclasapart</obj_name>
  <obj_hashval>83a8ad2adfd3e6fbd4711faf12a7697d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_setclasapart(aclasa numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMPART.CLASA_PART',to_char(aCLASA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_setct_monitor</obj_name>
  <obj_hashval>208d590db63ec96710aec5755d7dd807</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMPART.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_setpart_doc_rosu</obj_name>
  <obj_hashval>e71b2358a9d7b987b61fd87826abdbd4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_setpart_doc_rosu(apart_doc_rosu numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMPART.PART_DOC_ROSU',to_char(aPART_DOC_ROSU,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_setpartener_curent</obj_name>
  <obj_hashval>a26bc5bc17c55ca823bc1c0bc3f49e8b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_setpartener_curent(apartener_curent numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMPART.PARTENER_CURENT',to_char(aPARTENER_CURENT,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_setpartener_curent_cf</obj_name>
  <obj_hashval>d9b78ea8cf7381caae31dac8eee2fcbb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_setpartener_curent_cf(apartener_curent_cf numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMPART.PARTENER_CURENT_CF',to_char(aPARTENER_CURENT_CF,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_setpartener_curent_locatii</obj_name>
  <obj_hashval>1638af9d2d638085a65d5504afd7c772</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_setpartener_curent_locatii(apartener_curent_locatii numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMPART.PARTENER_CURENT_LOCATII',to_char(aPARTENER_CURENT_LOCATII,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_setpartener_editat</obj_name>
  <obj_hashval>b8c60f7cffcb3dc4382d71d95d51dda5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_setpartener_editat(apartener_editat numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMPART.PARTENER_EDITAT',to_char(aPARTENER_EDITAT,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_setpartener_icont_analizat</obj_name>
  <obj_hashval>db752899ac506aa117d4a2a73b4b8a29</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_setpartener_icont_analizat(apartener_icont_analizat numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMPART.PARTENER_ICONT_ANALIZAT',to_char(aPARTENER_ICONT_ANALIZAT,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_setpartener_sold_analizat</obj_name>
  <obj_hashval>7d4d7a41df11cfe21848ef0906a857ff</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_setpartener_sold_analizat(apartener_sold_analizat numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMPART.PARTENER_SOLD_ANALIZAT',to_char(aPARTENER_SOLD_ANALIZAT,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_settipserv_curent</obj_name>
  <obj_hashval>30c533221d7ef9897474784010bb3eee</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_settipserv_curent(atipserv_curent numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMPART.TIPSERV_CURENT',to_char(aTIPSERV_CURENT,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_sp_deleterecord</obj_name>
  <obj_hashval>693f6028b4edb7eed4cea8768d23b1a1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aDoc varchar;
BEGIN
  --Florin 01.06.2023 - monitor
  --Florin 12.04.2023 - sinc. Oracle (11.04.2023)
  perform pkg_nompart_setct_monitor('MON_4');
  PERFORM PKG_NOMPART_SP_LOCKRECORD( RecId);
  PERFORM PKG_CFGTABLES_EXT_DELETERECORD (recId, 500);

  SELECT 'Partener "' || den_part || '"' INTO aDoc FROM npart WHERE   codpart = recid;
  PERFORM ValidPostLog( 'MON_4',
                        'D',
                        recid,
                        CURRENT_SETTING('PKG_GLOBALS.SUBUNITATE', TRUE)::numeric,
                        null,
                        aDoc);

  DELETE FROM NPARTCONCURENTI  WHERE CodPart = RecId;
  DELETE FROM NPARTACTIVIT    WHERE CodPart = RecId;
  DELETE FROM NPARTDOMACT     WHERE CodPart = RecId;
  DELETE FROM NPART1          WHERE CODPART = RECID;
  DELETE FROM NPART1CRM       WHERE CODPART = RECID;
  DELETE FROM NPARTB          WHERE CODPART = RECID;
  DELETE FROM NPARTTR         WHERE CODPART = RECID;
  DELETE FROM NPARTDISC       WHERE CODPART = RECID;
  DELETE FROM NPARTCODFISC    WHERE CODPART = RECID;
  DELETE FROM NPARTLSTCLASE   WHERE CODPART = RECID;
  DELETE FROM SYNCPARTRETAIL  WHERE CODPART = RECID;

  FOR V_REC IN (SELECT * FROM NAGENDA WHERE CODPART = RECID) LOOP
    DELETE FROM NAGENDA1 WHERE CODAGENDA = V_REC.CODAGENDA;
    DELETE FROM NAGENDA  WHERE CODAGENDA = V_REC.CODAGENDA;
  END LOOP;

  DELETE FROM NPERSCONTACT WHERE CODPART = RecId;
  DELETE FROM NARTCLI      WHERE CodPart = RecId;
  DELETE FROM NPART        WHERE CodPart = RecId;

  PERFORM NotifyModif( 2, RECID, 'NPART');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_sp_insertrecord</obj_name>
  <obj_hashval>0ab9bb9f210b04ba0648abee5a6ab13c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 12.04.2023 - sinc. Oracle (11.04.2023)
  INSERT INTO TMP_NPART(CodPart) VALUES(0);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(500);
  /*
  IF  (SELECT pkg_categconst_GetValConstanta.WME_RESULT::numeric FROM pkg_categconst_GetValConstanta(NULL, 'DiscPartImplicit', TO_NUMBER(current_setting('PKG_GLOBALS.ANLUCRU', true),'999999999999999999'), TO_NUMBER(current_setting('PKG_GLOBALS.LUNALUCRU', true),'999999999999999999'))) &gt; 0
  THEN
  INSERT INTO TMP_NPARTDISC
  (
  CodPartDisc, CodPart, CodCategDisc, Indexlocal, Cumulat, Offinvoice
  )
  SELECT -1, 0, D.CODCRITERIU, 1, D.Cumulat, D.Offinvoice
  FROM CRITERIIDISC D
  WHERE
     D.CODCRITERIU = (SELECT pkg_categconst_GetValConstanta.WME_RESULT::numeric FROM pkg_categconst_GetValConstanta(NULL, 'DiscPartImplicit', TO_NUMBER(current_setting('PKG_GLOBALS.ANLUCRU', true),'999999999999999999'), TO_NUMBER(current_setting('PKG_GLOBALS.LUNALUCRU', true),'999999999999999999')));
  END IF;
  */
--&lt;sstcommit&gt;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_str_codfiscal</obj_name>
  <obj_hashval>1f0835a85ee97778d171a1005c30f14c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_str_codfiscal(INOUT wme_result character varying, INOUT acodfiscal character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  ACODFISC varchar := '';
begin
  aCODFISC := REPLACE( REPLACE( UPPER( aCODFISCAL), ' ', ''), '-', '');
  aCODFISC := REPLACE( UPPER( aCODFISCAL), '.', '');
  WME_Result :=  REPLACE( aCODFISC, 'RO', '');
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_tipserv_curent</obj_name>
  <obj_hashval>a9304d044760c8962787a011fa535494</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_tipserv_curent(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_NOMPART.TIPSERV_CURENT', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_tipservire_locatii_ok</obj_name>
  <obj_hashval>6c8b2f24c00e2e4941ef5fbfab506329</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_tipservire_locatii_ok(INOUT wme_result numeric, INOUT amodservire numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vModServire numeric := Coalesce( aModServire, 0);
begin
  IF (Coalesce( TO_NUMBER(current_setting('PKG_NOMPART.TIPSERV_CURENT', true),'999999999999999999'), 0) = 0)
      OR
     (Coalesce( TO_NUMBER(current_setting('PKG_NOMPART.TIPSERV_CURENT', true),'999999999999999999'), 0) = 1 AND  vModServire = 1)
      OR
     (Coalesce( TO_NUMBER(current_setting('PKG_NOMPART.TIPSERV_CURENT', true),'999999999999999999'), 0) = 2 AND  vModServire &gt; 1)
  THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    WME_Result :=  0;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_tvalaincasare</obj_name>
  <obj_hashval>27a7a0d1ca732f889141fa9c3ce4aee0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_tvalaincasare(INOUT wme_result numeric, INOUT acodfiscal character varying, INOUT adate character varying DEFAULT NULL::character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sCUI  VARCHAR(50) := Upper (REGEXP_REPLACE(aCodFiscal,'\W+', '', 'g'));
  nCUI  VARCHAR(50) := NULLIF(REGEXP_REPLACE(aCodFiscal,'\D+', '', 'g'),'');
  dDate DATE        := Coalesce(TO_DATE(aDate, 'dd.mm.yyyy'),  To_Date('9999','yyyy'));
  vRes  NUMERIC;
BEGIN
  -- Stef 28.08.2023
  IF SubStr(sCUI,1,2) = 'RO'
  THEN sCui := SubStr(sCui, 3);
  END IF;

  IF    nCUI IS NULL THEN -- CUI invalid
    vRes := NULL;
  ELSIF nCui &lt;&gt; sCui THEN -- CUI non RO
    vRes := NULL;
  ELSE
    BEGIN
      SELECT tvalaincasare
      INTO STRICT vRes
      FROM (
        SELECT r.tvalaincasare, Row_Number() OVER (ORDER BY r.id DESC) IDX
        FROM WINMADMIN.RTVAI_ISTORIC R
        WHERE r.cod_fiscal = To_Number(nCUI) AND Coalesce(r.data_sfarsit, r.data_inceput) &lt;= dDate
      ) ssub
      WHERE idx = 1;
    EXCEPTION WHEN OTHERS THEN
      vRes := 0;
    END;
  END IF;
  WME_Result :=  vRes;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_updatenpart1double</obj_name>
  <obj_hashval>4a750d5e40404cc59847ead876861c3c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_updatenpart1double(camp character varying, pvaloare numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Bogdan 29.03.2022 - 53634 Modificare valori: la parteneri, limita de creditare
  PERFORM PKG_NOMPART_UpdateNPART1String(camp, replace(pvaloare::varchar, ',', '.'));
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_updatenpart1integer</obj_name>
  <obj_hashval>ca67b1962c6755b0d848023fa701324e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_updatenpart1integer(camp character varying, pvaloare numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Bogdan 29.03.2022 - 53634 Modificare valori: la parteneri, limita de creditare
  PERFORM PKG_NOMPART_UpdateNPART1String(camp, pvaloare::varchar);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_updatenpart1string</obj_name>
  <obj_hashval>a56d27b775bac55eff7bd2f669d3197e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_updatenpart1string(camp character varying, pvaloare character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
  DECLARE
    V_REC   RECORD;
    sString varchar;
  BEGIN
    --Bogdan 29.03.2022 - 53634 Modificare valori: la parteneri, limita de creditare
    FOR v_rec IN ( select part1.*
              from npart1 part1 inner join TMP_MANEVRA_LISTE tmp ON VALOARE::numeric = part1.CODPART AND FILTRU = 'CODPART'
              WHERE GetANLUCRU()*12+GetLunaLUCRU() BETWEEN part1.alstart AND part1.alstop
                AND GetANLUCRU()*12+GetLunaLUCRU()   &lt;&gt; part1.anstart*12+part1.lunastart
              order by part1.CODPART )
    LOOP
      INSERT INTO npart1 (CODPART1, CODPART, CODIOPART,
                CREDITCLIENT, VOLUMTRANZC,
                CREDITFURN, VOLUMTRANZF,
                ANSTART, LUNASTART,
                SCADENTAV, SCADENTAC,
                DISCOUNT, CASSBAZAMIN,
                SIMBOLCASS, GDPR)
      VALUES (
        NEXTVAL ('seq_npart1_codpart1') , v_Rec.CODPART, v_Rec.CODIOPART,
        v_Rec.CREDITCLIENT, v_Rec.VOLUMTRANZC,
        v_Rec.CREDITFURN, v_Rec.VOLUMTRANZF,
        GetANLUCRU() , GetLunaLUCRU(),
        v_Rec.SCADENTAV, v_Rec.SCADENTAC,
        v_Rec.DISCOUNT, v_Rec.CASSBAZAMIN,
        v_Rec.SIMBOLCASS, v_Rec.GDPR);

      CALL prc_al_refresh('npart1', v_Rec.CODPART);
    END LOOP;

    FOR v_rec IN (select part1.CODPART1
            from npart1 part1 inner join TMP_MANEVRA_LISTE ON VALOARE::numeric = part1.CODPART AND FILTRU = 'CODPART'
            WHERE GetANLUCRU()*12+GetLunaLUCRU() BETWEEN part1.alstart AND part1.alstop
          order by part1.CODPART
                 )
    LOOP
      sString := 'update npart1 set ' || Camp || ' = ' || coalesce(pValoare,'') || ' where CODPART1 = ' || v_Rec.CODPART1;
      EXECUTE sString;
    END LOOP;
  end;
  $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_ct_monitor</obj_name>
  <obj_hashval>1ca8bdb51ac3f13d4f9bbab5aabc30dd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_NOMPERS.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_5';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_get_cod_npers1</obj_name>
  <obj_hashval>094b0a0b4d1212331c1868187889895e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_get_cod_npers1(INOUT wme_result numeric, INOUT acodpers numeric, INOUT aan numeric, INOUT aluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  CPERS1 numeric := -1;
begin
  --Florin 11.01.2022 - sinc. Oracle (29.12.2021)
  BEGIN
    SELECT COALESCE( CODPERS1, 0)
    INTO CPERS1
    FROM NPERS1 N1
      WHERE N1.CODPERS = ACODPERS AND aAn*12+aLuna BETWEEN n1.alstart AND n1.alstop;
  EXCEPTION WHEN OTHERS THEN
    CPERS1 := -1;
  END;

  WME_Result :=  CPERS1;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_get_icontpers_curent</obj_name>
  <obj_hashval>6b79e0c7fcf2654e6ec06d8c8c7abe6a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_get_icontpers_curent(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER((current_setting('PKG_NOMPERS.ICONT_PERS_CURENT',true)),'999999999999999999');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_get_monedapers_curent</obj_name>
  <obj_hashval>80c2238f709a193f1a9252a70cbc610d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_get_monedapers_curent()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 25 septembrie 2020
  RETURN TO_NUMBER(current_setting('PKG_NOMPERS.MONEDA_PERS_CURENT',true),'999999999999999999');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_get_monedapers_curent</obj_name>
  <obj_hashval>31d5c17291a948e60ba04a7a6711a400</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_get_monedapers_curent(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER((current_setting('PKG_NOMPERS.MONEDA_PERS_CURENT',true)),'999999999999999999');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_get_numeprenume</obj_name>
  <obj_hashval>d5f15dea7cdbda36b9394cf589d1fd67</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_get_numeprenume(INOUT wme_result character varying, INOUT acodpers numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
sNM varchar;
begin
BEGIN
SELECT nume || ' ' || prenume
INTO sNM
FROM npers
WHERE
   codpers = acodpers;
EXCEPTION WHEN OTHERS THEN
sNM := '';
END;
WME_Result :=  sNM;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_get_pers_cod_caract_luna</obj_name>
  <obj_hashval>b70165bda85306cbeaab950523108b60</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_get_pers_cod_caract_luna(INOUT wme_result numeric, INOUT acodpers numeric, INOUT aan numeric, INOUT aluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  ACODIOPERS  numeric := -1;
  ACODIOPERS1 numeric := -1;
begin
  --Florin 11.01.2022 - sinc. Oracle (29.01.2021)
  BEGIN
    SELECT COALESCE( CODIOPERS, 0)
    INTO ACODIOPERS
    FROM NPERS1 N1
      WHERE N1.CODPERS = ACODPERS AND aAn*12+aLuna BETWEEN n1.alstart AND n1.alstop;
  EXCEPTION WHEN OTHERS THEN
    ACODIOPERS1 := -1;
  END;

  IF  ACODIOPERS &gt; 0 THEN
    BEGIN
      SELECT COALESCE( CODIOPERS1, 0)
      INTO ACODIOPERS1
      FROM IOPERS1 I1
         WHERE I1.CODIOPERS = ACODIOPERS AND aAn*12+aLuna BETWEEN i1.alstart AND i1.alstop;
    EXCEPTION WHEN OTHERS THEN
      ACODIOPERS1 := -1;
    END;
  END IF;

  WME_Result :=  ACODIOPERS1;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_get_pers_cod_caract_luna</obj_name>
  <obj_hashval>22f53c5a171f2e7afdf5ce9521ac16b5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_get_pers_cod_caract_luna(acodpers numeric, aan numeric, aluna numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  ACODIOPERS numeric := -1;
  ACODIOPERS1 numeric := -1;
BEGIN
  --Florin 04.08.2020
  --Florin 11.01.2022 - sinc. Oracle (27.12.2021)
  BEGIN
    SELECT COALESCE( CODIOPERS, 0)
    INTO ACODIOPERS
    FROM NPERS1 N1
        WHERE N1.CODPERS = ACODPERS AND aAn*12+aLuna BETWEEN n1.alstart AND n1.alstop;
  EXCEPTION WHEN OTHERS THEN
    ACODIOPERS1 := -1;
  END;

  IF  ACODIOPERS &gt; 0 THEN
    BEGIN
      SELECT COALESCE( CODIOPERS1, 0)
      INTO ACODIOPERS1
      FROM IOPERS1 I1
         WHERE I1.CODIOPERS = ACODIOPERS AND aAn*12+aLuna BETWEEN i1.alstart AND i1.alstop;
    EXCEPTION WHEN OTHERS THEN
      ACODIOPERS1 := -1;
    END;
  END IF;

  RETURN ACODIOPERS1;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_get_persoana_curenta</obj_name>
  <obj_hashval>d899822208ae99f7f41dfe4b56e75b4f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_get_persoana_curenta(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER((current_setting('PKG_NOMPERS.PERSOANA_CURENTA',true)),'999999999999999999');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_get_persoana_curenta</obj_name>
  <obj_hashval>d1563d71b841dbef4259ed50132933bb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_get_persoana_curenta()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 25 septembrie 2020
  RETURN TO_NUMBER(current_setting('PKG_NOMPERS.PERSOANA_CURENTA',true),'999999999999999999');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_get_record_pers_caract_luna</obj_name>
  <obj_hashval>337be944a3bcdc0650435e0e22cf09b8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_get_record_pers_caract_luna(INOUT wme_result refcursor, INOUT acodpers numeric, INOUT an numeric, INOUT luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
TMPCURSOR REFCURSOR;
IOPERSCOD numeric;
begin
  --Florin 11.01.2022 - sinc. Oracle (29.12.2021)
BEGIN
SELECT COALESCE( CODIOPERS, -1)
INTO IOPERSCOD
FROM NPERS1 N1
    WHERE N1.CODPERS = ACODPERS AND An*12+Luna BETWEEN n1.alstart AND n1.alstop;
EXCEPTION WHEN OTHERS THEN
IOPERSCOD := -1;
END;
IF  IOPERSCOD &gt; 0
THEN
BEGIN
OPEN TMPCURSOR FOR
SELECT *
FROM IOPERS1 I1
   WHERE I1.CODIOPERS = IOPERSCOD AND An*12+Luna BETWEEN i1.alstart AND i1.alstop;
EXCEPTION WHEN OTHERS THEN
OPEN TMPCURSOR FOR
SELECT -1;
END;
ELSE
OPEN TMPCURSOR FOR
SELECT -1;
END IF;
WME_Result :=  TMPCURSOR;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_getct_monitor</obj_name>
  <obj_hashval>0f1b41236c7a9a691f32a6916b2c282d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_NOMPERS.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_5';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_getdatan</obj_name>
  <obj_hashval>17f138d99283cd9fcb418c0093202abd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_getdatan(acnp character varying)
 RETURNS date
 LANGUAGE plpgsql
AS $function$
DECLARE
  sy varchar(4);
  sm varchar(2);
  sd varchar(2);
  oData date;
  y numeric(4);
  m numeric(2);
  d numeric(2);
  FirstChar char;
BEGIN
  --Florin 28.10.2022 - fixat 55946
  --Florin 01.09.2022 - sinc. Oracle
  --Florin 20.07.2022 - sinc. Oracle
  BEGIN
    oData := Null;
    if Length(acnp) &lt; 6 then return oData; end if;

    sy := Substr(acnp, 2, 2);
    sm := Substr(acnp, 4, 2);
    sd := Substr(acnp, 6, 2);

    FirstChar := Substr(acnp, 1, 1);
    begin
      y := to_number(sy);
    exception when others then y := 0;
    end;
    if y = 0 then return oData; end if;

    if (FirstChar = '1') or (FirstChar = '2')
    then y := y + 1900;
    else
      if (FirstChar = '5') or (FirstChar = '6')
         then y := y + 2000;
         else if (FirstChar = '3') or (FirstChar = '4')
              then y := y + 2100;
              end if;
      end if;
    end if;

    begin
      m := To_number(sm);
    exception when others then m := 0;
    end;
    if m = 0 then return odata; end if;
    begin
      d := To_number(sd);
    exception when others then d := 0;
    end;
    if d = 0 then return odata; end if;
    return to_date(lpad(to_char(d),2,'0')||'.'||lpad(to_char(m),2,'0')||'.'||to_char(y), 'dd.mm.yyyy');
    exception when others then return odata;
  END;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_geticont_pers_curent</obj_name>
  <obj_hashval>b58107a8b34876d2bbcc8cedfd5e8860</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_geticont_pers_curent(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOMPERS.ICONT_PERS_CURENT')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_getmoneda_pers_curent</obj_name>
  <obj_hashval>4b70307588ad94ff3fda98749554d0b1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_getmoneda_pers_curent(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOMPERS.MONEDA_PERS_CURENT')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_getpersoana_curenta</obj_name>
  <obj_hashval>7285136875e3c803d8334f3b38608432</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_getpersoana_curenta(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOMPERS.PERSOANA_CURENTA')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_icont_pers_curent</obj_name>
  <obj_hashval>2f84b6be5b72943ee768fc621cb6e910</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_icont_pers_curent(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOMPERS.ICONT_PERS_CURENT')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_moneda_pers_curent</obj_name>
  <obj_hashval>a8d9466771ae0d90554277784491df4e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_moneda_pers_curent(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOMPERS.MONEDA_PERS_CURENT')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_persoana_curenta</obj_name>
  <obj_hashval>ac4d7d4bcb0b8803a4ae9c68d8b8dd4d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_persoana_curenta(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOMPERS.PERSOANA_CURENTA')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_propagadiscvalag</obj_name>
  <obj_hashval>39aa5d8127325233cb811b1d3997b100</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_propagadiscvalag(acodpers numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  V_AG1 RECORD;
  aCod  numeric;
begin
  FOR v_rec IN (SELECT ag1.codagent1 FROM tmp_npers_manevra tmp INNER JOIN nagenti1 ag1 ON  tmp.codpers = ag1.codpers WHERE tmp.codpers &lt;&gt; aCodPers) LOOP
    DELETE FROM nagentiproc WHERE codagent1 = v_rec.codagent1;
    DELETE FROM nagentival  WHERE codagent1 = v_rec.codagent1;
    DELETE FROM nagenti1    WHERE codagent1 = v_rec.codagent1;
  END LOOP;

  FOR v_rec IN (SELECT codpers FROM tmp_npers_manevra WHERE codpers &lt;&gt; aCodPers) LOOP
    FOR v_ag1 IN (SELECT * FROM nagenti1 WHERE codpers = aCodPers) LOOP
      SELECT NEXTVAL('SEQ_NAGENTI1_CODAGENT1') INTO aCod;

      INSERT INTO nagenti1(codagent1, codpers, datastart)
      VALUES(aCod, v_rec.codpers, v_ag1.datastart);

      INSERT INTO nagentiproc(codagentproc, codagent1, codpers, codobiect, peclasea, codpart, peclasep, proc)
      SELECT NEXTVAL('SEQ_NAGENTIPROC_CODAGENTPROC'), aCod, v_rec.codpers, codobiect, peclasea, codpart, peclasep, proc
      FROM nagentiproc WHERE codagent1 = v_ag1.codagent1;

      INSERT INTO nagentival(codagentval, codagent1, codpers, codmoneda, valmax)
      SELECT NEXTVAL('SEQ_NAGENTIVAL_CODAGENTVAL'), aCod, v_rec.codpers, codmoneda, valmax
      FROM nagentival WHERE codagent1 = v_ag1.codagent1;
    END LOOP;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_set_icontpers_curent</obj_name>
  <obj_hashval>c63ee5c53645dd6e662ecf6f38bc08e7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_set_icontpers_curent(aicont numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMPERS.ICONT_PERS_CURENT',to_char(AICONT,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_set_monedapers_curent</obj_name>
  <obj_hashval>599b8c28e5a0668f3f740b37ceb3553c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_set_monedapers_curent(amoneda numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMPERS.MONEDA_PERS_CURENT',to_char(AMONEDA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_set_persoana_curenta</obj_name>
  <obj_hashval>9d74a50737cbce0a48217d64acb49bae</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_set_persoana_curenta(acodpers numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMPERS.PERSOANA_CURENTA',to_char(ACODPERS,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_seticont_pers_curent</obj_name>
  <obj_hashval>2c32e959156091bb32b2708d960fd467</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_seticont_pers_curent(aicont_pers_curent numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMPERS.ICONT_PERS_CURENT',to_char(aICONT_PERS_CURENT,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_setmoneda_pers_curent</obj_name>
  <obj_hashval>94b640e5161beb2f342c8f3904d4beea</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_setmoneda_pers_curent(amoneda_pers_curent numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMPERS.MONEDA_PERS_CURENT',to_char(aMONEDA_PERS_CURENT,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_setpersoana_curenta</obj_name>
  <obj_hashval>2210b9ed5b2b5481f937a1b6e1726e44</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_setpersoana_curenta(apersoana_curenta numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMPERS.PERSOANA_CURENTA',to_char(aPERSOANA_CURENTA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_sp_deleterecord</obj_name>
  <obj_hashval>b7bb0ee6a253b7ed2cb1be2d9ecc1f9f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDoc       varchar;
  ACODAGENDA numeric;
BEGIN
  --Florin 01.06.2023 - monitor
  --Florin 12.04.2023 - sinc. Oracle
  --Florin 03.06.2022 - fixat 54504
  --Florin 23.09.2020 - fixat #39244
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_nompers_setct_monitor('MON_5');
  PERFORM PKG_NOMPERS_SP_LOCKRECORD( RecId);
  PERFORM PKG_CFGTABLES_EXT_DELETERECORD (recId, 502);

  IF (SELECT wme_result FROM PKG_USERFIRME_ValidPostLog(NULL, current_setting('PKG_GLOBALS.USERID', TRUE)::numeric, current_setting('PKG_NOMPERS.CT_MONITOR', TRUE)))
  THEN
    SELECT 'Persoana "' || Nume || ' ' || Prenume || '"' INTO aDoc FROM npers WHERE codpers = recid;
    PERFORM pkg_userfirme_postlogcucommit('NPERS', current_setting('PKG_GLOBALS.USERNAME', TRUE), 'S', RECID, current_setting('PKG_GLOBALS.FIRMANAME', TRUE), current_setting('PKG_GLOBALS.SUBUNITATE', TRUE)::NUMERIC, null, aDoc, null, (SELECT WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  SELECT AGENDA INTO ACODAGENDA FROM NPERS WHERE CODPERS = RECID;

  DELETE FROM NAGENTIPROC WHERE CODPERS = RECID;
  DELETE FROM NAGENTIVAL  WHERE CODPERS = RECID;
  DELETE FROM NAGENTI1    WHERE CODPERS = RECID;
  DELETE FROM NPERS1      WHERE CODPERS = RECID;
  DELETE FROM NPERSCVSCOL WHERE CODPERS = RECID;
  DELETE FROM NPERSCVLOCM WHERE CODPERS = RECID;
  DELETE FROM NPERSCVSKIL WHERE CODPERS = RECID;
  DELETE FROM NPERSCVPAS  WHERE CODPERS = RECID;
  DELETE FROM NAGENDA     WHERE CODAGENDA = ACODAGENDA;
  DELETE FROM NPERS       WHERE CODPERS = RECID;

  PERFORM NotifyModif( 2, RECID, 'NPERS');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_sp_insertrecord</obj_name>
  <obj_hashval>48d85b4adf4618804ae44b01ccd49164</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NPERS(CODPERS) VALUES(0);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(502);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_sp_lockrecord</obj_name>
  <obj_hashval>7b3895c55e1fcf0fbaa7f08ca40797fb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMP numeric;
begin
  SELECT CODPERS INTO TMP FROM NPERS WHERE CODPERS = RECID FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomremauto_sp_deleterecord</obj_name>
  <obj_hashval>88d92422062abc8b952a4144c4155756</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomremauto_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_NOMREMAUTO_SP_LOCKRECORD( RecId);
  DELETE FROM NREMAUTO WHERE CodRemAuto = RecId;
  PERFORM NotifyModif( 2, RECID, 'NREMAUTO');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomremauto_sp_gotorecord</obj_name>
  <obj_hashval>a115376515e6b2f3bad8eb64ea8ad000</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomremauto_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NREMAUTO(CodRemAuto, TipuriRemorci, Spor_150_1, Spor_150_2, Spor150_215_1, Spor150_215_2, Spor215_1, Spor215_2)
  (SELECT CodRemAuto, TipuriRemorci, Spor_150_1, Spor_150_2, Spor150_215_1, Spor150_215_2, Spor215_1, Spor215_2
   FROM NREMAUTO WHERE CodRemAuto = RecId
  );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomremauto_sp_insertrecord</obj_name>
  <obj_hashval>83955fc42343efe5fbd18d355d202e91</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomremauto_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NREMAUTO(CodRemAuto) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomremauto_sp_lockrecord</obj_name>
  <obj_hashval>decb3b982eb853e5533e7f0a35429dae</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomremauto_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodRemAuto INTO Tmp FROM NREMAUTO WHERE CodRemAuto = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomremauto_sp_postrecords</obj_name>
  <obj_hashval>73a7ca05bd9513f23c1c7297bab261a7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomremauto_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    SELECT CodRemAuto INTO RecId FROM TMP_NREMAUTO;

    UPDATE NREMAUTO
    SET
    (TipuriRemorci, Spor_150_1, Spor_150_2, Spor150_215_1, Spor150_215_2, Spor215_1, Spor215_2)
    =
    (SELECT TipuriRemorci, Spor_150_1, Spor_150_2, Spor150_215_1, Spor150_215_2, Spor215_1, Spor215_2 FROM TMP_NREMAUTO)
    WHERE
     CodRemAuto = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_NREMAUTO_CODREMAUTO') INTO RecId;

    INSERT INTO NREMAUTO(CodRemAuto, TipuriRemorci, Spor_150_1, Spor_150_2, Spor150_215_1, Spor150_215_2, Spor215_1, Spor215_2)
    (SELECT RecId, TipuriRemorci, Spor_150_1, Spor_150_2, Spor150_215_1, Spor150_215_2, Spor215_1, Spor215_2 FROM TMP_NREMAUTO);
  END IF;

  PERFORM NotifyModif( OPERATION, RECID, 'NREMAUTO');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomrestaurante_sp_deleterecord</obj_name>
  <obj_hashval>5ae2d94076b808fe5ded4e29abc0deed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomrestaurante_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  PERFORM PKG_NOMRESTAURANTE_SP_LOCKRECORD( RecId);

  FOR V_REC IN (SELECT * FROM RESTAURANTE WHERE CODRESTAURANT = RECID) LOOP
    DELETE FROM RESTAURANTE WHERE CODRESTAURANT = V_REC.CODRESTAURANT;
  END LOOP;

  PERFORM NotifyModif( 2, RECID, 'RESTAURANTE');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomrestaurante_sp_gotorecord</obj_name>
  <obj_hashval>bb64b79ef649c4e4436a17201f535a46</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomrestaurante_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_RESTAURANTE(CODRESTAURANT, DENUMIRE, SUBUNITATEA, TIPORAR, ORASTART, ORAEND, TIPUNICITATE, TIPGESTIMPLICITA, POSTWMRETAIL, CODPOSTRETAIL)
  SELECT CODRESTAURANT, DENUMIRE, SUBUNITATEA, COALESCE( TIPORAR, 0), ORASTART, ORAEND, COALESCE( TIPUNICITATE, 0), COALESCE( TIPGESTIMPLICITA, 0), COALESCE( POSTWMRETAIL, 0), COALESCE( CODPOSTRETAIL, 0)
  FROM RESTAURANTE
  WHERE CODRESTAURANT = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomrestaurante_sp_insertrecord</obj_name>
  <obj_hashval>de33d5b165dab5f09d54d1e784619f3b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomrestaurante_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_RESTAURANTE(CODRESTAURANT) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomrestaurante_sp_lockrecord</obj_name>
  <obj_hashval>a9362665f7f059669a45fd1ee7dc5a32</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomrestaurante_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CODRESTAURANT INTO Tmp FROM RESTAURANTE WHERE CODRESTAURANT = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomrestaurante_sp_postrecords</obj_name>
  <obj_hashval>c44f710734e2f796ed0d07e922033732</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomrestaurante_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    SELECT CODRESTAURANT INTO RecId FROM TMP_RESTAURANTE;

    UPDATE RESTAURANTE
    SET
    (DENUMIRE, SUBUNITATEA, TIPORAR, ORASTART, ORAEND, TIPUNICITATE, TIPGESTIMPLICITA, POSTWMRETAIL, CODPOSTRETAIL)
    =
    (SELECT DENUMIRE, SUBUNITATEA, TIPORAR, ORASTART, ORAEND, TIPUNICITATE, TIPGESTIMPLICITA, POSTWMRETAIL, CODPOSTRETAIL FROM TMP_RESTAURANTE)
    WHERE
     CODRESTAURANT = RECID;
  ELSE
    SELECT NEXTVAL('SEQ_RESTAURANTE_CODRESTAURANT') INTO RECID;

    INSERT INTO RESTAURANTE(CODRESTAURANT, DENUMIRE, SUBUNITATEA, TIPORAR, ORASTART, ORAEND, TIPUNICITATE, TIPGESTIMPLICITA, POSTWMRETAIL, CODPOSTRETAIL)
    SELECT RECID, DENUMIRE, SUBUNITATEA, TIPORAR, ORASTART, ORAEND, TIPUNICITATE, TIPGESTIMPLICITA, POSTWMRETAIL, CODPOSTRETAIL
    FROM TMP_RESTAURANTE;
  END IF;

  PERFORM NotifyModif( OPERATION, RECID, 'RESTAURANTE');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomsubunit_catecarnete</obj_name>
  <obj_hashval>4a3c1173dd979fb6ff7fa3fb0e7fe217</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomsubunit_catecarnete(INOUT wme_result numeric, INOUT acodsubunit numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  iResult numeric;
begin
  SELECT count( *) INTO iResult FROM doccarnete WHERE subunitatea = aCodSubunit;

  WME_Result :=  iResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomsubunit_ct_monitor</obj_name>
  <obj_hashval>be65192c6c7e4fcdf307d81e1b2565ba</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomsubunit_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_NOMSUBUNIT.CT_MONITOR', true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_7';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomsubunit_genereazacarnete</obj_name>
  <obj_hashval>ca065248a589e47903558bed67b961ac</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomsubunit_genereazacarnete(INOUT wme_result numeric, INOUT acodsubunit numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC         RECORD;
  V_REC_DOCLINK RECORD;
  V_REC_DOCFREE RECORD;
  IRESULT       numeric := 0;
  ACODCARNET    numeric;
begin
  FOR V_REC IN (SELECT CODCARNET, SIMBOL, DENUMIRE, SERIE, STARTNR, ENDNR, FREENR, INACTIV, SUBUNITATEA, LIMITA FROM SRC_DOCCARNETE) LOOP
    SELECT NEXTVAL('SEQ_DOCCARNETE_CODCARNET') INTO ACODCARNET;

    INSERT INTO DOCCARNETE(CODCARNET, SIMBOL,      DENUMIRE,      SERIE,      STARTNR,      ENDNR,      FREENR,      INACTIV,      SUBUNITATEA,LIMITA)
    VALUES                (ACODCARNET,V_REC.SIMBOL,V_REC.DENUMIRE,V_REC.SERIE,V_REC.STARTNR,V_REC.ENDNR,V_REC.FREENR,V_REC.INACTIV,ACODSUBUNIT,V_REC.LIMITA);
    IRESULT := IRESULT + 1;

    FOR V_REC_DOCLINK IN (SELECT CODDOCLINK,CODMACHETA FROM SRC_DOCLINK WHERE CODCARNET = V_REC.CODCARNET) LOOP
      INSERT INTO DOCLINK(CODDOCLINK,CODCARNET,CODMACHETA) VALUES (NEXTVAL('SEQ_DOCLINK_CODDOCLINK'),ACODCARNET,V_REC_DOCLINK.CODMACHETA);
    END LOOP;

    FOR V_REC_DOCFREE IN (SELECT CODDOCFREE,STARTNR,ENDNR FROM SRC_DOCFREE WHERE CODCARNET = V_REC.CODCARNET) LOOP
      INSERT INTO DOCFREE(CODDOCFREE,CODCARNET,STARTNR,ENDNR) VALUES (NEXTVAL('SEQ_DOCFREE_CODDOCFREE'),ACODCARNET,V_REC_DOCFREE.STARTNR,V_REC_DOCFREE.ENDNR);
    END LOOP;
  END LOOP;

  WME_Result :=  IRESULT;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomsubunit_get_cod_nsubunit1</obj_name>
  <obj_hashval>43aefc6ac8ceaf3ec7da560989f3baad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomsubunit_get_cod_nsubunit1(INOUT wme_result numeric, INOUT acodsubunit numeric, INOUT aan numeric, INOUT aluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  CSUBUNIT1 numeric := -1;
begin
  --Florin 30.12.2021 - sinc. Oracle (29.12.2021)
  BEGIN
    SELECT COALESCE( CODSUBUNIT1, 0)
    INTO CSUBUNIT1
    FROM NSUBUNIT1 N1
      WHERE N1.CODSUBUNIT = ACODSUBUNIT AND aAn*12+aLuna BETWEEN n1.alstart AND n1.alstop;
  EXCEPTION WHEN OTHERS THEN
    CSUBUNIT1 := -1;
  END;

  WME_Result :=  CSUBUNIT1;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomsubunit_get_subunit_cod_caract_luna</obj_name>
  <obj_hashval>bd7820a3a80a6f9b8e75c18863bde17c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomsubunit_get_subunit_cod_caract_luna(INOUT wme_result numeric, INOUT acodsubunit numeric, INOUT aan numeric, INOUT aluna numeric, INOUT acodiofilial numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  ACODIOFILIAL1 numeric := -1;
begin
  --Florin 30.12.2021 - sinc. Oracle (29.12.2021)
  ACODIOFILIAL := -1;
  BEGIN
    SELECT COALESCE( CODIOFILIAL, 0)
    INTO ACODIOFILIAL
    FROM NSUBUNIT1 N1
      WHERE N1.CODSUBUNIT = ACODSUBUNIT AND aAn*12+aLuna BETWEEN n1.alstart AND n1.alstop;
  EXCEPTION WHEN OTHERS THEN
    ACODIOFILIAL1 := -1;
  END;

  IF  ACODIOFILIAL &gt; 0 THEN
    BEGIN
      SELECT COALESCE( CODIOFILIAL1, 0)
      INTO ACODIOFILIAL1
      FROM IOFILIAL1 I1
        WHERE I1.CODIOFILIAL = ACODIOFILIAL AND aAn*12+aLuna BETWEEN i1.alstart AND i1.alstop;
    EXCEPTION WHEN OTHERS THEN
      ACODIOFILIAL1 := -1;
    END;
  END IF;

  WME_Result :=  ACODIOFILIAL1;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomsubunit_getct_monitor</obj_name>
  <obj_hashval>04c7f4cc87410d80d20b7cef6a4a0f43</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomsubunit_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_NOMSUBUNIT.CT_MONITOR', true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_7';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomsubunit_getdensubunit</obj_name>
  <obj_hashval>ec04e73fcf733c59fab0dae7a4a2bcbc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomsubunit_getdensubunit(INOUT wme_result character varying, INOUT acod numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult varchar;
begin
  SELECT den_subunit INTO sResult FROM nsubunit WHERE codsubunit = aCod;

  WME_Result :=  sResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomsubunit_setct_monitor</obj_name>
  <obj_hashval>c83d49adf39bce3b2966deef76a21f0c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomsubunit_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_NOMSUBUNIT.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomsubunit_sp_deleterecord</obj_name>
  <obj_hashval>3001d7789236020048e6ee28abe9ff54</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomsubunit_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  AdoC varchar;
BEGIN
  --Florin 30.09.2024 - sinc. Oracle
  --Florin 01.06.2023 - monitor
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_nomsubunit_setct_monitor('MON_7');
  IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999'), current_setting('PKG_NOMSUBUNIT.CT_MONITOR', true)))
  THEN
    SELECT 'subunitate "' || coalesce(n.DEN_SUBUNIT,'') || '"'
    INTO aDoc
    FROM NSUBUNIT n
    WHERE N.CODSUBUNIT = RECID;

    PERFORM pkg_userfirme_postlogcucommit( 'NSUBUNIT', current_setting('PKG_GLOBALS.USERNAME', true), 'S', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), TO_NUMBER(current_setting('PKG_GLOBALS.SUBUNITATE', true),'999999999999999999'), null, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  PERFORM PKG_NOMSUBUNIT_SP_LOCKRECORD( RecId);
  DELETE FROM NSUBUNIT1 WHERE CODSUBUNIT = RECID;
  DELETE FROM NSUBUNIT WHERE CODSUBUNIT = RECID;
  PERFORM NotifyModif( 2, RECID, 'NSUBUNIT');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomsubunit_sp_gotorecord</obj_name>
  <obj_hashval>5194e1dfbb861845ee166768853e5c45</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomsubunit_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 07.07.2025 - sinc. Oracle
  --Florin 20.09.2024 - fixat 63417
  --Stef 28.05.2024 - sinc. Oracle
  perform pkg_nomsubunit_setct_monitor('MON_7');
  INSERT INTO  TMP_NSUBUNIT (
    CODSUBUNIT,DEN_SUBUNIT,CIF, SATELITWM, ANPORNIRE, LUNAPORNIRE, NUMEPRESC, REGCOM,
    CODBANKCONT, CODBANKCONTTREZ, CODCATPRET,  CODBANCA, NRCONT, CODBANCATREZ, NRCONTTREZ, NoEconomicActiv, CODSIUI, CODCASA, CodPers, CAPITAL_SOCIAL,
    EFACT, TIPUNITJURIDICA )
  SELECT
    S.CODSUBUNIT, S.DEN_SUBUNIT, S.cif, S.SATELITWM, S.ANPORNIRE, S.LUNAPORNIRE, S.NUMEPRESC, S.REGCOM,
    S.CODBANKCONT, S.CODBANKCONTTREZ, S.CODCATPRET, NBK.CODBANK, NBK.NRCONT, NBKTREZ.CODBANK, NBKTREZ.NRCONT, Coalesce(S.NoEconomicActiv,0), S.CODSIUI, CODCASA, CodPers, S.CAPITAL_SOCIAL,
    COALESCE(S.EFACT,0), COALESCE(S.TIPUNITJURIDICA,0)
  FROM NSUBUNIT S
    LEFT JOIN NBANKCONT NBK     ON S.CODBANKCONT     = NBK.CODBANKCONT
    LEFT JOIN NBANKCONT NBKTREZ ON S.CODBANKCONTTREZ = NBKTREZ.CODBANKCONT
  WHERE CODSUBUNIT = RECID;

  INSERT INTO  TMP_NAGENDA (
    OBS,CODAGENDA,TIP,CODLOCALIT,SEDIUSOCIAL,TELEFON,FAX,EMAIL,SECTOR,STRADA,NR1,NR2,BLOC,SCARA,ETAJ,APART,CODPOSTAL,KM,CODBANKCONT, CODPART,CODGEST,CODSUBUNIT, GLN,
    ADRESA, LONGITUDINE, LATITUDINE, OBS2 )
  SELECT
    OBS,CODAGENDA,TIP,CODLOCALIT,SEDIUSOCIAL,TELEFON,FAX,EMAIL,SECTOR,STRADA,NR1,NR2,BLOC,SCARA,ETAJ,APART,CODPOSTAL,KM,CODBANKCONT,CODPART,CODGEST,CODSUBUNIT, GLN,
    (SELECT GETADRESA.WME_RESULT FROM GETADRESA (NULL, SECTOR, STRADA, NR1, NR2, BLOC, SCARA, ETAJ, APART, CODPOSTAL)), LONGITUDINE, LATITUDINE, OBS2
  FROM NAGENDA WHERE CODSUBUNIT = RECID;

  INSERT INTO  TMP_NSUBUNIT1 ( CODSUBUNIT1,CODSUBUNIT,CODIOFILIAL, CODCATPRET, TVALAINCASARE, CAEN, IsFirma, Grdeclaratie, ModEditareJurnal, CodTVA, ANSTART,LUNASTART, PRELCANTBCAR )
  SELECT CODSUBUNIT1,CODSUBUNIT, CODIOFILIAL, CODCATPRET, NVL(TVALAINCASARE,0), CAEN, IsFirma, Grdeclaratie, Coalesce(ModEditareJurnal, 0), CodTVA, ANSTART,LUNASTART, COALESCE(PRELCANTBCAR,0)
  FROM NSUBUNIT1 WHERE CODSUBUNIT = RECID;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomsubunit_sp_insertrecord</obj_name>
  <obj_hashval>5e3e48bb17af80f73dc06aae6cdd2746</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomsubunit_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NSUBUNIT (CODSUBUNIT) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomsubunit_sp_lockrecord</obj_name>
  <obj_hashval>af598113854d1aad79b806eda241f5bc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomsubunit_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMP numeric;
begin
  SELECT CODSUBUNIT INTO TMP FROM NSUBUNIT WHERE CODSUBUNIT = RECID FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomtaxe_ct_monitor</obj_name>
  <obj_hashval>53e87b4b0b8c550bb8ee43d0bb246aad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomtaxe_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_NOMTAXE.CT_MONITOR', true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_7';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomtaxe_getcodcaractluna</obj_name>
  <obj_hashval>58328fca08326a37b21ed346bd05c2b2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomtaxe_getcodcaractluna(INOUT wme_result numeric, INOUT cod numeric, INOUT an numeric, INOUT luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODNTAXA1 numeric := 0;
begin
  --Florin 30.12.2021 - sinc. Oracle (29.12.2021)
  BEGIN
    SELECT CODTAXA1 INTO aCODNTAXA1 FROM NTAXE1 T1
      WHERE CODTAXA = COD AND An*12+Luna BETWEEN T1.alstart AND T1.alstop;
  EXCEPTION WHEN OTHERS THEN
    aCODNTAXA1 := 0;
  END;

  WME_Result :=  aCODNTAXA1;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomtaxe_getct_monitor</obj_name>
  <obj_hashval>15ce84759357b18bca539d1f2f1cb3a9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomtaxe_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_NOMTAXE.CT_MONITOR', true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_7';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomtaxe_setct_monitor</obj_name>
  <obj_hashval>08689171e35bb5f61df8b2c0e61114ce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomtaxe_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMTAXE.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomtaxe_sp_deleterecord</obj_name>
  <obj_hashval>ff63eae8e461e56faca5008617dd462f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomtaxe_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDoc varchar;
BEGIN
  --Florin 01.06.2023 - monitor
  --Bogdan 22.10.2020
  perform pkg_nomtaxe_setct_monitor('MON_7');
  IF (SELECT WME_RESULT
      FROM PKG_USERFIRME_ValidPostLog (NULL, current_setting ('PKG_GLOBALS.USERID', true)::numeric , (current_setting ('PKG_NOMTAXE.CT_MONITOR', true))))
  THEN
    SELECT 'taxa "' || N.Den_Taxa || '"' INTO aDoc FROM NTAXE n WHERE N.CODTAXA = RECID;

    PERFORM pkg_userfirme_postlogcucommit ('NTAXE', (current_setting ('PKG_GLOBALS.USERNAME', true)) , 'S', RECID,
                                                    (current_setting ('PKG_GLOBALS.FIRMANAME', true)) ,
                                                    TO_NUMBER ((current_setting ('PKG_GLOBALS.SUBUNITATE', true)) ,'999999999999999999') ,
                                                    null, aDoc, null,
                                                    (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION (NULL,NULL)));
  END IF;

  PERFORM PKG_NOMTAXE_SP_LOCKRECORD (RecId);
  DELETE FROM NTAXE1 WHERE CodTaxa = RecId;
  DELETE FROM NTAXE  WHERE CodTaxa = RecId;
  PERFORM NotifyModif (2, RECID, 'NTAXE');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomtaxe_sp_gotorecord</obj_name>
  <obj_hashval>28026864a2b5b913ca6318429616570d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomtaxe_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  aANSFARSIT   numeric;
  aLUNASFARSIT numeric;
BEGIN
  --Florin 30.01.2023 - sinc. Oracle
  --Bogdan 29.03.2021
  --Florin 16.11.2021 - fixat 52001
  perform pkg_nomtaxe_setct_monitor('MON_7');
  INSERT INTO TMP_NTAXE(CodTaxa, Den_Taxa, Centralizat, TipPart)
  (SELECT CodTaxa, Den_Taxa, Centralizat, coalesce(TipPart,0) FROM NTAXE WHERE CodTaxa = RecId);

  INSERT INTO TMP_NTAXE1(CodTaxa1, CodTaxa, Valoare, LaCeAplic, CodCont, CodContChelt, OricareTip, CodIOArtExcl, ExclusAccize, ExclusExport, JAchiz, JVanz, CumJAchiz, CumJVanz, BazaMax, BazaMin, CodServFact, Facturabil, STOPAJ, ROTVALOARE, anstart, lunastart, ProcDiminuareB, SERVICIUMONETAR, BazaMed)
  (SELECT CodTaxa1, CodTaxa, Valoare, LaCeAplic, CodCont, CodContChelt, OricareTip, CodIOArtExcl, ExclusAccize, ExclusExport, JAchiz, COALESCE( JVanz, 1), CumJAchiz, CumJVanz, BazaMax, BazaMin, CodServFact, Facturabil, STOPAJ, ROTVALOARE, anstart, lunastart, ProcDiminuareB, SERVICIUMONETAR, BazaMed
   FROM NTAXE1
   WHERE CodTaxa = RecId
  );

  aANSFARSIT   := 0;
  aLUNASFARSIT := 0;

  FOR V_REC IN (SELECT CodTaxa1, CodTaxa, Valoare, LaCeAplic, CodCont, CodContChelt, OricareTip, CodIOArtExcl, ExclusAccize, ExclusExport, JAchiz, JVanz, CumJAchiz, CumJVanz, BazaMax, BazaMin, CodServFact, Facturabil, STOPAJ, ROTVALOARE, anstart, lunastart, SERVICIUMONETAR
                FROM TMP_NTAXE1 ORDER BY ANSTART * 12 + LUNASTART desc
               )
  LOOP
    IF (aANSFARSIT &lt;&gt; 0)  AND (aLUNASFARSIT &lt;&gt; 0) THEN
      UPDATE TMP_NTAXE1
      SET
      ANSFARSIT   = aANSFARSIT,
      LUNASFARSIT = aLUNASFARSIT
      WHERE
       CODTAXA1 = V_REC.CODTAXA1;
    END IF;

     select newan, newluna
     from  PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA( V_REC.ANStart, V_REC.LUNAStart, aANSFARSIT, aLUNASFARSIT) into  aANSFARSIT, aLUNASFARSIT;
  END LOOP;

  UPDATE TMP_NTAXE1 SET LUNASFARSIT = 0 WHERE LUNASFARSIT IS NULL;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomtaxe_sp_insertrecord</obj_name>
  <obj_hashval>6907da0daf5f44c4a6a3966b9d205aa9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomtaxe_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NTAXE(CodTaxa) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomtaxe_sp_lockrecord</obj_name>
  <obj_hashval>391583511bfdb2d90097bc4333147f04</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomtaxe_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodTaxa INTO Tmp FROM NTAXE WHERE CodTaxa = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomtaxe_sp_postrecords</obj_name>
  <obj_hashval>959d1b80d22b9f468ff48e5df18aea22</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomtaxe_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  V_REC  RECORD;
  vRecNo numeric := 0;
  vAn    numeric := 0;
  vLuna  numeric := 0;
  vCod   numeric;
  aDoc   varchar;
BEGIN
  --Florin 01.06.2023 - monitor
  --Florin 30.01.2023 - sinc. Oracle
  --Adina 10.03.2021 - add prc_al_refresh
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_nomtaxe_setct_monitor('MON_7');
  if Operation = 0 then
    SELECT CodTaxa INTO RecId FROM TMP_NTAXE;

    if (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT
        FROM PKG_USERFIRME_ValidPostLog(null,
                                        to_number(current_setting('PKG_GLOBALS.USERID', true), '999999999999999999'),
                                        current_setting('PKG_NOMTAXE.CT_MONITOR', true)))
    then
      SELECT 'taxa "' || N.Den_Taxa || '"' INTO aDoc FROM tmp_NTAXE n WHERE N.CODTAXA = RECID;

      perform pkg_userfirme_postlogcucommit( 'NTAXE', current_setting('PKG_GLOBALS.USERNAME', true), 'M', RECID,
                                     current_setting('PKG_GLOBALS.FIRMANAME', true),
                                     to_number(current_setting('PKG_GLOBALS.SUBUNITATE', true), '999999999999999999'),
                                     null, aDoc, null,
                                     (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(null,null)));
    end if;

    UPDATE NTAXE
    SET
    (Den_Taxa, Centralizat, TipPart) = (SELECT Den_Taxa, Centralizat, TipPart FROM TMP_NTAXE )
    WHERE CodTaxa = RecId ;

    DELETE FROM NTAXE1
    WHERE (CODTAXA = RECID) and (CODTAXA1 not in (SELECT CODTAXA1 FROM TMP_NTAXE1 )) ;

    INSERT INTO NTAXE1 ( CodTaxa1,
      CodTaxa,
      Valoare,
      LaCeAplic,
      CodCont,
      CodContChelt,
      OricareTip,
      CodIOArtExcl,
      ExclusAccize,
      ExclusExport,
      JAchiz,
      JVanz,
      CumJAchiz,
      CumJVanz,
      BazaMax,
      BazaMin,
      CodServFact,
      Facturabil,
      STOPAJ,
      ROTVALOARE,
      anstart,
      lunastart,
      ProcDiminuareB,
      SERVICIUMONETAR,
      BazaMed)
    SELECT
      nextval('SEQ_NTAXE1_CODTAXA1'),
      RecId,
      Valoare,
      coalesce( LaCeAplic, 0),
      CodCont,
      CodContChelt,
      OricareTip,
      CodIOArtExcl,
      ExclusAccize,
      ExclusExport,
      JAchiz,
      JVanz,
      CumJAchiz,
      CumJVanz,
      BazaMax,
      BazaMin,
      CodServFact,
      Facturabil,
      STOPAJ,
      ROTVALOARE,
      anstart,
      lunastart,
      ProcDiminuareB,
      SERVICIUMONETAR,
      BazaMed
    FROM TMP_NTAXE1 WHERE CodTaxa1 &lt; 0;

    for v_rec in (SELECT * FROM TMP_NTAXE1 WHERE coalesce( CodTaxa1, -1) &gt; 0 order BY CodTaxa1 ) loop
      UPDATE NTAXE1
      SET
      ProcDiminuareB  = v_rec.ProcDiminuareB,
      Valoare         = v_rec.Valoare,
      LaCeAplic       = coalesce( v_rec.LaCeAplic, 0),
      CodCont         = v_rec.CodCont,
      CodContChelt    = v_rec.CodContChelt,
      OricareTip      = v_rec.OricareTip,
      CodIOArtExcl    = v_rec.CodIOArtExcl,
      ExclusAccize    = v_rec.ExclusAccize,
      ExclusExport    = v_rec.ExclusExport,
      JAchiz          = v_rec.JAchiz,
      JVanz           = v_rec.JVanz,
      CumJAchiz       = v_rec.CumJAchiz,
      CumJVanz        = v_rec.CumJVanz,
      BazaMax         = v_rec.BazaMax,
      BazaMin         = v_rec.BazaMin,
      CodServFact     = v_rec.CodServFact,
      Facturabil      = v_rec.Facturabil,
      STOPAJ          = V_REC.STOPAJ,
      ROTVALOARE      = V_REC.ROTVALOARE,
      ANSTART         = V_REC.ANSTART,
      LUNASTART       = V_REC.LUNASTART,
      SERVICIUMONETAR = V_REC.SERVICIUMONETAR,
      BazaMed         = V_REC.BazaMed
      where
        CodTaxa1 = v_rec.CodTaxa1 ;
    end loop;
  else
    SELECT nextval('SEQ_NTAXE_CODTAXA') INTO RecId;

    if (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(null, to_number(current_setting('PKG_GLOBALS.USERID', true), '999999999999999999'), current_setting('PKG_NOMTAXE.CT_MONITOR', true)))
    then
      SELECT 'taxa "' || N.Den_Taxa || '"' INTO aDoc FROM tmp_NTAXE n;

      perform pkg_userfirme_postlogcucommit( 'NTAXE', current_setting('PKG_GLOBALS.USERNAME', true), 'A', RECID,
                                     current_setting('PKG_GLOBALS.FIRMANAME', true),
                                     to_number(current_setting('PKG_GLOBALS.SUBUNITATE', true), '999999999999999999'),
                                     null, aDoc, null,
                                     (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(null,null)));
    end if;

    INSERT INTO NTAXE ( CodTaxa, Den_Taxa, Centralizat, TipPart )
    (SELECT RecId, Den_Taxa, Centralizat, TipPart FROM TMP_NTAXE );

    INSERT INTO NTAXE1 ( CodTaxa1,
      CodTaxa,
      Valoare,
      LaCeAplic,
      CodCont,
      CodContChelt,
      OricareTip,
      CodIOArtExcl,
      ExclusAccize,
      ExclusExport,
      JAchiz,
      JVanz,
      CumJAchiz,
      CumJVanz,
      BazaMax,
      BazaMin,
      CodServFact,
      Facturabil,
      STOPAJ,
      ROTVALOARE,
      anstart,
      lunastart,
      ProcDiminuareB,
      SERVICIUMONETAR,
      BazaMed) (
    SELECT
        nextval('SEQ_NTAXE1_CODTAXA1'),
        RecId,
        Valoare,
        coalesce( LaCeAplic, 0),
        CodCont,
        CodContChelt,
        OricareTip,
        CodIOArtExcl,
        ExclusAccize,
        ExclusExport,
        JAchiz,
        JVanz,
        CumJAchiz,
        CumJVanz,
        BazaMax,
        BazaMin,
        CodServFact,
        Facturabil,
        STOPAJ,
        ROTVALOARE,
        anstart,
        lunastart,
        ProcDiminuareB,
        SERVICIUMONETAR,
        BazaMed
    FROM TMP_NTAXE1 );
  end if;

  UPDATE LUNA_RECORDS_FLAGS SET NTAXE_FLG = 0 ;

  CALL PRC_AL_REFRESH('ntaxe1', RecId);

  perform NotifyModif( OPERATION, RECID, 'NTAXE');

end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomtva_ct_monitor</obj_name>
  <obj_hashval>41ad55f546eae8a46915e08360da0e90</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomtva_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_NOMTVA.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_7';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomtva_getcodcaractluna</obj_name>
  <obj_hashval>b9ad5d2e49ecc3ae494aa8cfd2cd8cae</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomtva_getcodcaractluna(INOUT wme_result numeric, INOUT cod numeric, INOUT an numeric, INOUT luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODTVA1 numeric := 0;
begin
  --Florin 30.12.2021 - sinc. Oracle (29.12.2021)
  BEGIN
    SELECT CODTVA1 INTO aCODTVA1 FROM NTVA1 T1
      WHERE T1.CODTVA = COD AND An*12+Luna BETWEEN t1.alstart AND t1.alstop;
  EXCEPTION WHEN OTHERS THEN
    aCODTVA1 := 0;
  END;

  WME_Result :=  aCODTVA1;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomtva_getct_monitor</obj_name>
  <obj_hashval>b8015630b449b719f882fae16db48ff1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomtva_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_NOMTVA.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_7';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomtva_getcursortvauriluna</obj_name>
  <obj_hashval>11484b1e6ad331042281bcc48a3b326e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomtva_getcursortvauriluna(INOUT wme_result refcursor, INOUT an numeric, INOUT luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMPCURSOR REFCURSOR;
begin
  --Florin 30.12.2021 - sinc. Oracle (29.12.2021)
  BEGIN
    OPEN TMPCURSOR FOR SELECT N.DEN_TVA, N1.*
      FROM NTVA N LEFT JOIN NTVA1 N1 ON N1.CODTVA = N.CODTVA
      WHERE Coalesce(N.CODTVA, 0) &lt;&gt; 0 AND An*12+Luna BETWEEN n1.alstart AND n1.alstop;
  EXCEPTION WHEN OTHERS THEN
    OPEN TMPCURSOR FOR SELECT '-1';
  END;

  WME_Result :=  TMPCURSOR;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomtva_getproctvaluna</obj_name>
  <obj_hashval>812e51e58c29942c463df5102d29512c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomtva_getproctvaluna(INOUT wme_result numeric, INOUT cod numeric, INOUT an numeric, INOUT luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  PROC double precision := -1;
begin
  --Florin 30.12.2021 - sinc. Oracle (29.12.2021)
  BEGIN
    SELECT PROCENT INTO PROC FROM NTVA1 T1
      WHERE T1.CODTVA = COD AND An*12+Luna BETWEEN t1.alstart AND t1.alstop;
  EXCEPTION WHEN OTHERS THEN
    PROC := -1;
  END;

  WME_Result :=  PROC;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomtva_setct_monitor</obj_name>
  <obj_hashval>f71bcb959c2b0419ed2c37537e008242</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomtva_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMTVA.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomtva_sp_deleterecord</obj_name>
  <obj_hashval>c2b8d356aaaeaa8475f7623efc588f3f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomtva_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDoc varchar;
BEGIN
  --Florin 01.06.2023 - monitor
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_nomtva_setct_monitor('MON_7');
  PERFORM PKG_NOMTVA_SP_LOCKRECORD( RecId);

  IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_NOMTVA.CT_MONITOR', true))))
  THEN
    SELECT 'tva "' || n.den_tva || '"' INTO aDoc FROM NTVA n WHERE N.CODTVA = RECID;
    PERFORM pkg_userfirme_postlogcucommit( 'NTVA', (current_setting('PKG_GLOBALS.USERNAME', true)), 'S', RECID, (current_setting('PKG_GLOBALS.FIRMANAME', true)), TO_NUMBER((current_setting('PKG_GLOBALS.SUBUNITATE', true)),'999999999999999999'), null, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  DELETE FROM NTVA1 WHERE CodTva = RecId;
  DELETE FROM NTVA  WHERE CodTva = RecId;

  PERFORM NotifyModif( 2, RECID, 'NTVA');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomtva_sp_gotorecord</obj_name>
  <obj_hashval>9710208230f2ef0303b3ab391e2a6458</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomtva_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  aANSFARSIT   numeric;
  aLUNASFARSIT numeric;
begin
  --Bogdan 29.03.2021
  --Florin 16.11.2021 - fixat 52001
  perform pkg_nomtva_setct_monitor('MON_7');
  INSERT INTO TMP_NTVA(CodTva, Den_Tva)
  (SELECT CodTva, Den_Tva FROM NTVA WHERE CodTva = RecId);

  INSERT INTO TMP_NTVA1(CodTva1, CodTva, Procent, CodContDed, CodContCole, CodContNeex, anstart, lunastart)
  (SELECT CodTva1, CodTva, Procent, CodContDed, CodContCole, CodContNeex, anstart, lunastart
   FROM NTVA1 WHERE CodTva = RecId
  );

  aANSFARSIT   := 0;
  aLUNASFARSIT := 0;

  FOR V_REC IN (SELECT CODTVA1, ANSTART, LUNASTART FROM TMP_NTVA1 ORDER BY ANSTART * 12 + LUNASTART desc) LOOP
    IF (aANSFARSIT &lt;&gt; 0)  AND (aLUNASFARSIT &lt;&gt; 0) THEN
      UPDATE TMP_NTVA1
      SET
        ANSFARSIT   = aANSFARSIT,
        LUNASFARSIT = aLUNASFARSIT
      WHERE CODTVA1 = V_REC.CODTVA1;
    END IF;

     select newan, newluna
     from  PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA( V_REC.ANStart, V_REC.LUNAStart, aANSFARSIT, aLUNASFARSIT) into  aANSFARSIT, aLUNASFARSIT;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomtva_sp_insertrecord</obj_name>
  <obj_hashval>fc93447b214ec8f31e95eee7f6498dd6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomtva_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NTVA(CodTva) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomtva_sp_postrecords</obj_name>
  <obj_hashval>ddaa15e2118b7481cbb1a5465a05493a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomtva_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  vRecNo NUMERIC := 0;
  vAn    NUMERIC := 0;
  vLuna  NUMERIC := 0;
  vCod   numeric;
  aDoc   varchar;
BEGIN
  --Florin 01.06.2023 - monitor
  --Adina 10.03.2021 - add prc_al_refresh
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_nomtva_setct_monitor('MON_7');
  IF  Operation = 0 THEN
    SELECT CodTva INTO RecId FROM TMP_NTVA;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_NOMTVA.CT_MONITOR', true))))
    THEN
      SELECT 'tva "' || n.den_tva || '"' INTO aDoc FROM TMP_NTVA n WHERE N.CODTVA = RECID;
      PERFORM pkg_userfirme_postlogcucommit( 'NTVA', (current_setting('PKG_GLOBALS.USERNAME', true)), 'M', RECID, (current_setting('PKG_GLOBALS.FIRMANAME', true)), TO_NUMBER((current_setting('PKG_GLOBALS.SUBUNITATE', true)),'999999999999999999'), null, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    UPDATE NTVA SET (Den_Tva)  = (SELECT Den_Tva FROM TMP_NTVA) WHERE CodTva = RecId;

    DELETE FROM NTVA1 WHERE CodTVA = RecId and CodTVA1 NOT IN (SELECT CodTVA1 FROM TMP_NTVA1);

    INSERT INTO NTVA1(CodTva1, CodTva, Procent, CodContDed, CodContCole, CodContNeex, anstart, lunastart)
    SELECT NEXTVAL('SEQ_NTVA1_CODTVA1'), RecId, Procent, CodContDed, CodContCole, CodContNeex, anstart, lunastart
    FROM TMP_NTVA1 WHERE CodTva1 &lt; 0;

    FOR v_rec IN (SELECT * FROM TMP_NTVA1 WHERE COALESCE( CodTva1, -1) &gt; 0 ORDER BY CodTva1) LOOP
      SELECT CASE WHEN  Procent=v_rec.Procent         THEN 0 ELSE  1 END  +
             CASE WHEN  CodContDed=v_rec.CodContDed   THEN 0 ELSE  1 END  +
             CASE WHEN  CodContCole=v_rec.CodContCole THEN 0 ELSE  1 END  +
             CASE WHEN  CodContNeex=v_rec.CodContNeex THEN 0 ELSE  1 END ,
             anstart, lunastart
      INTO vRecNo, vAn, vLuna
      FROM NTVA1 WHERE CodTva1 = COALESCE( v_rec.CodTva1, 0);

      IF (vRecNo &gt; 0) THEN
        IF (v_rec.anstart = vAn)  and (v_rec.lunastart = vLuna) THEN
          UPDATE NTVA1
          SET
          Procent     = v_rec.Procent,
          CodContDed  = v_rec.CodContDed,
          CodContCole = v_rec.CodContCole,
          CodContNeex = v_rec.CodContNeex
          WHERE
           CodTva1 = v_rec.CodTva1;
        ELSE
          INSERT INTO NTVA1(CodTva1, CodTva, Procent, CodContDed, CodContCole, CodContNeex, anstart, lunastart)
          VALUES(NEXTVAL('SEQ_NTVA1_CODTVA1'), RecId, v_rec.Procent, v_rec.CodContDed, v_rec.CodContCole, v_rec.CodContNeex, v_rec.anstart, v_rec.lunastart);
        END IF;
      END IF;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_NTVA_CODTVA') INTO RecId;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_NOMTVA.CT_MONITOR', true))))
    THEN
      SELECT 'tva "' || n.den_tva || '"' INTO aDoc FROM TMP_NTVA n;
      PERFORM pkg_userfirme_postlogcucommit( 'NTVA', (current_setting('PKG_GLOBALS.USERNAME', true)), 'A', RECID, (current_setting('PKG_GLOBALS.FIRMANAME', true)), TO_NUMBER((current_setting('PKG_GLOBALS.SUBUNITATE', true)),'999999999999999999'), null, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    INSERT INTO NTVA(CodTva, Den_Tva) (SELECT RecId, Den_Tva FROM TMP_NTVA);

    INSERT INTO NTVA1(CodTva1, CodTva, Procent, CodContDed, CodContCole, CodContNeex, anstart, lunastart)
    (SELECT NEXTVAL('SEQ_NTVA1_CODTVA1'), RecId, Procent, CodContDed, CodContCole, CodContNeex, anstart, lunastart FROM TMP_NTVA1);
  END IF;

  UPDATE LUNA_RECORDS_FLAGS SET NTVA_FLG = 0;

  CALL PRC_AL_REFRESH('ntva1', RecId);

  PERFORM NotifyModif( OPERATION, RECID, 'NTVA');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_bagainx</obj_name>
  <obj_hashval>16f6a6115d0d4360025bb1987a9f311e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_bagainx(text character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  INSERT INTO x (test) VALUES(text);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_carnetdoc_i</obj_name>
  <obj_hashval>069173bc0e1491f316f7d6745041f08c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_carnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.CARNETDOC_I', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_check_nc_fact</obj_name>
  <obj_hashval>1b2d2eddfca3519dcb28e27e63dc3742</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_check_nc_fact(acoddoc numeric, acoddoc1 numeric, atipdoc numeric, acodnc numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCodDoc NUMERIC(20);
  aCount  NUMERIC(20);
BEGIN
  --Florin 17.12.2024 - fixat 64310
  --Florin 10.12.2024 - sinc. Oracle
  if aCodDoc1 &gt; 0 then
    if aTipDoc = 1 then
      begin
        select codintr into vCodDoc from intrari1 where codintr1 = aCodDoc1;
      exception when others then vCodDoc := -1;
      end;
      if vCodDoc &lt;= 0 then
        -- document neindentificat dar totusi caut pe linii
        select count(*) into aCount from notecreditfact where codncredit &lt;&gt; aCodNC and coddoc1 = acoddoc1 and tipdoc = atipdoc;
        if aCount &gt;= 1 then
          return aCount;
        end if;
      else
        select count(*) into aCount from notecreditfact where codncredit &lt;&gt; aCodNC and coddoc = vCodDoc and tipdoc = atipdoc;
        if aCount &gt; 0 then
          return aCount;
        end if;
        select count(*) into aCount
        from notecreditfact ncf
             inner join intrari1 i1 on i1.codintr1 = ncf.coddoc1
        where ncf.tipdoc = aTipDoc and i1.codintr = vCodDoc and ncf.codncredit &lt;&gt; aCodNC;
        if aCount &gt; 0 then
          return aCount;
        end if;
      end if;
    else
      begin
        select codies into vCodDoc from iesiri1 where codies1 = aCodDoc1;
      exception when others then vCodDoc := -1;
      end;
      if vCodDoc &lt;= 0 then
        -- document neindentificat dar totusi caut pe linii
        select count(*) into aCount from notecreditfact where codncredit &lt;&gt; aCodNC and coddoc1 = acoddoc1 and tipdoc = atipdoc;
        if aCount &gt;= 1 then
          return aCount;
        end if;
      else
        select count(*) into aCount from notecreditfact where codncredit &lt;&gt; aCodNC and coddoc = vCodDoc and tipdoc = atipdoc;
        if aCount &gt; 0 then
          return aCount;
        end if;
        select count(*) into aCount
        from notecreditfact ncf
             inner join iesiri1 i1 on i1.codies1 = ncf.coddoc1
        where ncf.tipdoc = aTipDoc and i1.codies = vCodDoc and ncf.codncredit &lt;&gt; aCodNC;
        if aCount &gt; 0 then
          return aCount;
        end if;
      end if;
    end if;
  else
    if aTipDoc = 1 then
      vCodDoc := aCodDoc;
      if vCodDoc &lt;= 0 then
        -- document neindentificat dar totusi caut pe linii
        select count(*) into aCount from notecreditfact where codncredit &lt;&gt; aCodNC and coddoc1 = acoddoc1 and tipdoc = atipdoc;
        if aCount &gt;= 1 then
          return aCount;
        end if;
      else
        select count(*) into aCount from notecreditfact where codncredit &lt;&gt; aCodNC and coddoc = vCodDoc and tipdoc = atipdoc;
        if aCount &gt; 0 then
          return aCount;
        end if;
        select count(*) into aCount
        from notecreditfact ncf
             inner join intrari1 i1 on i1.codintr1 = ncf.coddoc1
        where ncf.tipdoc = aTipDoc and i1.codintr = vCodDoc;
        if aCount &gt; 0 then
          return aCount;
        end if;
      end if;
    else
      vCodDoc := aCodDoc;
      if vCodDoc &lt;= 0 then
        -- document neindentificat dar totusi caut pe linii
        select count(*) into aCount from notecreditfact where codncredit &lt;&gt; aCodNC and coddoc1 = acoddoc1 and tipdoc = atipdoc;
        if aCount &gt;= 1 then
          return aCount;
        end if;
      else
        select count(*) into aCount from notecreditfact where codncredit &lt;&gt; aCodNC and coddoc = vCodDoc and tipdoc = atipdoc;
        if aCount &gt; 0 then
          return aCount;
        end if;
        select count(*) into aCount
        from notecreditfact ncf
             inner join iesiri1 i1 on i1.codies1 = ncf.coddoc1
        where ncf.tipdoc = aTipDoc and i1.codies = vCodDoc;
        if aCount &gt; 0 then
          return aCount;
        end if;
      end if;
    end if;
  end if;
  return 0;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_ct_monitor</obj_name>
  <obj_hashval>f29d428799a9a90730ef8e225f7b9568</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.CT_MONITOR', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_47';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_empty_note_temptables</obj_name>
  <obj_hashval>1b966da440b07e373accb8a9f07e1e4d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_empty_note_temptables()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM tmp_notecredit;
  DELETE FROM tmp_notecredit1;
  DELETE FROM tmp_notecreditt;
  DELETE FROM tmp_notecreditc;
  DELETE FROM tmp_notecreditv;
  DELETE FROM tmp_notecreditp;
  DELETE FROM tmp_notecreditct;
  DELETE FROM tmp_notecreditz;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_genereazavolum</obj_name>
  <obj_hashval>e96952f4ae3319407b1c1342f2899179</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_genereazavolum(INOUT acodncredit numeric, INOUT acodcontract numeric, INOUT atiparticol numeric, INOUT adatastart character varying, INOUT adatastop character varying, INOUT acodmoneda numeric, INOUT acodpart numeric, INOUT asubunitatea numeric, INOUT atrimestru numeric, INOUT apretbrutv numeric, INOUT atipdoc numeric, INOUT atipdiscv numeric, INOUT atotal numeric, INOUT atotallei numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
null;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getcarnetdoc_i</obj_name>
  <obj_hashval>336819dbb9c142fa125d72ffadefcde0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getcarnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.CARNETDOC_I', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getcodcontract1</obj_name>
  <obj_hashval>27435915a1f0e12ad17aabfecc364077</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getcodcontract1(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT adatadoc timestamp without time zone, INOUT acodcontract numeric, INOUT acoddoc1 numeric DEFAULT 0)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
  declare
    vrec record;
  BEGIN
    --Adina 04.05.2021 - sinc.Oracle din 30.04.2021
    vrec = pkg_notecredit_getcodcontract1(null,acodobiect,adatadoc::date,acodcontract,COALESCE(acoddoc1,0));
    WME_Result := vrec.wme_result;
    RETURN;
  end;
  $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getcodcontract1</obj_name>
  <obj_hashval>f9e18b1e2dd9094f00ea69dfadaf0a07</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getcodcontract1(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT adatadoc date, INOUT acodcontract numeric, INOUT acoddoc1 numeric DEFAULT 0)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCodContract1 numeric;
  vTipArticol   numeric;
  vConst        numeric;
  aTipDoc       numeric;
BEGIN
  --Adina 04.05.2021 - sinc.Oracle din 30.04.2021
  --Adina 24.04.2021 - sinc.Oracle din 23.04.2021
  --Adina 16.04.2021 - sinc.Oracle din 16.04.2021
  acoddoc1 := coalesce(acoddoc1,0);
  vConst   := coalesce((fnc_GetValConstanta('NCCContract', GetANLUCRU(), GetLUNALUCRU()))::numeric,2);

  IF  aCodDoc1 = 0 or vConst &lt;&gt; 1 THEN
    BEGIN
      SELECT COALESCE(TipArticol, 0) INTO vTipArticol FROM contract WHERE codcontract = aCodContract;
    EXCEPTION WHEN others THEN
      vTipArticol := 0;
    END;

    IF  vTipArticol = 0 THEN
      BEGIN
        SELECT COALESCE(c1.CodContract1, 0)
        INTO vCodContract1
        FROM contract1 c1
            INNER JOIN contract c ON  c1.codcontract = c.codcontract
        WHERE
           C1.codobiect = aCodObiect and  C1.CodContract = aCodContract
           and  COALESCE(C1.DataStart, C.DataStart) &lt;= aDataDoc AND  COALESCE(C1.DataStop, C.DataStop) &gt;= aDataDoc;
      EXCEPTION WHEN others THEN
        vCodContract1 := 0;
      END;
    ELSE
      BEGIN
        SELECT COALESCE(c1.CodContract1, 0)
        INTO vCodContract1
        FROM contract1 c1
            INNER JOIN nart     a   ON  a.clasa = c1.codclasa
            INNER JOIN nartobj  obj ON  obj.codarticol = a.codarticol
            INNER JOIN contract c   ON  c1.codcontract = c.codcontract
        WHERE
           obj.codobiect = aCodObiect and  C1.CodContract = aCodContract
           and  COALESCE(C1.DataStart, C.DataStart) &lt;= aDataDoc AND  COALESCE(C1.DataStop, C.DataStop) &gt;= aDataDoc;
      EXCEPTION WHEN others THEN
        vCodContract1 := 0;
      END;
    END IF;
  ELSE --16.04.2021 ; 04.05.2021
    begin
      select coalesce(TipArticol,0), tipdoc into vTipArticol, aTipDoc
      from contract
      where codcontract = aCodContract;
    exception when others then vTipArticol := 0;
    end;

    IF aTipDoc = 27 THEN
      if vTipArticol = 0 then
        begin
          select coalesce(c1.CodContract1,0) into vCodContract1
          from contract1 c1
               inner join contract c on c1.codcontract  = c.codcontract
               inner join iesiri1 i1 on c1.codcontract1 = i1.codcontract1
          where C1.codobiect = aCodObiect and C1.CodContract = aCodContract
                and i1.codies1 = aCodDoc1;
        exception when others then
          vCodContract1 := 0;
        end;
        if vCodContract1 = 0 then
          begin
            select coalesce(c1.CodContract1,0) into vCodContract1
            from contract1 c1
                 inner join contract c  on c1.codcontract = c.codcontract
                 inner join iesiri   i  on i.codcontract  = c.codcontract
                 inner join iesiri1  i1 on i1.codies = i.codies and i1.codobiect = c1.codobiect
            where i1.codobiect = aCodObiect and C1.CodContract = aCodContract
                  and i1.codies1 = aCodDoc1;
          exception when others then
            vCodContract1 := 0;
          end;
        end if;
      else
        begin
          select coalesce(c1.CodContract1,0) into vCodContract1
          from contract1 c1
               inner join nart     a   on a.clasa         = c1.codclasa
               inner join nartobj  obj on obj.codarticol  = a.codarticol
               inner join contract c   on c1.codcontract  = c.codcontract
               inner join iesiri1  i1  on c1.codcontract1 = i1.codcontract1
          where obj.codobiect = aCodObiect and C1.CodContract = aCodContract
                and coalesce(C1.DataStart,C.DataStart) &lt;= aDataDoc AND coalesce(C1.DataStop,C.DataStop)  &gt;= aDataDoc
                and i1.codies1 = aCodDoc1;
        exception when others then
          vCodContract1 := 0;
        end;
        if vCodContract1 = 0 then
          begin
            select coalesce(c1.CodContract1,0) into vCodContract1
            from contract1 c1
                 inner join nart     a   on a.clasa        = c1.codclasa
                 inner join nartobj  obj on obj.codarticol = a.codarticol
                 inner join contract c   on c1.codcontract = c.codcontract
                 inner join iesiri   i   on i.codcontract  = c.codcontract
                 inner join iesiri1  i1  on i1.codies      = i.codies and i1.codobiect = c1.codobiect
            where i1.codobiect = aCodObiect and C1.CodContract = aCodContract
                  and coalesce(C1.DataStart,C.DataStart) &lt;= aDataDoc AND coalesce(C1.DataStop,C.DataStop)  &gt;= aDataDoc
                  and i1.codies1 = aCodDoc1;
          exception when others then
            vCodContract1 := 0;
          end;
        end if;
      end if;
    ELSE  --04.05.2021
      if vTipArticol = 0 then
        begin
          select coalesce(c1.CodContract1,0) into vCodContract1
          from contract1 c1
               inner join contract c  on c1.codcontract  = c.codcontract
               inner join intrari1 i1 on c1.codcontract1 = i1.codcontract1
          where C1.codobiect = aCodObiect and C1.CodContract = aCodContract
                and i1.codintr1 = aCodDoc1;
        exception when others then
          vCodContract1 := 0;
        end;
        if vCodContract1 = 0 then
          begin
            select coalesce(c1.CodContract1,0) into vCodContract1
            from contract1 c1
                 inner join contract c  on c1.codcontract = c.codcontract
                 inner join intrari  i  on i.codcontract  = c.codcontract
                 inner join intrari1 i1 on i1.codintr     = i.codintr and i1.codobiect = c1.codobiect
            where i1.codobiect = aCodObiect and C1.CodContract = aCodContract
                  and i1.codintr1 = aCodDoc1;
          exception when others then
            vCodContract1 := 0;
          end;
        end if;
      else
        begin
          select coalesce(c1.CodContract1,0) into vCodContract1
          from contract1 c1
               inner join nart     a   on a.clasa         = c1.codclasa
               inner join nartobj  obj on obj.codarticol  = a.codarticol
               inner join contract c   on c1.codcontract  = c.codcontract
               inner join intrari1 i1  on c1.codcontract1 = i1.codcontract1
          where obj.codobiect = aCodObiect and C1.CodContract = aCodContract
                and coalesce(C1.DataStart,C.DataStart) &lt;= aDataDoc AND coalesce(C1.DataStop,C.DataStop)  &gt;= aDataDoc
                and i1.codintr1 = aCodDoc1;
        exception when others then
          vCodContract1 := 0;
        end;
        if vCodContract1 = 0 then
          begin
            select coalesce(c1.CodContract1,0) into vCodContract1
            from contract1 c1
                 inner join nart     a   on a.clasa        = c1.codclasa
                 inner join nartobj  obj on obj.codarticol = a.codarticol
                 inner join contract c   on c1.codcontract = c.codcontract
                 inner join intrari  i   on i.codcontract  = c.codcontract
                 inner join intrari1 i1  on i1.codintr     = i.codintr and i1.codobiect = c1.codobiect
            where i1.codobiect = aCodObiect and C1.CodContract = aCodContract
                  and coalesce(C1.DataStart,C.DataStart) &lt;= aDataDoc AND coalesce(C1.DataStop,C.DataStop)  &gt;= aDataDoc
                  and i1.codintr1 = aCodDoc1;
          exception when others then
            vCodContract1 := 0;
          end;
        end if;
      end if;
    END IF;
  END IF;

  WME_Result :=  vCodContract1;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getcodcontract1_20210504</obj_name>
  <obj_hashval>3d844a6bc728a57e7c536ffaf6efcfaf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getcodcontract1_20210504(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT adatadoc date, INOUT acodcontract numeric, INOUT acodies1 numeric DEFAULT 0)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCodContract1 numeric;
  vTipArticol   numeric;
  vConst        numeric;
BEGIN
  --Adina 24.04.2021 - sinc.Oracle din 23.04.2021
  --Adina 16.04.2021 - sinc.Oracle din 16.04.2021
  acodies1 := coalesce(acodies1,0);
  vConst   := coalesce((fnc_GetValConstanta('NCCContract', GetANLUCRU(), GetLUNALUCRU()))::numeric,2);

  IF  aCodIes1 = 0 or vConst &lt;&gt; 1 THEN
    BEGIN
      SELECT COALESCE(TipArticol, 0) INTO vTipArticol FROM contract WHERE codcontract = aCodContract;
    EXCEPTION WHEN others THEN
      vTipArticol := 0;
    END;

    IF  vTipArticol = 0 THEN
      BEGIN
        SELECT COALESCE(c1.CodContract1, 0)
        INTO vCodContract1
        FROM contract1 c1
            INNER JOIN contract c ON  c1.codcontract = c.codcontract
        WHERE
           C1.codobiect = aCodObiect and  C1.CodContract = aCodContract and  COALESCE(C1.DataStart, C.DataStart) &lt;= aDataDoc AND  COALESCE(C1.DataStop, C.DataStop) &gt;= aDataDoc;
      EXCEPTION WHEN others THEN
        vCodContract1 := 0;
      END;
    ELSE
      BEGIN
        SELECT COALESCE(c1.CodContract1, 0)
        INTO vCodContract1
        FROM contract1 c1
            INNER JOIN nart     a   ON  a.clasa = c1.codclasa
            INNER JOIN nartobj  obj ON  obj.codarticol = a.codarticol
            INNER JOIN contract c   ON  c1.codcontract = c.codcontract
        WHERE
           obj.codobiect = aCodObiect and  C1.CodContract = aCodContract and  COALESCE(C1.DataStart, C.DataStart) &lt;= aDataDoc AND  COALESCE(C1.DataStop, C.DataStop) &gt;= aDataDoc;
      EXCEPTION WHEN others THEN
        vCodContract1 := 0;
      END;
    END IF;
  ELSE --16.04.2021
    begin
      select coalesce(TipArticol,0) into vTipArticol
      from contract
      where codcontract = aCodContract;
    exception when others then vTipArticol := 0;
    end;

    if vTipArticol = 0 then
      begin
        select coalesce(c1.CodContract1,0) into vCodContract1
        from contract1 c1
             inner join contract c on c1.codcontract  = c.codcontract
             inner join iesiri1 i1 on c1.codcontract1 = i1.codcontract1
        where C1.codobiect = aCodObiect and C1.CodContract = aCodContract
              and i1.codies1 = aCodIes1;
      exception when others then
        vCodContract1 := 0;
      end;
      if vCodContract1 = 0 then
        begin
          select coalesce(c1.CodContract1,0) into vCodContract1
          from contract1 c1
               inner join contract c  on c1.codcontract = c.codcontract
               inner join iesiri   i  on i.codcontract  = c.codcontract
               inner join iesiri1  i1 on i1.codies = i.codies and i1.codobiect = c1.codobiect
          where i1.codobiect = aCodObiect and C1.CodContract = aCodContract
                and i1.codies1 = aCodIes1;
        exception when others then
          vCodContract1 := 0;
        end;
      end if;
    else
      begin
        select coalesce(c1.CodContract1,0) into vCodContract1
        from contract1 c1
             inner join nart     a   on a.clasa         = c1.codclasa
             inner join nartobj  obj on obj.codarticol  = a.codarticol
             inner join contract c   on c1.codcontract  = c.codcontract
             inner join iesiri1  i1  on c1.codcontract1 = i1.codcontract1
        where obj.codobiect = aCodObiect and C1.CodContract = aCodContract
              and coalesce(C1.DataStart,C.DataStart) &lt;= aDataDoc AND coalesce(C1.DataStop,C.DataStop)  &gt;= aDataDoc
              and i1.codies1 = aCodIes1;
      exception when others then
        vCodContract1 := 0;
      end;
      if vCodContract1 = 0 then
        begin
          select coalesce(c1.CodContract1,0) into vCodContract1
          from contract1 c1
               inner join nart     a   on a.clasa        = c1.codclasa
               inner join nartobj  obj on obj.codarticol = a.codarticol
               inner join contract c   on c1.codcontract = c.codcontract
               inner join iesiri   i   on i.codcontract  = c.codcontract
               inner join iesiri1  i1  on i1.codies      = i.codies and i1.codobiect = c1.codobiect
          where i1.codobiect = aCodObiect and C1.CodContract = aCodContract
                and coalesce(C1.DataStart,C.DataStart) &lt;= aDataDoc AND coalesce(C1.DataStop,C.DataStop)  &gt;= aDataDoc
                and i1.codies1 = aCodIes1;
        exception when others then
          vCodContract1 := 0;
        end;
      end if;
    end if;
  END IF;

  WME_Result :=  vCodContract1;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getcodcontract1_vechi</obj_name>
  <obj_hashval>3ad912995598936bab94f0dfa3e11a80</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getcodcontract1_vechi(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT adatadoc timestamp without time zone, INOUT acodcontract numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
  declare
    vrec record;
  begin
    vrec = pkg_notecredit_getcodcontract1(null,acodobiect,adatadoc::date,acodcontract);
    WME_Result := vrec.wme_result;
    RETURN;
  end;
  $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getcodcontract1_vechi</obj_name>
  <obj_hashval>b2431be3d08d0606d49d4a2d4a167a6c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getcodcontract1_vechi(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT adatadoc date, INOUT acodcontract numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCodContract1 numeric;
  vTipArticol   numeric;
begin
  BEGIN
    SELECT COALESCE(TipArticol, 0) INTO vTipArticol FROM contract WHERE codcontract = aCodContract;
  EXCEPTION WHEN others THEN
    vTipArticol := 0;
  END;

  IF  vTipArticol = 0 THEN
    BEGIN
      SELECT COALESCE(c1.CodContract1, 0)
      INTO vCodContract1
      FROM contract1 c1
          INNER JOIN contract c ON  c1.codcontract = c.codcontract
      WHERE
         C1.codobiect = aCodObiect and  C1.CodContract = aCodContract and  COALESCE(C1.DataStart, C.DataStart) &lt;= aDataDoc AND  COALESCE(C1.DataStop, C.DataStop) &gt;= aDataDoc;
    EXCEPTION WHEN others THEN
      vCodContract1 := 0;
    END;
  ELSE
    BEGIN
      SELECT COALESCE(c1.CodContract1, 0)
      INTO vCodContract1
      FROM contract1 c1
          INNER JOIN nart a ON  a.clasa = c1.codclasa
          INNER JOIN nartobj obj ON  obj.codarticol = a.codarticol
          INNER JOIN contract c ON  c1.codcontract = c.codcontract
      WHERE
         obj.codobiect = aCodObiect and  C1.CodContract = aCodContract and  COALESCE(C1.DataStart, C.DataStart) &lt;= aDataDoc AND  COALESCE(C1.DataStop, C.DataStop) &gt;= aDataDoc;
    EXCEPTION WHEN others THEN
      vCodContract1 := 0;
    END;
  END IF;

  WME_Result :=  vCodContract1;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getct_monitor</obj_name>
  <obj_hashval>e218c4ad99c8bd8664b994d84e07d1c6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.CT_MONITOR', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_47';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getdisccant</obj_name>
  <obj_hashval>cbc08fd2d1eb61303ab6a03ba75a6bd7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getdisccant(INOUT wme_result numeric, INOUT vcant numeric, INOUT vvaldoc numeric, INOUT vtotal numeric, INOUT vcodcontract1 numeric, INOUT vpretmediu numeric, INOUT vglobal numeric DEFAULT 0, INOUT vcurs numeric DEFAULT 1)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  VREC RECORD;
  vProc         numeric;
  vVal          numeric;
  vRez          numeric(20,7);
  vValT         numeric(20,7);
  vTipDiscount  numeric;
  vTipDiscountC numeric;
  vPret         numeric;
  vParitate     numeric;
  vRest         numeric;
  vLastP        numeric;
  vCount        numeric(20);
  vCodContract  numeric(20);
BEGIN
  --Florin 20.04.2023 - sinc. Oracle (12.04.2023)
  --Florin 01.03.2023 - sinc. Oracle (17.02.2023)
  select coalesce(c1.TipDiscount, 0), coalesce(c1.TipDiscountC, 0), c1.pret, CASE WHEN coalesce(num1.paritate,1) = 0 THEN 1 ELSE coalesce(num1.paritate,1) END,c1.codcontract
  into vTipDiscount, vTipDiscountC, vPret, vParitate, vCodContract
  FROM contract1          c1
    INNER JOIN contract c ON c.codcontract = c1.codcontract
    INNER JOIN num1       ON num1.codum1 = c1.umsec
  WHERE c1.codcontract1 = vCodContract1;

  IF vTipDiscountC = 0 THEN
    BEGIN
      SELECT COALESCE (cc.Discount, 0) INTO vProc
      FROM contractc         cc
        INNER JOIN contract1 c1 ON c1.codcontract1 = cc.codcontract1
        INNER JOIN num1         ON c1.umsec = num1.codum1
      WHERE
        c1.codcontract1 = vCodContract1
        and cc.cantmin * num1.paritate = (SELECT max (cantmin * num1.paritate) FROM contractc WHERE codcontract1 = c1.codcontract1 and cantmin * num1.paritate &lt;= vTotal);
    EXCEPTION
    WHEN others THEN
      vProc := 0;
    END;

    IF vTipDiscount = 0 THEN
      vRez := coalesce(vProc * vValDoc / 100,0);
      RETURN;
    ELSE
      vRez := coalesce(vProc / 100 * vCant * vPret / vParitate,0);
      RETURN;
    END IF;
  ELSE
    IF vTipDiscountC = 1 THEN
      BEGIN
        SELECT COALESCE (cc.ValDiscount, 0) INTO vVal
        FROM contractc         cc
          INNER JOIN contract1 c1 ON c1.codcontract1 = cc.codcontract1
          INNER JOIN num1         ON c1.umsec = num1.codum1
        WHERE
          c1.codcontract1 = vCodContract1
          and cc.cantmin * num1.paritate = (SELECT max (cantmin * num1.paritate) FROM contractc WHERE codcontract1 = c1.codcontract1 and cantmin * num1.paritate &lt;= vTotal);
      EXCEPTION
      WHEN others THEN
        vVal := 0;
      END;

      vRez := coalesce(vVal * vCant / vParitate,0);
      RETURN;
    ELSE
      vRest := vTotal;
      vVal  := 0;
      FOR vrec IN (SELECT cc.CantMin, cc.Discount
                   FROM contract1            c1
                        INNER JOIN contractc cc ON cc.codcontract1 = c1.codcontract1
                   WHERE c1.codcontract1 = vCodContract1 AND cc.cantmin &lt;= vTotal
                   ORDER BY cantmin DESC
                  )
      LOOP
         vLastP := vrec.discount;
          if vTipDiscount = 0 then
            vVal   := vVal + vLastP/100 * vrec.CantMin * vPretMediu;
          else
            vVal   := vVal + vLastP/100 * vrec.CantMin * vPret;
          end if;
          vRest  := vRest - vrec.CantMin;
    END LOOP;
        IF vTipDiscount = 0 THEN
          vVal := vVal + vLastP / 100 * vrec.CantMin * vPretMediu;
        ELSE
          vVal := vVal + vLastP / 100 * vrec.CantMin * vPret;
        END IF;
         vRez := vCant/vTotal * vVal;
    end if;
  END IF;
    vValT := 0;
    if vGlobal &gt; 0 then
    begin
      select coalesce(cc.Discount, 0), coalesce(cc.ValDiscount, 0) into vProc, vVal
      from contractc0 cc
      where cc.cantmin = (select max(c0.cantmin) from contractc0 c0 where c0.codcontract = cc.codcontract and c0.cantmin &lt;= vGlobal)
            and cc.codcontract = vCodContract;
    exception when others then vProc := 0; vVal := 0;
    end;
      if vProc &lt;&gt; 0 then
        if vTipDiscount = 0 then
          vValT := vProc/100 * vValDoc * vCant / vGlobal;
        else
          vValT := vProc/100 * vCant * vPret * vCant / vGlobal;
        end if;
      else if vVal &lt;&gt; 0 then
        vValT := vVal;
      end if;
      end if;
    end if;
    vRez := coalesce(vRez,0) + vValT;
      Wme_Result := vRez * vCurs;
      RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getdisctermencli</obj_name>
  <obj_hashval>d9eb6b4cece5cbeb639bd78aac377ab6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getdisctermencli(INOUT wme_result numeric, INOUT vdataplata character varying, INOUT vnrzile interval, INOUT vcodcontract numeric, INOUT vcoddoc1 numeric, INOUT vplata numeric, INOUT vvalorig numeric DEFAULT 0)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  vrec record;
begin
  vrec := pkg_notecredit_getdisctermencli(null,vdataplata,EXTRACT(day from vnrzile)::numeric,vcodcontract,vcoddoc1,vplata,vvalorig);
  WME_Result := vrec.wme_result;
  return;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getdisctermencli</obj_name>
  <obj_hashval>fe5e34a576c43d03195885c2ec717b5a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getdisctermencli(INOUT wme_result numeric, INOUT vdataplata character varying, INOUT vnrzile numeric, INOUT vcodcontract numeric, INOUT vcoddoc1 numeric, INOUT vplata numeric, INOUT vvalorig numeric DEFAULT 0)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  vDisc         numeric;
  vProc         numeric;
  vTipDiscount  numeric;
  vPretC        numeric;
  vCodContract1 numeric;
  vDiscTCumulat numeric;
  vTipArticol   numeric;
begin
  if coalesce(vCodContract, 0) &gt; 0 and coalesce(vCodDoc1, 0) &gt; 0 then
    SELECT coalesce(TipArticol, 0) INTO vTipArticol FROM contract WHERE codcontract = vCodContract;

    if vTipArticol = 0 then
      SELECT TipDiscount, PretC, CodContract1, DiscTCumulat
      INTO vTipDiscount, vPretC, vCodContract1, vDiscTCumulat
      FROM
          (
          select
            coalesce(C1.TipDiscount, 0) TIPDISCOUNT,
            coalesce(c1.pret, 0) PRETC,
            coalesce(c1.CodContract1, 0) CODCONTRACT1,
            coalesce(C1.DiscTCumulat, 0) DISCTCUMULAT
          FROM iesiri1 i1
          inner join iesiri i ON i.codies = i1.codies
          inner join contract1 c1 ON i1.codobiect = c1.codobiect
          inner join contract c ON c.codcontract = c1.codcontract
          where
            i1.codies1 = vCodDoc1
            and C1.CodContract = vCodContract
            and i.datadoc between coalesce(c1.datastart, c.datastart) and coalesce(c1.datastop, c.datastop)
            and coalesce(c1.sediulivrare, 0) in (0, i.codlocatie)
          order by
            coalesce(c1.sediulivrare, 0) desc
          ) A_PG
      limit 1;
    else
      SELECT TipDiscount, PretC, CodContract1, DiscTCumulat
      INTO vTipDiscount, vPretC, vCodContract1, vDiscTCumulat
      FROM
          (
          select
            coalesce(C1.TipDiscount, 0) TIPDISCOUNT,
            coalesce(c1.pret, 0) PRETC,
            coalesce(c1.CodContract1, 0) CODCONTRACT1,
            coalesce(C1.DiscTCumulat, 0) DISCTCUMULAT
          FROM iesiri1 i1
          inner join iesiri i ON i.codies = i1.codies
          inner join nartobj obj ON obj.codobiect = i1.codobiect
          inner join nart a ON a.codarticol = obj.codarticol
          inner join contract1 c1 ON a.clasa = c1.codclasa
          inner join contract c ON c.codcontract = c1.codcontract
          where
            i1.codies1 = vCodDoc1
            and C1.CodContract = vCodContract
            and i.datadoc between coalesce(c1.datastart, c.datastart) and coalesce(c1.datastop, c.datastop)
            and coalesce(c1.sediulivrare, 0) in (0, i.codlocatie)
          order by
            coalesce(c1.sediulivrare, 0) desc
          ) B_PG
      limit 1;
    end if;

    if vValOrig &gt; 0 then
      if vDiscTCumulat = 0 then
        if vTipDiscount = 0 then
          SELECT coalesce((select pkg_notecredit_GETPROCCONTRACTTERMEN.WME_RESULT from pkg_notecredit_GETPROCCONTRACTTERMEN(null, vDataPlata, vNrZile, vCodContract1)), 0)
          INTO vProc
          FROM iesiri1 i1 WHERE i1.codies1 = vCodDoc1;

          if vProc &lt;&gt; 0 then
            begin
              SELECT CASE when coalesce(i.valdoc, 0) = 0 then 0
                          else coalesce(vProc / 100 * vPlata / i.valdoc * ( case when i.tipdoc = 21 then I1.Cant * I1.PU - I1.Tva else i1.cant * i1.PU end ) , 0) end
              INTO vDisc
              FROM iesiri1 i1 inner join iesiri i ON i1.codies = i.codies
              WHERE i1.codies1 = vCodDoc1;
            exception
              when others then vDisc := 0;
            end;
          else
            SELECT CASE when coalesce(i.valdoc, 0) = 0 then 0
                        else coalesce((select pkg_notecredit_GETVALDISCCONTRACTTERMEN.WME_RESULT from pkg_notecredit_GETVALDISCCONTRACTTERMEN(null, vDataPlata, vNrZile, vCodContract1)), 0) * I1.Cant * vPlata / i.valdoc end
            INTO vDisc
            FROM iesiri1 i1 inner join iesiri i ON i1.codies = i.codies
            WHERE i1.codies1 = vCodDoc1;
          end if;
        else
          SELECT coalesce((select pkg_notecredit_GETPROCCONTRACTTERMEN.WME_RESULT from pkg_notecredit_GETPROCCONTRACTTERMEN(null, vDataPlata, vNrZile, vCodContract1)), 0)
          INTO vProc
          FROM iesiri1 i1 WHERE i1.codies1 = vCodDoc1;

          if vProc &lt;&gt; 0 then
            begin
              SELECT CASE when coalesce(i.valdoc, 0) = 0 then 0
                          else coalesce(vProc / 100 * vPlata / i.valdoc * ( case when i.tipdoc = 21 then I1.Cant * vPretC - I1.Tva else i1.cant * vPretC end ) , 0) end
              INTO vDisc
              FROM iesiri1 i1 inner join iesiri i ON i1.codies = i.codies
              WHERE i1.codies1 = vCodDoc1;
            exception
              when others then vDisc := 0;
            end;
          else
            SELECT CASE when coalesce(i.valdoc, 0) = 0 then 0
                        else coalesce((select pkg_notecredit_GETVALDISCCONTRACTTERMEN.WME_RESULT from pkg_notecredit_GETVALDISCCONTRACTTERMEN(null, vDataPlata, vNrZile, vCodContract1)), 0) * I1.Cant * vPlata / i.valdoc end
            INTO vDisc
            FROM iesiri1 i1 inner join iesiri i ON i1.codies = i.codies
            WHERE i1.codies1 = vCodDoc1;
          end if;
        end if;
      else
        vDisc := (SELECT pkg_notecredit_GETDISCCUMULAT.WME_RESULT FROM pkg_notecredit_GETDISCCUMULAT(null, vCodDoc1, vCodContract1, 1, null));
      end if;
    else
      if vDiscTCumulat = 0 then
        if vTipDiscount = 0 then
          SELECT coalesce((select pkg_notecredit_GETPROCCONTRACTTERMEN.WME_RESULT from pkg_notecredit_GETPROCCONTRACTTERMEN(null, vDataPlata, vNrZile, vCodContract1)), 0)
          INTO vProc
          FROM iesiri1 i1 WHERE i1.codies1 = vCodDoc1;

          if vProc &lt;&gt; 0 then
            begin
              SELECT CASE when coalesce(i.valdoc, 0) = 0 then 0
                          else coalesce(vProc / 100 * vPlata / i.valdoc * ( case when i.tipdoc = 21 then ( I1.Cant * I1.PU - I1.Tva) * I1.Coefdiscmaj else i1.cant * i1.PU * i1.coefdiscmaj end ) , 0) end
              INTO vDisc
              FROM iesiri1 i1 inner join iesiri i ON i1.codies = i.codies
              WHERE i1.codies1 = vCodDoc1;
            exception
              when others then vDisc := 0;
            end;
          else
            SELECT CASE when coalesce(i.valdoc, 0) = 0 then 0
                        else coalesce((select pkg_notecredit_GETVALDISCCONTRACTTERMEN.WME_RESULT from pkg_notecredit_GETVALDISCCONTRACTTERMEN(null, vDataPlata, vNrZile, vCodContract1)), 0) * I1.Cant * vPlata / i.valdoc end
            INTO vDisc
            FROM iesiri1 i1 inner join iesiri i ON i1.codies = i.codies
            WHERE i1.codies1 = vCodDoc1;
          end if;
        else
          SELECT coalesce((select pkg_notecredit_GETPROCCONTRACTTERMEN.WME_RESULT from pkg_notecredit_GETPROCCONTRACTTERMEN(null, vDataPlata, vNrZile, vCodContract1)), 0)
          INTO vProc
          FROM iesiri1 i1 WHERE i1.codies1 = vCodDoc1;

          if vProc &lt;&gt; 0 then
            begin
              SELECT CASE when coalesce(i.valdoc, 0) = 0 then 0
                          else coalesce(vProc / 100 * vPlata / i.valdoc * ( case when i.tipdoc = 21 then I1.Cant * vPretC - I1.Tva else i1.cant * vPretC end ) , 0) end
              INTO vDisc
              FROM iesiri1 i1 inner join iesiri i ON i1.codies = i.codies
              WHERE i1.codies1 = vCodDoc1;
            exception
              when others then vDisc := 0;
            end;
          else
            SELECT CASE when coalesce(i.valdoc, 0) = 0 then 0
                        else coalesce((select pkg_notecredit_GETVALDISCCONTRACTTERMEN.WME_RESULT from pkg_notecredit_GETVALDISCCONTRACTTERMEN(null, vDataPlata, vNrZile, vCodContract1)), 0) * I1.Cant * vPlata / i.valdoc end
            INTO vDisc
            FROM iesiri1 i1 inner join iesiri i ON i1.codies = i.codies
            WHERE i1.codies1 = vCodDoc1;
          end if;
        end if;
      else
        vDisc := (SELECT pkg_notecredit_GETDISCCUMULAT.WME_RESULT FROM pkg_notecredit_GETDISCCUMULAT(null, vCodDoc1, vCodContract1, 1, null));
      end if;
    end if;
  ELSE
    vDisc := 0;
  end if;

  WME_Result := vDisc;
  return;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getdisctermenfurn</obj_name>
  <obj_hashval>be01b15ad60a4e1c857826a91130eee7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getdisctermenfurn(INOUT wme_result numeric, INOUT vdataplata character varying, INOUT vnrzile numeric, INOUT vcodcontract numeric, INOUT vcoddoc1 numeric, INOUT vplata numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vDisc         numeric;
  vProc         numeric;
  vTipDiscount  numeric;
  vPretC        numeric;
  vCodContract1 numeric;
  vDiscTCumulat numeric;
  vTipArticol   numeric;
BEGIN
  --Florin 05.01.2023 - sinc. Oracle (03.01.2023)
  --Florin 20.04.2023 - sinc. Oracle (12.04.2023)
  --Laura 15.09.2021 - sinc Oracle (14.09.2021)
  IF  vCodContract &gt; 0 THEN
    SELECT COALESCE(TipArticol, 0) INTO vTipArticol FROM contract WHERE codcontract = vCodContract;

    IF  vTipArticol = 0 THEN
      SELECT COALESCE(C1.TipDiscount, 0), COALESCE(c1.pret, 0), COALESCE(c1.CodContract1, 0), COALESCE(C1.DiscTCumulat, 0)
      INTO vTipDiscount, vPretC, vCodContract1, vDiscTCumulat
      FROM intrari1 i1
          INNER JOIN intrari   i  ON  i.codintr     = i1.codintr
          INNER JOIN contract1 c1 ON  i1.codobiect  = c1.codobiect
          INNER JOIN contract  c  ON  c.codcontract = c1.codcontract
      WHERE i1.codintr1 = vCodDoc1 and  C1.CodContract = vCodContract and i.datadoc BETWEEN COALESCE(c1.datastart, c.datastart) AND COALESCE(c1.datastop, c.datastop);
    ELSE
      SELECT COALESCE(C1.TipDiscount, 0), COALESCE(c1.pret, 0), COALESCE(c1.CodContract1, 0), COALESCE(C1.DiscTCumulat, 0)
      INTO vTipDiscount, vPretC, vCodContract1, vDiscTCumulat
      FROM intrari1 i1
          INNER JOIN intrari   i   ON  i.codintr     = i1.codintr
          INNER JOIN nartobj   obj ON  obj.codobiect = i1.codobiect
          INNER JOIN nart      a   ON  a.codarticol  = obj.codarticol
          INNER JOIN contract1 c1  ON  a.clasa       = c1.codclasa
          INNER JOIN contract  c   ON  c.codcontract = c1.codcontract
      WHERE i1.codintr1 = vCodDoc1 and  C1.CodContract = vCodContract and i.datadoc BETWEEN COALESCE(c1.datastart, c.datastart) AND COALESCE(c1.datastop, c.datastop);
    END IF;

    IF  vDiscTCumulat = 0 THEN
      IF  vTipDiscount = 0 THEN
        SELECT COALESCE((SELECT pkg_notecredit_GETPROCCONTRACTTERMEN.WME_RESULT FROM pkg_notecredit_GETPROCCONTRACTTERMEN(NULL,vDataplata, vNrZile, vCodContract1)), 0)
        INTO vProc
        FROM intrari1 i1
        WHERE i1.codintr1 = vCodDoc1;

        IF  vProc &lt;&gt; 0 THEN
          BEGIN
            select
              case when coalesce(i.valdoc,0)=0 then 0 else ---razvan
              nvl((SELECT pkg_notecredit_GETPROCCONTRACTTERMEN.WME_RESULT FROM pkg_notecredit_GETPROCCONTRACTTERMEN(NULL,vDataPlata, vNrZile, vCodContract1)) * vPlata/i.valdoc *
              case when i.tipdoc = 9 then I1.Cant * I1.PU + i1.tva else i1.cant * i1.pu end/100, 0) end into vDisc
            FROM intrari1 i1 INNER JOIN intrari i ON  i1.codintr = i.codintr
            WHERE i1.codintr1 = vCodDoc1;
          EXCEPTION WHEN others THEN
            vDisc := 0;
          END;
        ELSE
          SELECT case
              when coalesce(i.valdoc,0) = 0 then 0
              when I1.Cant * I1.PU + i1.tva = 0 then 0
              when I1.Cant * I1.PU = 0 then 0
              else COALESCE((SELECT pkg_notecredit_GETVALDISCCONTRACTTERMEN.WME_RESULT FROM pkg_notecredit_GETVALDISCCONTRACTTERMEN(NULL,vDataPlata, vNrZile, vCodContract1)), 0) * I1.Cant * vPlata/case when i.tipdoc = 9 then I1.Cant * I1.PU + i1.tva else i1.cant * i1.pu end
               end INTO vDisc
          FROM intrari1 i1 INNER JOIN intrari i ON  i.codintr = i1.codintr
          WHERE i1.codintr1 = vCodDoc1;
        END IF;
      ELSE
        SELECT COALESCE((SELECT pkg_notecredit_GETPROCCONTRACTTERMEN.WME_RESULT FROM pkg_notecredit_GETPROCCONTRACTTERMEN(NULL,vDataplata, vNrZile, vCodContract1)), 0)
        INTO vProc
        FROM intrari1 i1 WHERE i1.codintr1 = vCodDoc1;

        IF  vProc &lt;&gt; 0 THEN
          BEGIN
            SELECT
              case when coalesce(i.valdoc,0)=0 then 0 else ---razvan
              nvl((SELECT pkg_notecredit_GETPROCCONTRACTTERMEN.WME_RESULT FROM pkg_notecredit_GETPROCCONTRACTTERMEN(NULL,vDataPlata, vNrZile, vCodContract1)) * vPlata/i.valdoc * (I1.Cant * vPretC)/100, 0)
              end into vDisc
            FROM intrari1 i1 INNER JOIN intrari i ON  i1.codintr = i.codintr
            WHERE i1.codintr1 = vCodDoc1;
          EXCEPTION WHEN others THEN
            vDisc := 0;
          END;
        ELSE
          select case
              when coalesce(i.valdoc,0) = 0 then 0
              else COALESCE((SELECT pkg_notecredit_GETVALDISCCONTRACTTERMEN.WME_RESULT FROM pkg_notecredit_GETVALDISCCONTRACTTERMEN(NULL,vDataPlata, vNrZile, vCodContract1)), 0) * I1.Cant * vPlata / i.valdoc
              end INTO vDisc
          FROM intrari1 i1 INNER JOIN intrari i ON  i.codintr = i1.codintr
          WHERE i1.codintr1 = vCodDoc1;
        END IF;
      END IF;
    ELSE
      vDisc := (SELECT pkg_notecredit_GETDISCCUMULAT.WME_RESULT FROM pkg_notecredit_GETDISCCUMULAT(NULL,vCodDoc1, vCodContract1, 2,NULL));
    END IF;
  ELSE
    vDisc := 0;
  END IF;

  WME_Result :=  vDisc;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getdiscvollinie</obj_name>
  <obj_hashval>1d10c1c0af499a1fa816e72b4ea601ba</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getdiscvollinie(INOUT wme_result numeric, INOUT acoddoc1 numeric, INOUT atipnc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aValDisc  numeric;
  aValDisc1 numeric;
  aCodDoc   numeric;
begin
  IF  aTipNC = 59 THEN
    BEGIN
      SELECT codintr INTO aCodDoc FROM intrari1 WHERE codintr1 = aCodDoc1;
    EXCEPTION WHEN others THEN
      aCodDoc := 0;
    END;
  ELSE
    BEGIN
      SELECT codies INTO aCodDoc FROM iesiri1 WHERE codies1 = aCodDoc1;
    EXCEPTION WHEN others THEN
      aCodDoc := 0;
    END;
  END IF;

  aValDisc := 0.0;

  IF  aTipNC = 59 THEN
    BEGIN
      SELECT sum(NC1.valoare)
      INTO aValDisc
      FROM NOTECREDIT1 NC1
        INNER JOIN NOTECREDIT NC ON  NC1.CODNCREDIT = NC.CODNCREDIT
        INNER JOIN INTRARI1   I1 ON  I1.CODINTR1    = NC1.CODDOC
        INNER JOIN INTRARI    I  ON  I1.CODINTR     = I.CODINTR AND  NC1.TIPDOC = I.TIPDOC
        LEFT  JOIN CONTRACT   C  ON  NC.CODCONTRACT = C.CODCONTRACT
      WHERE
        (NC1.CODDOC = aCodDoc1 AND (COALESCE(C.TipTargetV, -1) = 2 OR  NC.VOLUMPEARTICOLE = 1) )  AND  NC1.Valoare &lt;&gt; 0 AND  I.TIPDOC = NC1.TIPDOC AND  NC1.TIP = current_setting('PKG_NOTECREDIT.tncVolum', true)::numeric;
    EXCEPTION WHEN others THEN
      aValDisc := 0.0;
    END;

    BEGIN
      SELECT SUM(NC1.VALOARE * I1.CANT * I1.PRETORIG / CENTR.VAL)
      INTO aValDisc1
      FROM NOTECREDIT1 NC1
      INNER JOIN NOTECREDIT NC ON  NC1.CODNCREDIT = NC.CODNCREDIT
      INNER JOIN INTRARI I ON  NC1.CODDOC = I.CODINTR AND  I.TIPDOC = NC1.TIPDOC
      INNER JOIN (SELECT SUM(II1.CANT * II1.PRETORIG) VAL, II1.CODINTR FROM INTRARI1 II1 WHERE II1.CODINTR = aCodDoc GROUP BY II1.CODINTR) CENTR ON  CENTR.CODINTR = I.CODINTR
      INNER JOIN INTRARI1 I1 ON  I1.CODINTR = I.CODINTR AND  I1.CODINTR1 = aCodDoc1
      LEFT JOIN CONTRACT C ON  NC.CODCONTRACT = C.CODCONTRACT
      WHERE
        (NC1.CODDOC = aCodDoc AND  COALESCE(C.TipTargetV, -1) &lt;&gt; 2 AND  NC.VOLUMPEARTICOLE &lt;&gt; 1)  AND  NC1.Valoare &lt;&gt; 0 AND  NC1.TIP = current_setting('PKG_NOTECREDIT.tncVolum', true)::numeric;
    EXCEPTION WHEN others THEN
      aValDisc1 := 0;
    END;
  ELSE
    BEGIN
      SELECT sum(NC1.valoare)
      INTO aValDisc
      FROM NOTECREDIT1 NC1
        INNER JOIN NOTECREDIT NC ON  NC1.CODNCREDIT = NC.CODNCREDIT
        INNER JOIN IESIRI1    I1 ON  I1.CODIES1     = NC1.CODDOC
        INNER JOIN IESIRI     I  ON  I1.CODIES      = I.CODIES AND  NC1.TIPDOC = I.TIPDOC
        LEFT  JOIN CONTRACT   C  ON  NC.CODCONTRACT = C.CODCONTRACT
      WHERE
        (NC1.CODDOC = aCodDoc1 AND (COALESCE(C.TipTargetV, -1) = 2 OR  NC.VOLUMPEARTICOLE = 1) )  AND  NC1.Valoare &lt;&gt; 0 AND  I.TIPDOC = NC1.TIPDOC AND  NC1.TIP = current_setting('PKG_NOTECREDIT.tncVolum', true)::numeric;
    EXCEPTION WHEN others THEN
      aValDisc := 0.0;
    END;

    BEGIN
      SELECT SUM(NC1.VALOARE * I1.CANT * I1.PRETORIG / CENTR.VAL)
      INTO aValDisc1
      FROM NOTECREDIT1 NC1
      INNER JOIN NOTECREDIT NC ON  NC1.CODNCREDIT = NC.CODNCREDIT
      INNER JOIN IESIRI I ON  NC1.CODDOC = I.CODIES AND  I.TIPDOC = NC1.TIPDOC
      INNER JOIN (SELECT SUM(II1.CANT * II1.PRETORIG) VAL, II1.CODIES FROM IESIRI1 II1 WHERE II1.CODIES = aCodDoc GROUP BY II1.CODIES) CENTR ON  CENTR.CODIES = I.CODIES
      INNER JOIN IESIRI1 I1 ON  I1.CODIES = I.CODIES AND  I1.CODIES1 = aCodDoc1
      LEFT JOIN CONTRACT C ON  NC.CODCONTRACT = C.CODCONTRACT
      WHERE
        (NC1.CODDOC = aCodDoc AND  COALESCE(C.TipTargetV, -1) &lt;&gt; 2 AND  NC.VOLUMPEARTICOLE &lt;&gt; 1)  AND  NC1.Valoare &lt;&gt; 0 AND  NC1.TIP = current_setting('PKG_NOTECREDIT.tncVolum', true)::numeric;
    EXCEPTION WHEN others THEN
      aValDisc1 := 0;
    END;
  END IF;

  aValDisc := COALESCE(aValDisc, 0) + COALESCE(aValDisc1, 0);

  WME_Result :=  aValDisc;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getkartdiscaccant</obj_name>
  <obj_hashval>760d7ca5c2000fa273a1e662648bf75f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getkartdiscaccant(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.KArtDiscAcCant', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getkartdiscacter</obj_name>
  <obj_hashval>fe392ce98a203cde29a566157904fba2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getkartdiscacter(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOTECREDIT.KArtDiscAcTer', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getkartdiscacter</obj_name>
  <obj_hashval>0e38f49ee620d831c3cf86f6a597d5ec</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getkartdiscacter(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.KArtDiscAcTer', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := '';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getkartdiscacvol</obj_name>
  <obj_hashval>c222574f93255df584ad343acf6fd17b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getkartdiscacvol(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.KArtDiscAcVol', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getkartdiscoffinvoicec</obj_name>
  <obj_hashval>0e1634424d446728a1e436437df09afe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getkartdiscoffinvoicec(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.KArtDiscOffInvoiceC', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getkartdiscoffinvoicef</obj_name>
  <obj_hashval>3215ac2307a31b1b2d9e54c3059f02fa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getkartdiscoffinvoicef(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.KArtDiscOffInvoiceF', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getkartdiscprimcant</obj_name>
  <obj_hashval>3d674e18bf2738e145f8cfd7d4c71443</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getkartdiscprimcant(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.KArtDiscPrimCant', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getkartdiscprimter</obj_name>
  <obj_hashval>8987973a23ae58de97871d2127040e78</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getkartdiscprimter(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.KArtDiscPrimTer', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getkartdiscprimvol</obj_name>
  <obj_hashval>c69ca2039afbfe3ca944f7fea616d05e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getkartdiscprimvol(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.KArtDiscPrimVol', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getkartpenacter</obj_name>
  <obj_hashval>842acc012877ce7def0d8f6b6c32d690</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getkartpenacter(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.KArtPenAcTer', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getkartpenprimter</obj_name>
  <obj_hashval>69ca51571a064177e333a78cb9cd8741</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getkartpenprimter(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.KArtPenPrimTer', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getnrdoc_i</obj_name>
  <obj_hashval>3b9b51ef793b6f10aa4a8e4798f1d1db</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getnrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.NRDOC_I', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getproccontractcant</obj_name>
  <obj_hashval>d060c65e87a2ac512fbcde8134cc2fdc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getproccontractcant(INOUT wme_result numeric, INOUT vcodobiect numeric, INOUT vvaloare numeric, INOUT vcodcontract numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vProc numeric;
begin
  BEGIN
    SELECT COALESCE(cc.Discount, 0)
    INTO vProc
    FROM contractc cc
        INNER JOIN contract1 c1 ON  c1.codcontract1 = cc.codcontract1
        INNER JOIN num1         ON  c1.umsec        = num1.codum1
    WHERE  c1.codcontract = vCodContract and  c1.codobiect = vCodObiect
      and  cc.cantmin = (SELECT max(cantmin * num1.paritate) FROM contractc ccv WHERE ccv.codcontract1 = c1.codcontract1 and  cantmin * num1.paritate &lt;= vValoare);
  EXCEPTION WHEN others THEN
    vProc := 0;
  END;

  WME_Result :=  vProc;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getproccontractpen</obj_name>
  <obj_hashval>e9d6d4f89ec4c5347c6ac3c507e24184</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getproccontractpen(INOUT wme_result numeric, INOUT vcodcontract numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vProc numeric;
begin
  BEGIN
    SELECT COALESCE(ct.PROCMAJ, 0) INTO vProc FROM contract ct WHERE ct.codcontract = vCodContract;
  EXCEPTION WHEN others THEN
    vProc := 0;
  END;

  WME_Result :=  vProc;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getproccontracttermen</obj_name>
  <obj_hashval>bc5997c1ccf942eb7777f08269c7a710</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getproccontracttermen(INOUT wme_result numeric, INOUT vdataplata character varying, INOUT vnrzile numeric, INOUT vcodcontract1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vProc numeric;
  vTip  numeric;
begin
  BEGIN
    SELECT COALESCE(c1.TipDiscountT, 0) INTO vTip FROM contract1 c1 WHERE c1.codcontract1 = vCodContract1;
  EXCEPTION WHEN others THEN
    vTip := -1;
  END;

  IF  vTip = -1 THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  IF  vTip = 0 THEN
    BEGIN
      SELECT COALESCE(ct.Discount, 0)
      INTO vProc
      FROM contractt ct INNER JOIN contract1 c1 ON  ct.codcontract1 = c1.codcontract1
      WHERE c1.codcontract1 = vCodContract1 and  ct.zile = (SELECT min(zile) FROM contractt ctt WHERE codcontract1 = c1.codcontract1 and  zile &gt;= vNrZile);
    EXCEPTION WHEN others THEN
      vProc := 0;
    END;
  ELSE
    BEGIN
      SELECT COALESCE(ct.Discount, 0)
      INTO vProc
      FROM contractt ct INNER JOIN contract1 c1 ON  ct.codcontract1 = c1.codcontract1
      WHERE  c1.codcontract1 = vCodContract1
        and  ct.TermenFix = (SELECT min(termenfix) FROM contractt WHERE codcontract1 = c1.codcontract1 and  to_date(vDataPlata, 'DD.MM.YYYY') &lt;= termenfix);
    EXCEPTION WHEN others THEN
      vProc := 0;
    END;
  END IF;

  WME_Result :=  vProc;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getproccontractvolum</obj_name>
  <obj_hashval>21d764899326baf991232a160463bfa9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getproccontractvolum(INOUT wme_result numeric, INOUT vsuma numeric, INOUT vcodcontract numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vProc numeric;
  vTip  numeric;
begin
  SELECT c.tiptargetv INTO vTip FROM contract c WHERE codcontract = vCodContract;

  IF  vTip &lt;= 1 THEN
    BEGIN
      SELECT COALESCE(cv.Discount, 0)
      INTO vProc
      FROM contractv cv
      WHERE cv.codcontract = vCodContract and  cv.suma = (SELECT max(suma) FROM contractv CCv WHERE CCv.Codcontract = vCodContract and  suma &lt;= vSuma);
    EXCEPTION WHEN others THEN
      vProc := 0;
    END;
  END IF;

  WME_Result :=  vProc;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_gettncpenalizari</obj_name>
  <obj_hashval>c4d379cfcc1ea789c4de63c6e596de99</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_gettncpenalizari(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.tncPenalizari', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 6;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_gettncprovizioane</obj_name>
  <obj_hashval>bc443fb7ca9c7eeecc09ec765030fd39</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_gettncprovizioane(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.tncProvizioane', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 5;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_gettnctermen</obj_name>
  <obj_hashval>9a5c7ff475a8b27763b5cfde0f9e1a0a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_gettnctermen(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.tncTermen', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 1;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_gettncvolum</obj_name>
  <obj_hashval>fdd644406a8bfe211854952f6c3bfd78</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_gettncvolum(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.tncVolum', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 2;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getvaldisccontracttermen</obj_name>
  <obj_hashval>482b6e56e3b531d7e70426c9f0c7c57a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getvaldisccontracttermen(INOUT wme_result numeric, INOUT vdataplata character varying, INOUT vnrzile numeric, INOUT vcodcontract1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vProc numeric;
  vTip numeric;
begin
  BEGIN
    SELECT COALESCE(c1.tipdiscountt, 0) INTO vTip FROM contract1 c1 WHERE c1.codcontract1 = vCodContract1;
  EXCEPTION WHEN others THEN
    vTip := -1;
  END;

  IF  vTip = -1 THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  IF  vTip = 0 THEN
    BEGIN
      SELECT COALESCE(ct.ValDiscount, 0)
      INTO vProc
      FROM contractt ct INNER JOIN contract1 c1 ON  ct.codcontract1 = c1.codcontract1
      WHERE c1.codcontract1 = vCodContract1 and  ct.zile = (SELECT min(zile) FROM contractt ctt WHERE ctt.codcontract1 = c1.codcontract1 and  zile &gt;= vNrZile);
    EXCEPTION WHEN others THEN
      vProc := 0;
    END;
  ELSE
    BEGIN
      SELECT COALESCE(ct.ValDiscount, 0)
      INTO vProc
      FROM contractt ct INNER JOIN contract1 c1 ON  ct.codcontract1 = c1.codcontract1
      WHERE  c1.codcontract1 = vCodContract1
        and  ct.TermenFix = (SELECT min(termenfix) FROM contractt WHERE codcontract1 = c1.codcontract1 and  to_date(vDataPlata, 'DD.MM.YYYY') &lt;= termenfix);
    EXCEPTION WHEN others THEN
      vProc := 0;
    END;
  END IF;

  WME_Result :=  vProc;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getvaldisccontractvolum</obj_name>
  <obj_hashval>d20ff90ad2d31584d6152a11ba78d032</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getvaldisccontractvolum(INOUT wme_result numeric, INOUT vsuma numeric, INOUT vcodcontract numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vProc numeric;
begin
  BEGIN
    SELECT COALESCE(cv.ValDiscount, 0)
    INTO vProc
    FROM contractv cv
    WHERE cv.codcontract = vCodContract and  cv.suma = (SELECT max(suma) FROM contractv CCv WHERE CCv.Codcontract = vCodContract and  suma &lt;= vSuma);
  EXCEPTION WHEN others THEN
    vProc := 0;
  END;

  WME_Result :=  vProc;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getvaldiscncvol</obj_name>
  <obj_hashval>057568161f6627f88ae0084083093f77</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getvaldiscncvol(INOUT wme_result numeric, INOUT acodies1 numeric, INOUT acantlivr numeric, INOUT acodies numeric, INOUT atipdoc numeric, INOUT acant numeric, INOUT apu numeric, INOUT atva numeric, INOUT aaddim numeric, INOUT acoefdiscmaj numeric, INOUT avaldiscpret numeric, INOUT avaldoc numeric, INOUT atvadoc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  aValPeArt numeric;
  aValPeDoc numeric;
begin
  aValPeArt := 0;
  aValPeDoc := 0;

  FOR v_rec IN (SELECT nc1.valoare
                FROM NOTECREDIT NC
                    INNER JOIN NOTECREDIT1 NC1 ON  NC.CODNCREDIT  = NC1.CODNCREDIT
                    LEFT  JOIN CONTRACT    C   ON  NC.CODCONTRACT = C.CODCONTRACT
                WHERE ((NC.CODCONTRACT &gt; 0 AND  COALESCE(C.TIPTARGETV, 0) = 2 AND  NC.TIPDOC = 58 AND  NC1.TIP = current_setting('PKG_NOTECREDIT.tncVolum', true)::numeric AND  NC1.CODDOC = aCodIes1 AND  NC1.TIPDOC = aTipDoc)
                        OR
                       (COALESCE(NC.CODCONTRACT, 0) = 0 AND  NC.VOLUMPEARTICOLE = 1 AND  NC.TIPDOC = 58 AND  NC1.TIP = current_setting('PKG_NOTECREDIT.tncVolum', true)::numeric AND  NC1.CODDOC = aCodIes1 AND  NC1.TIPDOC = aTipDoc)
                      )
  )
  LOOP
    aValPeArt := aValPeArt + v_rec.Valoare;
  END LOOP;

  FOR v_rec IN (SELECT nc1.valoare
                FROM NOTECREDIT NC
                INNER JOIN NOTECREDIT1 NC1 ON  NC.CODNCREDIT = NC1.CODNCREDIT
                LEFT JOIN CONTRACT C ON  NC.CODCONTRACT = C.CODCONTRACT
                WHERE
                  ((NC.CODCONTRACT &gt; 0 AND  COALESCE(C.TIPTARGETV, 0) &lt; 2 AND  NC.TIPDOC = 58 AND  NC1.TIP = current_setting('PKG_NOTECREDIT.tncVolum', true)::numeric AND  NC1.CODDOC = aCodIes AND  NC1.TIPDOC = aTipDoc)
                    OR
                   (COALESCE(NC.CODCONTRACT, 0) = 0 AND  COALESCE(NC.VOLUMPEARTICOLE, 0) = 0 AND  NC.TIPDOC = 58 AND  NC1.TIP = current_setting('PKG_NOTECREDIT.tncVolum', true)::numeric AND  NC1.CODDOC = aCodIes AND  NC1.TIPDOC = aTipDoc)
                  )
                )
  LOOP
    aValPeDoc := aValPeDoc + v_rec.Valoare;
  END LOOP;

  IF  aValPeDoc &lt;&gt; 0 THEN
    aValPeDoc := aCantLivr * (SELECT PKG_LIST_BASE_IESIRI_CALCPIES.WME_RESULT FROM PKG_LIST_BASE_IESIRI_CALCPIES(NULL,aCodIes, aTipDoc, aCant, aPU, aTVA, aAdDim, aCoefdiscmaj, aValdiscpret,NULL)) / (  aValdoc - aTvadoc)  * aValPeDoc;
  END IF;

  WME_Result :=  aValPeArt + aValPeDoc;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getvalobiecties</obj_name>
  <obj_hashval>622606c197442a09c1768d42d8a9ffdd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getvalobiecties(INOUT wme_result numeric, INOUT acodies1 numeric, INOUT atipdiscount numeric, INOUT apretc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodObiect numeric;
  aVal       numeric;
begin
  IF  aTipDiscount = 0 THEN
    SELECT i1.codobiect INTO aCodObiect FROM iesiri1 i1 WHERE i1.codies1 = aCodIes1;

    SELECT sum(CASE WHEN  i.tipdoc = 21 THEN I1.Cant * I1.PU * I1.Coefdiscmaj - I1.Tva ELSE i1.cant * i1.PU * i1.coefdiscmaj END )
    INTO aVal
    FROM iesiri1 i1 INNER JOIN iesiri i ON  i1.codies = i.codies
    WHERE i.codies = (SELECT codies FROM iesiri1 WHERE codies1 = aCodIes1) and  i1.codobiect = aCodObiect;
  ELSE
    SELECT i1.codobiect INTO aCodObiect FROM iesiri1 i1 WHERE i1.codies1 = aCodIes1;

    SELECT sum(CASE WHEN  i.tipdoc = 21 THEN I1.Cant * aPretC * I1.Coefdiscmaj - I1.Tva ELSE i1.cant * aPretC * i1.coefdiscmaj END )
    INTO aVal
    FROM iesiri1 i1 INNER JOIN iesiri i ON  i1.codies = i.codies
    WHERE i.codies = (SELECT codies FROM iesiri1 WHERE codies1 = aCodIes1) and  i1.codobiect = aCodObiect;
  END IF;

  WME_Result :=  aVal;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getvalobiectintr</obj_name>
  <obj_hashval>a368072686451fa9e4434cc3d3a503aa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getvalobiectintr(INOUT wme_result numeric, INOUT acodintr1 numeric, INOUT atipdiscount numeric, INOUT apretc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodObiect numeric;
  aVal       numeric;
begin
  IF  aTipDiscount = 0 THEN
    SELECT i1.codobiect INTO aCodObiect FROM intrari1 i1 WHERE i1.codintr1 = aCodIntr1;

    SELECT sum(I1.Cant * I1.PU * i1.Coefdiscmaj)
    INTO aVal
    FROM intrari1 i1 INNER JOIN intrari i ON  i1.codintr = i.codintr
    WHERE i.codintr = (SELECT codintr FROM intrari1 WHERE codintr1 = aCodIntr1) and  i1.codobiect = aCodObiect;
  ELSE
    SELECT i1.codobiect INTO aCodObiect FROM intrari1 i1 WHERE i1.codintr1 = aCodIntr1;

    SELECT sum(I1.Cant * aPretC * i1.Coefdiscmaj)
    INTO aVal
    FROM intrari1 i1 INNER JOIN intrari i ON  i1.codintr = i.codintr
    WHERE i.codintr = (SELECT codintr FROM intrari1 WHERE codintr1 = aCodIntr1) and  i1.codobiect = aCodObiect;
  END IF;

  WME_Result :=  aVal;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_intrarecudiscount</obj_name>
  <obj_hashval>9aa1de192453116ba6887eacb364adea</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_intrarecudiscount(INOUT wme_result numeric, INOUT codintr numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCount numeric;
BEGIN
  --Florin 05.01.2023 - sinc. Oracle (03.01.2023)
  BEGIN
    SELECT count(i1.codobiect)
    INTO aCount
    FROM intrari1 i1
    WHERE i1.codintr = CodIntr
      and i1.CodObiect IN (COALESCE((fnc_GetValConstantalucru('ArtDiscPrimVol' )::numeric), 0),
                           COALESCE((fnc_GetValConstantalucru('ArtDiscPrimCant')::numeric), 0),
                           COALESCE((fnc_GetValConstantalucru('ArtPenPrim'     )::numeric), 0))
      OR INSTR(fnc_GetValConstantalucru('ArtDiscPrimVol' ), (I1.CODOBIECT)::varchar &gt; 0);
  EXCEPTION WHEN others THEN
    aCount := 0;
  END;

  WME_Result :=  aCount;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_iscumulat</obj_name>
  <obj_hashval>5afdc478de0448bc3ea66e4077311fef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_iscumulat(INOUT wme_result numeric, INOUT vcoddoc1 numeric, INOUT vcodcontract numeric, INOUT vtip numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCumulat numeric;
begin
  --Bogdan 23.12.2020

  vCumulat := 0;
  IF vTip = 1 THEN
    IF vCodContract &gt; 0 THEN
      BEGIN
        SELECT COALESCE (C1.DISCTCUMULAT, 0)
        into STRICT vCumulat
        FROM iesiri1           i1
          INNER JOIN iesiri    i  ON i.codies       = i1.codies
          INNER JOIN contract1 c1 ON i1.codobiect   = c1.codobiect
          INNER JOIN contract  c  ON c1.codcontract = c.codcontract
        WHERE
          i1.codies1 = vCodDoc1
          and C1.CodContract = vCodContract
          and i.datadoc BETWEEN COALESCE (c1.datastart, c.datastart) AND COALESCE (c1.datastop, c.datastop);

      EXCEPTION
      WHEN others THEN
        vCumulat := 0;
      END;
    END IF;
  ELSE
    IF vCodContract &gt; 0 THEN
      BEGIN
        SELECT COALESCE (C1.DISCTCUMULAT, 0)
        into STRICT vCumulat
        FROM intrari1          i1
          INNER JOIN intrari   i  ON i.codintr      = i1.codintr
          INNER JOIN contract1 c1 ON i1.codobiect   = c1.codobiect
          INNER JOIN contract  c  ON c1.codcontract = c.codcontract
        WHERE
          i1.codintr1 = vCodDoc1
          and C1.CodContract = vCodContract
          and i.datadoc BETWEEN COALESCE (c1.datastart, c.datastart) AND COALESCE (c1.datastop, c.datastop);

      EXCEPTION
      WHEN others THEN
        vCumulat := 0;
      END;
    END IF;
  END IF;

  WME_Result := vCumulat;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_kartdiscacter</obj_name>
  <obj_hashval>3712da3e045eaa3a2f829552e4f4b69e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_kartdiscacter(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOTECREDIT.KArtDiscAcTer', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_kartdiscacter</obj_name>
  <obj_hashval>3676c6692470b1ff8cb2ec5ce4629455</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_kartdiscacter(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.KArtDiscAcTer', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := '';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_kartdiscacvol</obj_name>
  <obj_hashval>186a6e1bde338fe9229a5f9d6abe4206</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_kartdiscacvol(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.KArtDiscAcVol', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_kartdiscoffinvoicec</obj_name>
  <obj_hashval>40b3afba9cd308b0e53ce426b17b99ff</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_kartdiscoffinvoicec(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.KArtDiscOffInvoiceC', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_kartdiscoffinvoicef</obj_name>
  <obj_hashval>a4af58c21431e8de990b8304ce180d29</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_kartdiscoffinvoicef(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.KArtDiscOffInvoiceF', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_kartdiscprimcant</obj_name>
  <obj_hashval>52197ea5b162eb81337d95e839017ae1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_kartdiscprimcant(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.KArtDiscPrimCant', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_kartdiscprimter</obj_name>
  <obj_hashval>056ada5cf1186d963472cde706aa8d38</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_kartdiscprimter(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.KArtDiscPrimTer', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_kartdiscprimvol</obj_name>
  <obj_hashval>3dc1f8c603c05fa09732c46fd93e5f39</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_kartdiscprimvol(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.KArtDiscPrimVol', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_kartpenacter</obj_name>
  <obj_hashval>09ee4e68559d5c97ed319608810fa5a2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_kartpenacter(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.KArtPenAcTer', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_kartpenprimter</obj_name>
  <obj_hashval>84e8bb46f4793d9270d1a37e124376a4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_kartpenprimter(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.KArtPenPrimTer', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_make_manevra_t</obj_name>
  <obj_hashval>fabca4f28dc07ea552c2e67bdc83b87c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_make_manevra_t(acodcontract numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_TMP    RECORD;
  V_REC    RECORD;
  DeLa     numeric;
  DeLaData date;
  sDeLa varchar(40);
BEGIN
  --Florin 21.11.2024 - sinc. Oracle
  --Florin 30.06.2023 - sinc. Oracle (29.06.2023)
  --Florin 28.06.2023 - sinc. Oracle
  DELETE FROM contractt_manevra;
  DELETE FROM tmp_manevra_liste where filtru = 'CODOBIECT' AND FILTRU1 = 'TERMENFIX';
  sDeLa := '30.12.1899';
  for v_rec in (
    select 'CODOBIECT' FILTRU, c1.codobiect VALOARE, 'TERMENFIX' FILTRU1, to_char(ct.termenfix, 'dd.mm.yyyy') stermenfix, ct.termenfix
    from contractt ct
      inner join contract1 c1 on c1.codcontract1 = ct.codcontract1
    where c1.codcontract = aCodContract
        order by codobiect, termenfix)
  LOOP
    insert into tmp_manevra_liste(filtru, filtru1, valoare, valoare1, valoare2)
    values (v_rec.filtru, v_rec.filtru1, v_rec.valoare, sDeLa, v_rec.stermenfix);
    sDeLa := to_char(v_rec.termenfix + 1, 'dd.mm.yyyy');
  END LOOP;

  FOR v_tmp IN (SELECT COALESCE(TipDiscountT, 0) TIPDISCOUNTT, CodContract1
                FROM contract1
                WHERE codcontract = aCodContract and  COALESCE(DiscTCumulat, 0) = 1
               )
  LOOP
    IF  v_tmp.TipDiscountT = 0 THEN
      DeLa := 0;
      FOR v_rec IN (SELECT * FROM contractt WHERE codcontract1 = v_tmp.CodContract1 ORDER BY zile ) LOOP
        INSERT INTO contractt_manevra(CODCONTRACTT, CODCONTRACT1, ZILE, DISCOUNT, VALDISCOUNT, TERMENFIX, PROCVALDOC, ZILEDELA)
        VALUES(v_rec.CODCONTRACTT, v_rec.CODCONTRACT1, v_rec.ZILE, v_rec.DISCOUNT, v_rec.VALDISCOUNT, v_rec.TERMENFIX, v_rec.PROCVALDOC, DELA);

        DeLa := v_rec.ZILE + 1;
      END LOOP;
    ELSE
      DeLaData := to_date('01.01.1899', 'dd.mm.yyyy');
      FOR v_rec IN (SELECT * FROM contractt WHERE codcontract1 = v_tmp.CodContract1 ORDER BY termenfix) LOOP
        INSERT INTO contractt_manevra(CODCONTRACTT, CODCONTRACT1, ZILE, DISCOUNT, VALDISCOUNT, TERMENFIX, PROCVALDOC, TERMENFIXDELA)
        VALUES(v_rec.CODCONTRACTT, v_rec.CODCONTRACT1, v_rec.ZILE, v_rec.DISCOUNT, v_rec.VALDISCOUNT, v_rec.TERMENFIX, v_rec.PROCVALDOC, DeLaData);

        DeLaData := v_rec.TERMENFIX + 1;
      END LOOP;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_nrdoc_i</obj_name>
  <obj_hashval>05941e39db6a23931066abab34e1aefd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_nrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.NRDOC_I', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_preiaprocente</obj_name>
  <obj_hashval>f7dcce73d6881ab3e2d83b61c9efc596</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_preiaprocente()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR v_rec IN (SELECT TMP.coddiscount, DI.PROCENT
                FROM TMP_NCVDISC_MAN tmp INNER JOIN DISCINTERVAL DI ON  DI.CODDISCOUNT = tmp.CODDISCOUNT
                WHERE COALESCE(TMP.CANT, 0) &lt;&gt; 0 AND TMP.CANT BETWEEN DI.LIMINF AND DI.LIMSUP
               )
  LOOP
    UPDATE TMP_NCVDISC_MAN SET PROC = V_REC.PROCENT WHERE CODDISCOUNT = V_REC.CODDISCOUNT;
  END LOOP;

  FOR v_rec IN (SELECT TMP.coddiscount, DI.PROCENT
                FROM TMP_NCVDISC_MAN tmp INNER JOIN DISCINTERVAL DI ON  DI.CODDISCOUNT = tmp.CODDISCOUNT
                WHERE COALESCE(TMP.VALOARE, 0) &lt;&gt; 0 AND TMP.VALOARE BETWEEN DI.LIMINF AND DI.LIMSUP
               )
  LOOP
    UPDATE TMP_NCVDISC_MAN SET PROC = V_REC.PROCENT WHERE CODDISCOUNT = V_REC.CODDISCOUNT;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_rupe</obj_name>
  <obj_hashval>ee37aa0ead272542728a586dc8be1510</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_rupe(acodncfact numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_rec record;
  v_tmp record;
  v_c record;
  aCount NUMERIC(10);
  aVal NUMERIC(20,7);
BEGIN
  --Florin 27.06.2024 - sinc. Oracle
  --Florin 04.01.2024 - sinc. Oracle
  --Florin 12.10.2023 - sinc. Oracle
  --Florin 11.09.2023 - sinc. Oracle
  for v_rec in (select f.codncredit, coalesce(f.coddoc, i1.codies) coddoc, f.coddoc1
                from notecreditfact f
                     inner join notecredit nc on nc.codncredit = f.codncredit
                     left join iesiri1 i1 on f.coddoc1 = i1.codies1
                where codncfact = aCodNCFact and nc.tipdoc = 58) LOOP
    if v_rec.coddoc1 &gt; 0 THEN
      PERFORM pkg_notecredit_UpdateCentralizare(-v_rec.coddoc, v_rec.codncredit, v_rec.coddoc1);
      DELETE FROM notecreditfact where coddoc1  = v_rec.coddoc1;
    ELSE
      PERFORM pkg_notecredit_UpdateCentralizare(-v_rec.coddoc, v_rec.codncredit);
      delete FROM notecreditfact where coddoc = v_rec.coddoc;
    END IF;
  END LOOP;
  for v_rec in (select f.codncredit, coalesce(f.coddoc, i1.codintr) coddoc, f.coddoc1
                from notecreditfact f
                     inner join notecredit nc on nc.codncredit = f.codncredit
                     left join intrari1 i1 on f.coddoc1 = i1.codintr1
                where codncfact = aCodNCFact and nc.tipdoc = 59) LOOP
    if v_rec.coddoc1 &gt; 0 THEN
      PERFORM pkg_notecredit_UpdateCentralizare(-v_rec.coddoc, v_rec.codncredit, v_rec.coddoc1);
      DELETE FROM notecreditfact where coddoc1  = v_rec.coddoc1;
    ELSE
      PERFORM pkg_notecredit_UpdateCentralizare(-v_rec.coddoc, v_rec.codncredit);
      delete FROM notecreditfact where coddoc = v_rec.coddoc;
    END IF;
  end loop;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_setcarnetdoc_i</obj_name>
  <obj_hashval>1be9a1c377528ee8272635229b7106d9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_setcarnetdoc_i(acarnetdoc_i numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOTECREDIT.CARNETDOC_I',to_char(aCARNETDOC_I,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_setct_monitor</obj_name>
  <obj_hashval>2ecca1e2d52e8eadb2216c01126b5245</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOTECREDIT.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_setkartdiscaccant</obj_name>
  <obj_hashval>c56cffbd1fccf859729cf58aaa35a25c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_setkartdiscaccant(akartdiscaccant numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOTECREDIT.KArtDiscAcCant',aKArtDiscAcCant::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_setkartdiscacter</obj_name>
  <obj_hashval>f0a119af9a25240d1c1db03d95cc46d7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_setkartdiscacter(akartdiscacter character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOTECREDIT.KArtDiscAcTer',aKArtDiscAcTer,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_setkartdiscacter</obj_name>
  <obj_hashval>c122d993795e0696ac92b4ae9a984e92</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_setkartdiscacter(akartdiscacter numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOTECREDIT.KArtDiscAcTer',to_char(aKArtDiscAcTer,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_setkartdiscacvol</obj_name>
  <obj_hashval>fc4a9a907ebda8bb488abc74c495365b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_setkartdiscacvol(akartdiscacvol numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOTECREDIT.KArtDiscAcVol',aKArtDiscAcVol::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_setkartdiscoffinvoicec</obj_name>
  <obj_hashval>3d6aa2faece784b0a30ce51526720e9c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_setkartdiscoffinvoicec(akartdiscoffinvoicec numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOTECREDIT.KArtDiscOffInvoiceC',aKArtDiscOffInvoiceC::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_setkartdiscoffinvoicef</obj_name>
  <obj_hashval>017d0c8633a75d76b76a500bf757c1b5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_setkartdiscoffinvoicef(akartdiscoffinvoicef numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOTECREDIT.KArtDiscOffInvoiceF',aKArtDiscOffInvoiceF::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_setkartdiscprimcant</obj_name>
  <obj_hashval>24b7604d1d7084be0015f3f450eba977</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_setkartdiscprimcant(akartdiscprimcant numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOTECREDIT.KArtDiscPrimCant',aKArtDiscPrimCant::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_setkartpenacter</obj_name>
  <obj_hashval>ef9a8eb9805fe954c3c6386b91c6eac9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_setkartpenacter(akartpenacter numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOTECREDIT.KArtPenAcTer',aKArtPenAcTer::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_setkartpenprimter</obj_name>
  <obj_hashval>179c7d7ffa2b0d8ca5fce896695f3a39</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_setkartpenprimter(akartpenprimter numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOTECREDIT.KArtPenPrimTer',aKArtPenPrimTer::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_setnrdoc_i</obj_name>
  <obj_hashval>95290a2439de39c9bc4c37de2316332e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_setnrdoc_i(anrdoc numeric, acarnet numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOTECREDIT.CARNETDOC_I',ACARNET::varchar,false);
perform set_config('PKG_NOTECREDIT.NRDOC_I',ANRDOC::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_settnccantitate</obj_name>
  <obj_hashval>9270d1918f5237aee4291475afa30dfd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_settnccantitate(atnccantitate numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOTECREDIT.tncCantitate',atncCantitate::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_settncpenalizari</obj_name>
  <obj_hashval>9594b32c265ab7de994c2308fdf473a2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_settncpenalizari(atncpenalizari numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOTECREDIT.tncPenalizari',atncPenalizari::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_settncprovizioane</obj_name>
  <obj_hashval>f28e5977a687662d1f31865e1deae881</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_settncprovizioane(atncprovizioane numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOTECREDIT.tncProvizioane',atncProvizioane::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_settnctermen</obj_name>
  <obj_hashval>bb4e082a555282705204cc45664ef2cc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_settnctermen(atnctermen numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOTECREDIT.tncTermen',atncTermen::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_settncvolum</obj_name>
  <obj_hashval>482be347566e980187a3b87542f010af</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_settncvolum(atncvolum numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOTECREDIT.tncVolum',atncVolum::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_sp_deleterecord</obj_name>
  <obj_hashval>f411fdbab3c671510d307c49f2e39fa4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  V_REC          RECORD;
  V_REC_JURN_SUB RECORD;
  vTipDoc        numeric;
  ACARNETDOC     numeric;
  ANRDOC         numeric;
  aCodSubunit    numeric;
  aDataDoc       date;
  aDoc           varchar;
begin
  --Florin 01.06.2023 - monitor
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_notecredit_setct_monitor('MON_47');
  perform set_config('PKG_NOTECREDIT.tncTermen'      , '1', false);
  perform set_config('PKG_NOTECREDIT.tncVolum'       , '2', false);
  perform set_config('PKG_NOTECREDIT.tncCantitate'   , '3', false);
  perform set_config('PKG_NOTECREDIT.tncCadouri'     , '4', false);
  perform set_config('PKG_NOTECREDIT.tncProvizioane' , '5', false);
  perform set_config('PKG_NOTECREDIT.tncPenalizari'  , '6', false);

  perform PKG_GLOBALS_MarkDirtyJurnal();
  perform PKG_NOTECREDIT_SP_LOCKRECORD(RecId);

  select
    TipDoc,
    CarnetDoc,
    NrDoc,
    Subunitatea,
    to_date(to_char(DataCreare, 'dd.mm.yyyy'), 'dd.mm.yyyy'),
    coalesce(PREFIXDOC, '') || coalesce(NRDOC::varchar , '') || '/' || coalesce(to_char(DATACREARE, 'dd.mm.yyyy'),  '')
  into
    vTipDoc,
    ACARNETDOC,
    ANRDOC,
    aCodSubunit,
    aDataDoc,
    aDoc
  FROM notecredit WHERE CodNCredit = RecId;

  if (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT
      FROM   PKG_USERFIRME_ValidPostLog(null, current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_NOTECREDIT.CT_MONITOR', true)))
  then
    perform pkg_userfirme_postlogcucommit('NOTECREDIT', current_setting('PKG_GLOBALS.USERNAME', true), 'S', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true),
                                          aCodSubunit, aDataDoc, aDoc, null, current_setting('PKG_GLOBALS.EXE_VERSION', true));
  end if;

  DELETE FROM NOTECREDIT1    WHERE CodNCredit = RecId;
  DELETE FROM NOTECREDIT     WHERE CodNCredit = RecId;
  DELETE FROM NOTECREDITFACT WHERE CodNCredit = RecId;

  for V_REC in (SELECT * FROM JURNAL WHERE CODDOC = RecID and TIPDOC = vTipDoc ) loop
    UPDATE NCONTRUL
    set
      RULAJCD  = RULAJCD  - V_REC.VALOARE,
      RULAJVCD = RULAJVCD - V_REC.VALOAREV
    where
      CODCONT  = V_REC.CONTD
      and AN   = current_setting('PKG_GLOBALS.ANLUCRU'  , true)::numeric
      and LUNA = current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric ;

    for V_REC_JURN_SUB in (SELECT * FROM NCONTRUL WHERE CODCONT = V_REC.CONTD and AN = V_REC.AN and LUNA = V_REC.LUNA ) loop
      UPDATE NCONTRULSUB
      set
        RULAJCD  = RULAJCD  - V_REC.VALOARE,
        RULAJVCD = RULAJVCD - V_REC.VALOAREV
      where
        CODCONTRUL = V_REC_JURN_SUB.CODCONTRUL
        and SUBUNITATEA = V_REC.SUBUNITATEA ;
    end loop;

    UPDATE NCONTRUL
    set
      RULAJCC  = RULAJCC  - V_REC.VALOARE,
      RULAJVCC = RULAJVCC - V_REC.VALOAREV
    where
      CODCONT = V_REC.CONTC
      and AN = current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric
      and LUNA = current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric ;

    for V_REC_JURN_SUB in (SELECT * FROM NCONTRUL WHERE CODCONT = V_REC.CONTC and AN = V_REC.AN and LUNA = V_REC.LUNA ) loop
      UPDATE NCONTRULSUB
      set
        RULAJCC  = RULAJCC  - V_REC.VALOARE,
        RULAJVCC = RULAJVCC - V_REC.VALOAREV
      where
        CODCONTRUL = V_REC_JURN_SUB.CODCONTRUL
        and SUBUNITATEA = V_REC.SUBUNITATEA ;
    end loop;
  end loop;

  UPDATE CONTRACT2
  SET
    CODDOC  = null,
    TIPDOC  = null,
    NRDOC   = null,
    DATADOC = null
  WHERE CODDOC = RecID and TIPDOC = vTipDoc ;

  DELETE FROM JURNAL  WHERE CODDOC = RecID and TIPDOC = vTipDoc;
  DELETE FROM JURNAL1 WHERE CODDOC = RecID and TIPDOC = vTipDoc;

  if aCARNETDOC &lt;&gt; 0 then
    perform PKG_CARNETEDOC_RELEASENUMARDOC(aCARNETDOC, aNRDOC);
    perform PKG_CARNETEDOC_COMPACTEAZAINTERVALE(aCARNETDOC);
  end if;

  perform NotifyModif(2, RECID, 'CONTRACT');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_sp_gotorecord_sec</obj_name>
  <obj_hashval>b895ef75b2a9c982691351e427437c66</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_sp_gotorecord_sec(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC            RECORD;
  vDataStart       date;
  vDataStop        date;
  vTipDoc          numeric;
  vCodContract     numeric := 0;
  vCount           numeric;
  vCount1          numeric;
  vCodPart         numeric;
  vTipDiscV        numeric;
  vVolumPeArticole numeric;
  vPretBrutC       numeric;
  vPretBrutV       numeric;
  vTrimestriala    numeric;
  vLuna            numeric;
  vTrimestru       numeric;
  vCurs            NUMERIC(20,7);
BEGIN
  --Florin 17.02.2025 - sinc. Oracle
  --Florin 12.02.2025 - sinc. Oracle
  --Stef 30.01.2024
  DELETE FROM tmp_notecredit_man;
  DELETE FROM tmp_notecreditc_man;
  DELETE FROM tmp_notecreditv_man;
  DELETE FROM tmp_notecreditt_man;
  DELETE FROM tmp_notecreditz_man;
  DELETE FROM tmp_notecreditzc_man;
  DELETE FROM tmp_notecreditp_man;
  DELETE FROM tmp_notecreditfact_man;
  DELETE FROM tmp_centralizarenc_man;

  PERFORM PKG_STOC_GENERARE_FACTURI_MAKE_CONFIG_LUNA();

  perform set_config('PKG_NOTECREDIT.KArtDiscAcTer'      ,to_char(COALESCE( (fnc_GetValConstantaLucru('ArtDiscAcTer'      )), 0),'999999999999999999'),false);
  perform set_config('PKG_NOTECREDIT.KArtDiscAcVol'      ,to_char(COALESCE( (fnc_GetValConstantaLucru('ArtDiscAcVol'      )), 0),'999999999999999999'),false);
  perform set_config('PKG_NOTECREDIT.KArtDiscAcCant'     ,to_char(COALESCE( (fnc_GetValConstantaLucru('ArtDiscAcCant'     )), 0),'999999999999999999'),false);
  perform set_config('PKG_NOTECREDIT.KArtPenAcTer'       ,to_char(COALESCE( (fnc_GetValConstantaLucru('ArtPenAc'          )), 0),'999999999999999999'),false);
  perform set_config('PKG_NOTECREDIT.KArtDiscOffInvoiceC',to_char(COALESCE( (fnc_GetValConstantaLucru('ArtDiscOffInvoiceC')), 0),'999999999999999999'),false);
  perform set_config('PKG_NOTECREDIT.KArtDiscPrimTer'    ,fnc_GetValConstantaLucru('ArtDiscPrimTer'    ),false);
  perform set_config('PKG_NOTECREDIT.KArtDiscPrimVol'    ,to_char(COALESCE( (fnc_GetValConstantaLucru('ArtDiscPrimVol'    )), 0),'999999999999999999'),false);
  perform set_config('PKG_NOTECREDIT.KArtDiscPrimCant'   ,to_char(COALESCE( (fnc_GetValConstantaLucru('ArtDiscPrimCant'   )), 0),'999999999999999999'),false);
  perform set_config('PKG_NOTECREDIT.KArtPenPrimTer'     ,to_char(COALESCE( (fnc_GetValConstantaLucru('ArtPenPrim'        )), 0),'999999999999999999'),false);
  perform set_config('PKG_NOTECREDIT.KArtDiscOffInvoiceF',to_char(COALESCE( (fnc_GetValConstantaLucru('ArtDiscOffInvoiceF')), 0),'999999999999999999'),false);

  IF  RecId &gt; 0 THEN
    INSERT INTO TMP_NOTECREDIT_MAN(CodNCredit, CodContract2, CodPart, TipDoc, Subunitatea, DataStart, DataStop, CODCONTV, CODCONTT, CODCONTC, CODCONTP, DataStartD, DataStopD, DataFact, Contract, An, Luna, TipARticol, Obs, CodContract, CodMoneda, VolumPeArticole, CODCONTZ, PretBrutC, PretBrutV, CodCarnet, TipDiscV, Trimestriala, Corectie, COdNCCorectie, PrefixDoc, CarnetDoc, NrDoc, SeriaDoc, AreCarnetDoc)
    SELECT NC.CodNCredit, NC.CodContract2, NC.CodPart, NC.TipDoc, NC.Subunitatea, NC.Datastart, NC.DataStop,
           nc.CODCONTV, nc.CODCONTT, nc.CODCONTC, nc.CODCONTP, NC.DataStart, NC.DataStop, CURRENT_TIMESTAMP,
           CASE WHEN  COALESCE( NC.CodContract2, COALESCE( NC.CodContract, 0)) = 0 THEN '...fara...'
                ELSE CASE WHEN  COALESCE( NC.CodContract, 0) = 0 THEN C.Nrdoc || '/' || to_char( C.DataStart, 'DD.MM.YYYY') || '-' || to_char( C.DataStop, 'DD.MM.YYYY')
                          ELSE CNC.Nrdoc || '/' || to_char( CNC.DataStart, 'DD.MM.YYYY') || '-' || to_char( CNC.DataStop, 'DD.MM.YYYY')
                     END
           END ,
           NC.An, NC.Luna, NC.TipArticol, NC.Obs,
           CASE WHEN  COALESCE( nc.codcontract2, 0) = 0 THEN NC.CodContract ELSE C.Codcontract END ,
           COALESCE( NC.CodMoneda, C.Moneda), COALESCE( NC.VOLUMPEARTICOLE, 0), nc.CODCONTZ, COALESCE( nc.pretbrutc, 0), COALESCE( nc.pretbrutv, 0), nc.codcarnet,
           CASE WHEN CASE WHEN  COALESCE( NC.CodContract2, 0)=0 THEN COALESCE( NC.CodContract, 0)
                          ELSE  NC.CodContract2
                     END  = 0 THEN CASE WHEN  COALESCE( NC.Volumpearticole, 0) = 0 THEN 3 ELSE 4 END
                ELSE CASE WHEN  COALESCE( NC.CodContract, 0) = 0 THEN COALESCE( C.TIPTARGETV, 0) ELSE COALESCE( CNC.TIPTARGETV, 0) END
           END ,
           COALESCE( NC.Trimestriala, 0), NC.Corectie, NC.CodNCCorectie, NC.PrefixDoc, NC.CarnetDoc, NC.NrDoc, NC.SeriaDoc,
           CASE WHEN  COALESCE( NC.CARNETDOC, 0)=0 THEN 0 ELSE  1 END
    FROM NOTECREDIT NC
        LEFT JOIN CONTRACT2 C2  ON  NC.CODCONTRACT2 = C2.CODCONTRACT2
        LEFT JOIN CONTRACT  C   ON  C2.CODCONTRACT  = C.CODCONTRACT
        LEFT JOIN CONTRACT  CNC ON  CNC.Codcontract = nc.codcontract
    WHERE CodNCredit = RecId;

    SELECT COALESCE( VolumPeArticole, 0) INTO vVolumPeArticole FROM tmp_notecredit_man;
    SELECT COALESCE( Trimestriala, 0)    INTO vTrimestriala    FROM tmp_notecredit_man;
    select coalesce(curs,0) into vCurs from notecredit where codncredit = recid;
    if vCurs = 0 then vCurs := 1; end if;

    IF  vTrimestriala = 1 THEN
      SELECT extract( month FROM datastop) INTO vLuna FROM tmp_notecredit_man;
      vTrimestru := 0;
      IF vLuna IN ( 1,  2,  3) THEN vTrimestru := 1; END IF;
      IF vLuna IN ( 4,  5,  6) THEN vTrimestru := 2; END IF;
      IF vLuna IN ( 7,  8,  9) THEN vTrimestru := 3; END IF;
      IF vLuna IN (10, 11, 12) THEN vTrimestru := 4; END IF;
    END IF;

    SELECT datastart INTO vDataStart FROM tmp_notecredit_man;
    SELECT datastop  INTO vDataStop  FROM tmp_notecredit_man;
    SELECT TipDoc    INTO vTipDoc    FROM tmp_notecredit_man;

    SELECT COALESCE( c.codcontract, 0), COALESCE( nc.codpart, 0), COALESCE( c.tiptargetv, 0)
    INTO vCodContract, vCodPart, vTipDiscV
    FROM notecredit nc LEFT JOIN contract c ON  nc.codcontract = c.codcontract
    WHERE nc.codncredit = RecId;

    SELECT count( *) INTO vCount FROM notecredit1
    WHERE codncredit = recid and  tip = TO_NUMBER((current_setting('PKG_NOTECREDIT.tncProvizioane', true)),'999999999999999999');

    IF  vCount &gt; 0 THEN
      INSERT INTO TMP_NOTECREDITZ_MAN(CodNCredit1, CodNCredit, Valoare, CodObligStins, CodDoc, TipDoc, CodObligStingator, Obs, ValDif, Valoareold, CODNCREDIT1ORIG, CODDISCOUNT, DOC,
      NRDOC, DATADOC, MONEDA, SEDIU, CURS, VALDOC, VALLEI, DISCOUNT, DENCRITERIU, CREDITAT, DEN_CLASEDISC, CODCLASEDISC, PROCTVA,
      CODANALIZANOD, CODCENTRU)
      SELECT NC1.CodNCredit1, NC1.CodNCredit, NC1.Valoareold, NC1.CODNCREDIT1ORIG, NC1.CODDISCOUNT,I.CodIes, NC1.CodDoc, NC1.TipDoc, NC1.CodObligStingator,
             NC1.Obs, NC1.ValDif, NC1.Valoare, I.PREFIXDOC DOC, I.NRDOC NRDOC, I.DATADOC DATADOC,
             (SELECT wme_result FROM PKG_MONEDE_GET_SIMBOL_MONEDA(NULL, NVL(G.MONEDA,NC.CODMONEDA))) MONEDA,
             A.OBS SEDIU,
             CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END  CURS,
             CASE
               when i.codies is null then nc1.valdoc
               else I.ValDoc - I.TVADOC
             END,
             CASE
               when i.codies is null then nc1.valdoc
               else ROUND((I.ValDoc - I.TVADOC) * (CASE WHEN NVL(GREG.CURS, G.CURS) = 0 then 1 else NVL(GREG.CURS, G.CURS) END), 4)
             END *
             CASE
               when NC.Corectie = 2 and nvl(nc1.coddoc,0) = 0 then NC.Curs
               ELSE 1
             end ValLei,
             0, CD.DENCRITERIU, COALESCE( ALTE.CREDITAT, 0) + COALESCE( ALTELIBERE.CREDITAT, 0),
             CLSDISC.DEN_CLASEDISC, CLSDISC.CODCLASEDISC, COALESCE( nc1.proctva, 24), CODANALIZANOD, CODCENTRU
      FROM NOTECREDIT1 NC1
      INNER JOIN NOTECREDIT                NC      ON  NC.CODNCREDIT = NC1.CODNCREDIT
      LEFT  JOIN IESDISC                   ID      ON  NC1.CODDOC    = ID.CODIESDISC
      LEFT  JOIN DISCOUNT                  D       ON  COALESCE( ID.CODDISCOUNT, NC1.CODDISCOUNT) = D.CODDISCOUNT
      LEFT  JOIN CRITERIIDISC              CD      ON  CD.CODCRITERIU  = D.CODCRITERIU
      LEFT  JOIN IESIRI                    I       ON  I.CODIES        = ID.CodIes AND  NC1.TipDoc = I.TipDoc
      LEFT  JOIN NCLASEDISC                CLSDISC ON  CLSDISC.CODCLASEDISC = CD.CLASA
      LEFT  JOIN GENERAL                   G       ON  I.CODIES        = G.CODDOC AND  I.TipDoc = G.TipDoc
      LEFT  JOIN TMP_CURS_REGULARIZAT_LUNA GREG    ON  GREG.CODGENERAL = G.CODGENERAL
      LEFT  JOIN NAGENDA                   A       ON  A.CODAGENDA     = I.CODLOCATIE
      LEFT  JOIN (SELECT sum(N1.VALOARE) creditat, N1.CODDOC, nvl(n1.proctva,24) proctva
                  FROM NOTECREDIT1 N1 INNER JOIN NOTECREDIT NC ON  NC.CODNCREDIT = N1.CODNCREDIT
                  WHERE N1.Valoare &lt;&gt; 0 AND  NC.TIPDOC = vTipDoc AND  n1.TIP = TO_NUMBER((current_setting('PKG_NOTECREDIT.tncProvizioane', true)),'999999999999999999') AND  N1.CODNCREDIT &lt;&gt; RecId
                     AND NVL(NC.CORECTIE,0) = 0
                     and n1.coddoc &gt; 0
                  group by n1.coddoc, nvl(n1.proctva,24)
                  ) ALTE on alte.coddoc = nc1.coddoc and alte.proctva = nvl(nc1.proctva,24)
      LEFT  JOIN (SELECT sum( NCC1.VALOARE) CREDITAT, nc1.codncredit1, COALESCE( nc1.proctva, 24) PROCTVA
                  FROM NOTECREDIT1 NC1
                      INNER JOIN NOTECREDIT  NC   ON  NC.CODNCREDIT        = NC1.CODNCREDIT
                      INNER JOIN NOTECREDIT1 NCC1 ON  NCC1.CODNCREDIT1ORIG = NC1.CODNCREDIT1
                      INNER JOIN NOTECREDIT  NCC  ON  NCC.CODNCREDIT       = NCC1.CODNCREDIT
                  WHERE COALESCE( nc1.coddoc, 0) = 0 and  NC1.Valoare &lt;&gt; 0 AND  NC.TIPDOC = vTipDoc AND  NC1.TIP = 5 AND  NCC1.CODNCREDIT &lt;&gt; RecId AND  COALESCE( NCC.corectie, 0) = 0 AND  NC.corectie = 2
                  GROUP BY nc1.codncredit1, COALESCE( nc1.proctva, 24)
                 ) AlteLibere ON  altelibere.codncredit1 = nc1.CodNCredit1Orig and  COALESCE( nc1.proctva, 24) = altelibere.proctva
            WHERE NC1.CodNCredit = RecId AND  NC1.Tip = TO_NUMBER((current_setting('PKG_NOTECREDIT.tncProvizioane', true)),'999999999999999999')
            AND not nvl(g.semnificatie,0) in (240, 500, 211, 210);

    IF  vTipDoc = 58 THEN
         for v_rec in (with IProc as (
                    select distinct I1.CodIes,i1.codobiect, PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT, 1) ProcTVA
                    FROM tmp_notecreditz_man ncz
                      inner join iesdisc id on id.codiesdisc = NCZ.CODDOC
                      inner join iesiri i on id.codies = i.codies
                      inner join iesiri1 I1 on i.codies = i1.codies
                      INNER JOIN nartobj obj ON i1.codobiect = obj.codobiect
                      INNER JOIN nart1 art1 ON art1.codarticol = obj.codarticol AND I.AN*12+I.LUNA BETWEEN art1.ALStart AND art1.ALStop
                      INNER JOIN ntva1 tva1 ON tva1.codtva = art1.codtva        AND I.AN*12+I.LUNA BETWEEN tva1.ALStart AND tva1.ALStop
                    ),
                    IProcVal as ( select ProcTva, CodIes, CodObiect, sum(BazaTVA) BazaTVA, cumulat from
                                 (
                                  select distinct IProc.ProcTVA, I.CodIes, ii.codobiect,i1.indexlocal,
                                         i1.PretOrig*i1.cant*
                                         case when ii.cumulat = 1 then 1 else nvl(i1.coefdiscmaj,1) end
                                         -
                                         case
                                           when not i.tipdoc in (16,21) then 0
                                           else i1.PretOrig*i1.cant*
                                                case when ii.cumulat = 1 then 1 else nvl(i1.coefdiscmaj,1) end
                                                *(SELECT wme_result FROM pkg_list_base_utils_get_cota_tva_art(NULL, i1.codobiect, i.an, i.luna))/100
                                         end BazaTVA, 0 cumulat
                                  FROM (select distinct id.codies, 0 codobiect, coalesce(cd.cumulat,0) cumulat
                                        from tmp_notecreditz ncz
                                             inner join iesdisc id on id.codiesdisc = NCZ.CODDOC
                                             inner join discount d on d.coddiscount = id.coddiscount
                                             inner join criteriidisc cd on cd.codcriteriu = d.codcriteriu
                                        where nvl(id.codobiect,0) = 0
                                       ) ii
                                        inner join iesiri i on ii.codies = i.codies
                                        inner join iesiri1 I1 on i.codies = i1.codies
                                        INNER JOIN IProc ON i1.codies = IProc.codies and IProc.codobiect = i1.codobiect
                                 ) a_pg
                                 group by ProcTVA, CodIes, CodObiect
                                 union all
                                 select distinct IProc.ProcTVA, I.CodIes, ii.codobiect,
                                        sum(i1.PretOrig*i1.cant*
                                            case when ii.cumulat = 1 then 1 else nvl(i1.coefdiscmaj,1) end
                                            -
                                            case
                                              when not i.tipdoc in (16,21) then 0
                                              else i1.PretOrig*i1.cant*
                                                   case when ii.cumulat = 1 then 1 else nvl(i1.coefdiscmaj,1) end
                                                   *(SELECT wme_result FROM pkg_list_base_utils_get_cota_tva_art(NULL, i1.codobiect, i.an, i.luna))/100
                                            end) BazaTVA, ii.cumulat
                                  FROM (select distinct id.codies, id.codobiect, coalesce(cd.cumulat,0) cumulat
                                        from tmp_notecreditz ncz
                                             inner join iesdisc id on id.codiesdisc = NCZ.CODDOC
                                             inner join discount d on d.coddiscount = id.coddiscount
                                             inner join criteriidisc cd on cd.codcriteriu = d.codcriteriu
                                        where nvl(id.codobiect,0) &gt; 0
                                       ) ii
                                        inner join iesiri i on ii.codies = i.codies
                                        inner join iesiri1 I1 on i.codies = i1.codies and i1.codobiect = ii.codobiect
                                        INNER JOIN IProc ON i1.codies = IProc.codies and IProc.codobiect = i1.codobiect
                                  group by IProc.ProcTVA, I.CodIes, ii.codobiect, ii.cumulat
                                )
                    select ncz.codncredit1, id.procent*IProcVal.BazaTVA/100 valdisc
                    from tmp_notecreditz_man ncz
                         inner join iesdisc id on id.codiesdisc = NCZ.CODDOC
                         inner JOIN DISCOUNT D ON NVL(ID.CODDISCOUNT,NCz.CODDISCOUNT) = D.CODDISCOUNT
                         inner JOIN CRITERIIDISC CD ON CD.CODCRITERIU = D.CODCRITERIU
                         inner join IProcVal on IProcVal.CodIes = id.COdIes and ncz.proctva = IProcVal.ProcTVA and nvl(id.codobiect,0) = IProcVal.CodObiect and iprocval.cumulat = coalesce(cd.cumulat,0)
                    where id.offinvoice = 2 and ncz.coddoc &gt; 0
                   ) loop
        update tmp_notecreditz set discount = v_Rec.valdisc where codncredit1 = v_rec.codncredit1 and coddoc &gt; 0;
      end loop;
      for v_rec in (select ncz.codncredit1, n1.valoare valdisc, n1.proctva
                    from tmp_notecreditz_man ncz
                         inner join notecredit1 n1 on n1.codncredit1 = ncz.codncredit1orig
                    where nvl(ncz.coddoc,0) = 0
                   ) loop
        update tmp_notecreditz set discount = v_Rec.valdisc where codncredit1 = v_rec.codncredit1 and nvl(coddoc,0) = 0 and proctva = v_rec.proctva;
      end loop;
    else
      for v_rec in (with IProc as (
                    select distinct I1.CodIes1, PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT, 1) ProcTVA
                    FROM tmp_notecreditz_man ncz
                      inner join iesdisc id on id.codiesdisc = NCZ.CODDOC
                      inner join iesiri i on id.codies = i.codies
                      inner join iesiri1 I1 on i.codies = i1.codies
                      INNER JOIN nartobj obj ON i1.codobiect = obj.codobiect
                      INNER JOIN nart1 art1 ON art1.codarticol = obj.codarticol AND I.AN*12+I.LUNA BETWEEN art1.ALStart AND art1.ALStop
                      INNER JOIN ntva1 tva1 ON tva1.codtva = art1.codtva        AND I.AN*12+I.LUNA BETWEEN tva1.ALStart AND tva1.ALStop
                    ),
                    IProcVal as (
                                  select IProc.ProcTVA, I.CodIes,
                                         sum(i1.PretOrig*i1.cant*nvl(i1.coefdiscmaj,1) -
                                             case
                                               when not i.tipdoc in (16,21) then 0
                                               else i1.PretOrig*i1.cant*nvl(i1.coefdiscmaj,1)*(SELECT wme_result FROM pkg_list_base_utils_get_cota_tva_art(NULL, i1.codobiect, i.an, i.luna))/100
                                             end) BazaTVA
                                  FROM tmp_notecreditz ncz
                                       inner join iesdisc id on id.codiesdisc = NCZ.CODDOC
                                       inner join iesiri i on id.codies = i.codies
                                       inner join iesiri1 I1 on i.codies = i1.codies
                                       INNER JOIN IProc ON i1.codies1 = IProc.codies1
                                  group by IProc.ProcTVA, I.CodIes
                                 )
                    select ncz.codncredit1, id.procent*IProcVal.BazaTVA/100 valdisc
                    from tmp_notecreditz_man ncz
                         inner join iesdisc id on id.codiesdisc = NCZ.CODDOC
                         inner join IProcVal on IProcVal.CodIes = id.COdIes and ncz.proctva = IProcVal.ProcTVA
                    where id.offinvoice = 3) loop
        update tmp_notecreditz set discount = v_Rec.valdisc where codncredit1 = v_rec.codncredit1 and coddoc &gt; 0;
      end loop;
      for v_rec in (select ncz.codncredit1, n1.valoare valdisc, n1.proctva
                    from tmp_notecreditz_man ncz
                         inner join notecredit1 n1 on n1.codncredit1 = ncz.codncredit1orig
                    where nvl(ncz.coddoc,0) = 0
                   ) loop
        update tmp_notecreditz_man set discount = v_Rec.valdisc where codncredit1 = v_rec.codncredit1 and nvl(coddoc,0) = 0 and proctva = v_rec.proctva;
      end loop;
    end if;
    update tmp_notecreditz_man set discount = valoare where nvl(coddoc,0) = 0 and nvl(codncredit1orig,0) = 0;
    update tmp_notecreditz_man tmpz
    set
      valoare = valoare + nvl((select sum(nvl(valoare,0) - nvl(valoareold,0)) from notecredit1 where codncredit1orig = tmpz.codncredit1),0);
  end if;


  INSERT INTO tmp_notecreditzc_man(codncredit, valoare, discount, dencriteriu, creditat, den_clasedisc)
  SELECT RecId, sum( valoare), sum( discount), dencriteriu, sum( creditat), den_clasedisc
  FROM tmp_notecreditz_man
  GROUP BY dencriteriu, den_clasedisc;

  SELECT count( *) INTO vCount FROM notecredit1
  WHERE codncredit = recid and  tip = TO_NUMBER((current_setting('PKG_NOTECREDIT.tncVolum', true)),'999999999999999999');

  IF  vCount &gt; 0 THEN
    PERFORM PKG_NOTECREDIT_MAKE_MANEVRA_NC( RecId, False);
    IF  vTipDoc = 58 THEN
      IF  vCodContract &gt; 0 THEN
        IF  vTipDiscV = 0 THEN
          INSERT INTO TMP_NOTECREDITV_MAN(CodNCredit1, CodNCredit, Valoare, CodObligStins, CodDoc, TipDoc, CodObligStingator, Obs, ValDif, Valoareold, DOC,
          NRDOC, DATADOC, MONEDA, SEDIU, CURS, VALDOC_N, VALLEI_N, DISCOUNT_N, VALDOC_B, VALLEI_B, DISCOUNT_B, CODOBIECT, DENUMIRE, CODDOCMASTER, CODCLASEDISC,
          PROCTVA,
          CODANALIZANOD, CODCENTRU)
          with ValAfis as (
                            select codies, sum(valm) valm, sum(valm_b) valm_b from (
                            select I.CodIes,
                            SUM(case when i.tipdoc = 21 then (I1.Cant*i1.pretorig - I1.TVA) * nvl(I1.CoefDiscMaj,1) else i1.cant * i1.pretorig * nvl(I1.CoefDiscMaj,1) end) ValM,
                            SUM(case when i.tipdoc = 21 then I1.Cant*i1.pretorig - I1.TVA else i1.cant * i1.pretorig end) ValM_b
                            FROM notecredit1 nc1
                                 inner join IESIRI I on nc1.coddoc = i.codies and nc1.tipdoc = i.tipdoc
                                 inner join iesiri1 I1 on i.codies = i1.codies
                            where I.DataDoc BETWEEN to_date(vDataStart, 'DD.MM.YYYY') and to_date(vDataStop, 'DD.MM.YYYY')
                              and i1.codobiect &gt; 0
                              and I1.CodObiect not in (current_setting ('PKG_NOTECREDIT.KArtDiscPrimVol', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtDiscPrimCant', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtPenPrimTer', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceF', true) ::numeric)
                         AND INSTR(current_setting ('PKG_NOTECREDIT.KArtDiscPrimTer', true) , TO_CHAR(I1.CODOBIECT)) = 0
                         AND nc1.tip = tncVolum
                              and nc1.codncredit = RecId
                           group by I.CodIes
                           ) a_pg group by codies
                           )
          SELECT NC1.CodNCredit1, NC1.CodNCredit, NC1.Valoare + COALESCE( CORECTII.VALOARE, 0), NC1.CodObligStins,
                 NC1.CodDoc, NC1.TipDoc, NC1.CodObligStingator, NC1.Obs, NC1.ValDif, NC1.Valoare + COALESCE( CORECTII.VALOARE, 0), I.PREFIXDOC DOC, I.NRDOC NRDOC, I.DATADOC DATADOC,
                 (SELECT PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT FROM PKG_MONEDE_GET_SIMBOL_MONEDA(NULL, G.MONEDA)) MONEDA,
                 A.OBS SEDIU,
                 CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END  CURS,
                 ROUND( V.ValM, 4) VALDOC,
                 ROUND( V.ValM * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END , 4) VALLEI,
                 CASE WHEN  vTrimestriala = 1 THEN (SELECT pkg_notecredit_GetDiscVolumTrim.WME_RESULT FROM pkg_notecredit_GetDiscVolumTrim(NULL, I.CodIes, vCodContract, 1, RecID, vTrimestru, 0, vCurs))
                      ELSE (SELECT pkg_notecredit_GetDiscVolum.WME_RESULT FROM pkg_notecredit_GetDiscVolum(NULL, I.CodIes, vCodContract, 1, RecID,0, vCurs))
                 END ,
                 ROUND( V.ValM_b, 4) VALDOC_B,
                 ROUND( V.ValM_b * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END , 4) VALLEI_B,
                 CASE WHEN  vTrimestriala = 1 THEN (SELECT pkg_notecredit_GetDiscVolumTrim.WME_RESULT FROM pkg_notecredit_GetDiscVolumTrim(NULL, I.CodIes, vCodContract, 1, RecID, vTrimestru, 1, vCurs))
                      ELSE (SELECT pkg_notecredit_GetDiscVolum.WME_RESULT FROM pkg_notecredit_GetDiscVolum(NULL, I.CodIes, vCodContract, 1, RecID, 1, vCurs))
                 END ,
                 0, '', I.CODIES, NC1.CODCLASEDISC, COALESCE(NC1.PROCTVA,24), NC1.CODANALIZANOD,
                 NC1.CODCENTRU
          FROM NOTECREDIT1 NC1
          INNER JOIN IESIRI                    I    ON  NC1.Coddoc      = I.CodIes AND  NC1.TipDoc = I.TipDoc
          INNER JOIN VALAFIS                   V    ON  I.CODIES        = V.CODIES
          LEFT  JOIN GENERAL                   G    ON  I.CODIES        = G.CODDOC AND  I.TipDoc = G.TipDoc
          LEFT  JOIN TMP_CURS_REGULARIZAT_LUNA GREG ON  GREG.CODGENERAL = G.CODGENERAL
          LEFT  JOIN NAGENDA                   A    ON  A.CODAGENDA     = I.CODLOCATIE
          LEFT  JOIN (SELECT SUM( COALESCE( N1.VALOARE, 0) - COALESCE( N1.VALOAREOLD, 0)) VALOARE, N1.CODNCREDIT1ORIG
                      FROM NOTECREDIT1 N1 INNER JOIN NOTECREDIT N ON  N1.CODNCREDIT = N.CODNCREDIT
                      WHERE N.CODNCREDIT &lt;&gt; RECID
                      GROUP BY N1.CODNCREDIT1ORIG
                     ) CORECTII ON  CORECTII.CODNCREDIT1ORIG = NC1.CODNCREDIT1
          WHERE NC1.CodNCredit = RecId AND  NC1.Tip = TO_NUMBER((current_setting('PKG_NOTECREDIT.tncVolum', true)),'999999999999999999');
        ELSE
          IF  vTipDiscV = 1 THEN
            INSERT INTO TMP_NOTECREDITV_MAN(CodNCredit1, CodNCredit, Valoare, CodObligStins, CodDoc, TipDoc, CodObligStingator, Obs, ValDif, Valoareold, DOC,
            NRDOC, DATADOC, MONEDA, SEDIU, CURS, VALDOC_N, VALLEI_N, DISCOUNT_N, VALDOC_B, VALLEI_B, DISCOUNT_B, CODOBIECT, DENUMIRE, CODDOCMASTER, CODCLASEDISC,
            PROCTVA, CODANALIZANOD, CODCENTRU)
            with ValAfis as (
                            select codies, sum(valm) valm, sum(valm_b) valm_b from (
                            select I.CodIes, SUM(case when i.tipdoc = 21 then (I1.Cant*i1.pretorig - I1.TVA) * nvl(I1.CoefDiscMaj,1) else i1.cant * i1.pretorig * nvl(I1.CoefDiscMaj,1) end) ValM,
                                   SUM(case when i.tipdoc = 21 then I1.Cant*i1.pretorig - I1.TVA else i1.cant * i1.pretorig end) ValM_b
                            FROM notecredit1 nc1
                                 inner join IESIRI I on nc1.coddoc = i.codies and nc1.tipdoc = i.tipdoc
                                 inner join iesiri1 I1 on i.codies = i1.codies
                                 inner join contract1 c1 on c1.codcontract1 = GetCodContract1(i1.codobiect, i.datadoc, vCodContract)
                            where I.DataDoc BETWEEN to_date(vDataStart, 'DD.MM.YYYY') and to_date(vDataStop, 'DD.MM.YYYY')
                              and i1.codobiect &gt; 0
                              and I1.CodObiect not in (current_setting ('PKG_NOTECREDIT.KArtDiscPrimVol', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtDiscPrimCant', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtPenPrimTer', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceF', true) ::numeric)
                              AND INSTR(current_setting ('PKG_NOTECREDIT.KArtDiscPrimTer', true) , TO_CHAR(I1.CODOBIECT)) = 0
                              AND nc1.tip = tncVolum and c1.codcontract = vCodContract
                              and nc1.codncredit = RecId
                           group by I.CodIes
                           ) a_pg group by codies
                           )
            SELECT NC1.CodNCredit1, NC1.CodNCredit, NC1.Valoare + COALESCE( CORECTII.VALOARE, 0), NC1.CodObligStins,
                   NC1.CodDoc, NC1.TipDoc, NC1.CodObligStingator, NC1.Obs, NC1.ValDif, NC1.Valoare + COALESCE( CORECTII.VALOARE, 0),
                   I.PREFIXDOC DOC, I.NRDOC NRDOC, I.DATADOC DATADOC,
                   (SELECT PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT FROM PKG_MONEDE_GET_SIMBOL_MONEDA(NULL, G.MONEDA)) MONEDA,
                   A.OBS SEDIU,
                   CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END  CURS,
                   ROUND( V.ValM, 4) VALDOC,
                   ROUND( V.ValM * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END , 4) VALLEI,
                   CASE WHEN  vTrimestriala = 1 THEN (SELECT pkg_notecredit_GetDiscVolumTrim.WME_RESULT FROM pkg_notecredit_GetDiscVolumTrim(NULL, I.CodIes, vCodContract, 1, RecId, vTrimestru,0, vCurs))
                        ELSE (SELECT pkg_notecredit_GetDiscVolum.WME_RESULT FROM pkg_notecredit_GetDiscVolum(NULL, I.CodIes, vCodContract, 1, RecId, 0, vCurs))
                   END ,
                   ROUND( V.ValM_b, 4) VALDOC_B,
                   ROUND( V.ValM_b * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END , 4) VALLEI_B,
                   CASE WHEN  vTrimestriala = 1 THEN (SELECT pkg_notecredit_GetDiscVolumTrim.WME_RESULT FROM pkg_notecredit_GetDiscVolumTrim(NULL, I.CodIes, vCodContract, 1, RecId, vTrimestru, 1, vCurs))
                        ELSE (SELECT pkg_notecredit_GetDiscVolum.WME_RESULT FROM pkg_notecredit_GetDiscVolum(NULL, I.CodIes, vCodContract, 1, RecId, 1, vCurs))
                   END ,
                   0, '', I.CODIES, NC1.CODCLASEDISC,
                   COALESCE(NC1.PROCTVA,24),
                   NC1.CODANALIZANOD,
                   NC1.CODCENTRU
            FROM NOTECREDIT1 NC1
            INNER JOIN IESIRI                    I    ON  NC1.Coddoc      = I.CodIes AND  NC1.TipDoc = I.TipDoc
            INNER JOIN VALAFIS                   V    ON  I.CODIES        = V.CODIES
            LEFT  JOIN GENERAL                   G    ON  I.CODIES        = G.CODDOC AND  I.TipDoc = G.TipDoc
            LEFT  JOIN TMP_CURS_REGULARIZAT_LUNA GREG ON  GREG.CODGENERAL = G.CODGENERAL
            LEFT  JOIN NAGENDA                   A    ON  A.CODAGENDA     = I.CODLOCATIE
            LEFT  JOIN (SELECT SUM( COALESCE( N1.VALOARE, 0) - COALESCE( N1.VALOAREOLD, 0)) VALOARE, N1.CODNCREDIT1ORIG
                        FROM NOTECREDIT1 N1 INNER JOIN NOTECREDIT N ON  N1.CODNCREDIT = N.CODNCREDIT
                        WHERE N.CODNCREDIT &lt;&gt; RECID
                        GROUP BY N1.CODNCREDIT1ORIG
                       ) CORECTII ON  CORECTII.CODNCREDIT1ORIG = NC1.CODNCREDIT1
            WHERE NC1.CodNCredit = RecId AND  NC1.Tip = TO_NUMBER((current_setting('PKG_NOTECREDIT.tncVolum', true)),'999999999999999999');
          ELSE
            INSERT INTO TMP_NOTECREDITV_MAN(CodNCredit1, CodNCredit, Valoare, CodObligStins, CodDoc, TipDoc, CodObligStingator, Obs, ValDif, Valoareold, DOC,
            NRDOC, DATADOC, MONEDA, SEDIU, CURS, VALDOC_N, VALLEI_N, DISCOUNT_N, VALDOC_B, VALLEI_B, DISCOUNT_B, CODOBIECT, DENUMIRE, CODDOCMASTER, CODCLASEDISC,
            CODINTERN, PROCTVA, CODANALIZANOD, CODCENTRU)
            with ValAfis as (
                              select codies1, valm, valm_b from (
                              select I1.CodIes1, case when nvl(c1.tipdiscount,0) = 0 then case when i.tipdoc = 21 then (I1.Cant*i1.pretorig - I1.TVA) * nvl(I1.CoefDiscMaj,1) else i1.cant * i1.pretorig * nvl(I1.CoefDiscMaj,1) end else I1.Cant * C1.pret end ValM,
                                     case when nvl(c1.tipdiscount,0) = 0 then case when i.tipdoc = 21 then I1.Cant*i1.pretorig - I1.TVA else i1.cant * i1.pretorig end else I1.Cant * C1.pret end ValM_b
                              FROM notecredit1 nc1
                                   inner join IESIRI I on nc1.tipdoc = i.tipdoc
                                   inner join iesiri1 I1 on i.codies = i1.codies and nc1.coddoc = i1.codies1
                                   inner join contract1 c1 on c1.codcontract1 = GetCodContract1(i1.codobiect, i.datadoc, vCodContract)
                              where I.DataDoc BETWEEN to_date(vDataStart, 'DD.MM.YYYY') and to_date(vDataStop, 'DD.MM.YYYY')
                                and i1.codobiect &gt; 0
                                and I1.CodObiect not in (current_setting ('PKG_NOTECREDIT.KArtDiscPrimVol', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtDiscPrimCant', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtPenPrimTer', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceF', true) ::numeric)
                                AND INSTR(current_setting ('PKG_NOTECREDIT.KArtDiscPrimTer', true) , TO_CHAR(I1.CODOBIECT)) = 0
                                AND nc1.tip = tncVolum and c1.codcontract = vCodContract
                                and nc1.codncredit = RecId
                             ) a_pg
                             )
            SELECT NC1.CodNCredit1, NC1.CodNCredit, NC1.Valoare + COALESCE( CORECTII.VALOARE, 0), NC1.CodObligStins,
                   NC1.CodDoc, NC1.TipDoc, NC1.CodObligStingator, NC1.Obs, NC1.ValDif, NC1.Valoare + COALESCE( CORECTII.VALOARE, 0),
                   I.PREFIXDOC DOC, I.NRDOC NRDOC, I.DATADOC DATADOC,
                   (SELECT PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT FROM PKG_MONEDE_GET_SIMBOL_MONEDA(NULL, G.MONEDA)) MONEDA,
                   A.OBS SEDIU,
                   CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END  CURS,
                   ROUND( V.ValM, 4) VALDOC,
                   ROUND( V.ValM * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END , 4) VALLEI,
                   (SELECT pkg_notecredit_GetDiscVolum.WME_RESULT FROM pkg_notecredit_GetDiscVolum(NULL, I1.CodIes1, vCodContract, 1, RecId, 0, vCurs)),
                   ROUND( V.ValM_b, 4) VALDOC_B,
                   ROUND( V.ValM_b * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END , 4) VALLEI_B,
                   (SELECT pkg_notecredit_GetDiscVolum.WME_RESULT FROM pkg_notecredit_GetDiscVolum(NULL, I1.CodIes1, vCodContract, 1, RecId, 1, vCurs)),
                   I1.CodObiect, OBJ.Denumire, I.CODIES, NC1.CODCLASEDISC, OBJ.CODINTERN,
                   COALESCE(NC1.PROCTVA,24),
                   NC1.CODANALIZANOD,
                   NC1.CODCENTRU
            FROM NOTECREDIT1 NC1
            INNER JOIN IESIRI                    I    ON  NC1.TipDoc      = I.TipDoc
            INNER JOIN IESIRI1                   I1   ON  NC1.Coddoc      = I1.CodIes1 AND  I.CodIes = I1.CodIes
            INNER JOIN VALAFIS                   V    ON  V.CODIES1       = I1.CODIES1
            INNER JOIN NARTOBJ                   OBJ  ON  I1.CodObiect    = OBJ.CodObiect
            LEFT  JOIN GENERAL                   G    ON  I.CODIES        = G.CODDOC AND  I.TipDoc = G.TipDoc
            LEFT  JOIN TMP_CURS_REGULARIZAT_LUNA GREG ON  GREG.CODGENERAL = G.CODGENERAL
            LEFT  JOIN NAGENDA                   A    ON  A.CODAGENDA     = I.CODLOCATIE
            LEFT  JOIN (SELECT SUM( COALESCE( N1.VALOARE, 0) - COALESCE( N1.VALOAREOLD, 0)) VALOARE, N1.CODNCREDIT1ORIG
                        FROM NOTECREDIT1 N1 INNER JOIN NOTECREDIT N ON  N1.CODNCREDIT = N.CODNCREDIT
                        WHERE N.CODNCREDIT &lt;&gt; RECID
                        GROUP BY N1.CODNCREDIT1ORIG
                       ) CORECTII ON  CORECTII.CODNCREDIT1ORIG = NC1.CODNCREDIT1
            WHERE NC1.CodNCredit = RecId AND  NC1.Tip = TO_NUMBER((current_setting('PKG_NOTECREDIT.tncVolum', true)),'999999999999999999');
          END IF;
        END IF;
      ELSE
        IF  vVolumPeArticole = 0 THEN
          INSERT INTO TMP_NOTECREDITV_MAN(CodNCredit1, CodNCredit, Valoare, CodObligStins, CodDoc, TipDoc, CodObligStingator, Obs, ValDif, Valoareold, DOC, NRDOC,
          DATADOC, MONEDA, SEDIU, CURS, VALDOC_N, VALLEI_N, DISCOUNT_N, VALDOC_B, VALLEI_B, DISCOUNT_B, CODOBIECT, Denumire, CODDOCMASTER, CODCLASEDISC,
          PROCTVA, CODANALIZANOD, CODCENTRU)
          with ValAfis as (
                            select codies, sum(valm) valm, sum(valm_b) valm_b from (
                            select I.CodIes, SUM(case when i.tipdoc = 21 then (I1.Cant*i1.pretorig - I1.TVA) * nvl(I1.CoefDiscMaj,1) else i1.cant * i1.pretorig * nvl(I1.CoefDiscMaj,1) end) ValM,
                                   SUM(case when i.tipdoc = 21 then I1.Cant*i1.pretorig - I1.TVA else i1.cant * i1.pretorig end) ValM_b
                            FROM notecredit1 nc1
                                 inner join IESIRI I on nc1.coddoc = i.codies and nc1.tipdoc = i.tipdoc
                                 inner join iesiri1 I1 on i.codies = i1.codies
                            where I.DataDoc BETWEEN to_date(vDataStart, 'DD.MM.YYYY') and to_date(vDataStop, 'DD.MM.YYYY')
                              and i1.codobiect &gt; 0
                              and I1.CodObiect not in (current_setting ('PKG_NOTECREDIT.KArtDiscPrimVol', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtDiscPrimCant', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtPenPrimTer', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceF', true) ::numeric)
                              AND INSTR(current_setting ('PKG_NOTECREDIT.KArtDiscPrimTer', true) , TO_CHAR(I1.CODOBIECT)) = 0
                              AND nc1.tip = tncVolum
                              and nc1.codncredit = RecId
                           group by I.CodIes
                           ) a_pg group by codies
                           )
          SELECT NC1.CodNCredit1, NC1.CodNCredit, NC1.Valoare + COALESCE( CORECTII.VALOARE, 0), NC1.CodObligStins,
                 NC1.CodDoc, NC1.TipDoc, NC1.CodObligStingator, NC1.Obs, NC1.ValDif, NC1.Valoare + COALESCE( CORECTII.VALOARE, 0),
                 I.PREFIXDOC DOC, I.NRDOC NRDOC, I.DATADOC DATADOC,
                 (SELECT PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT FROM PKG_MONEDE_GET_SIMBOL_MONEDA(NULL, G.MONEDA)) MONEDA,
                 A.OBS SEDIU,
                 CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END  CURS,
                 ROUND( V.ValM, 4) VALDOC,
                 ROUND( V.ValM * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END , 4) VALLEI,
                 (SELECT pkg_notecredit_GetDiscVolum.WME_RESULT FROM pkg_notecredit_GetDiscVolum(NULL, I.CodIes, vCodContract, 1, RecId,0, vCurs)),
                 ROUND( V.ValM_b, 4) VALDOC_B,
                 ROUND( V.ValM_b * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END , 4) VALLEI_B,
                 (SELECT pkg_notecredit_GetDiscVolum.WME_RESULT FROM pkg_notecredit_GetDiscVolum(NULL, I.CodIes, vCodContract, 1, RecId, 1, vCurs)),
                 0, '', I.CODIES, NC1.CODCLASEDISC,
                 COALESCE(NC1.PROCTVA,24),
                 NC1.CODANALIZANOD,
                 NC1.CODCENTRU
          FROM NOTECREDIT1 NC1
          INNER JOIN IESIRI                    I    ON  NC1.Coddoc      = I.CodIes AND  NC1.TipDoc = I.TipDoc
          INNER JOIN VALAFIS                   V    ON  V.CODIES        = I.CODIES
          LEFT  JOIN GENERAL                   G    ON  I.CODIES        = G.CODDOC AND  I.TipDoc = G.TipDoc
          LEFT  JOIN TMP_CURS_REGULARIZAT_LUNA GREG ON  GREG.CODGENERAL = G.CODGENERAL
          LEFT  JOIN NAGENDA                   A    ON  A.CODAGENDA     = I.CODLOCATIE
          LEFT  JOIN (SELECT SUM( COALESCE( N1.VALOARE, 0) - COALESCE( N1.VALOAREOLD, 0)) VALOARE, N1.CODNCREDIT1ORIG
                      FROM NOTECREDIT1 N1 INNER JOIN NOTECREDIT N ON  N1.CODNCREDIT = N.CODNCREDIT
                      WHERE N.CODNCREDIT &lt;&gt; RECID
                      GROUP BY N1.CODNCREDIT1ORIG
                     ) CORECTII ON  CORECTII.CODNCREDIT1ORIG = NC1.CODNCREDIT1
          WHERE NC1.CodNCredit = RecId AND  NC1.Tip = TO_NUMBER((current_setting('PKG_NOTECREDIT.tncVolum', true)),'999999999999999999');
        ELSE
          INSERT INTO TMP_NOTECREDITV_MAN(CodNCredit1, CodNCredit, Valoare, CodObligStins, CodDoc, TipDoc, CodObligStingator, Obs, ValDif, Valoareold, DOC, NRDOC,
          DATADOC, MONEDA, SEDIU, CURS, VALDOC_N, VALLEI_N, DISCOUNT_N, VALDOC_B, VALLEI_B, DISCOUNT_B, CODOBIECT, Denumire, CODDOCMASTER, CODCLASEDISC, CODINTERN,
          PROCTVA, CODANALIZANOD, CODCENTRU)
          with ValAfis as (
                            select codies1, sum(valm) valm, sum(valm_b) valm_b from (
                            select I1.CodIes1,
                            SUM(
                              case when i.tipdoc = 21 then (I1.Cant*i1.pretorig - I1.TVA) * nvl(I1.CoefDiscMaj,1) else i1.cant * i1.pretorig * nvl(I1.CoefDiscMaj,1) end
                            ) ValM,
                            SUM(
                              case when i.tipdoc = 21 then I1.Cant*i1.pretorig - I1.TVA else i1.cant * i1.pretorig end
                            ) ValM_b
                            FROM notecredit1 nc1
                                 inner join IESIRI I on nc1.tipdoc = i.tipdoc
                                 inner join iesiri1 I1 on i.codies = i1.codies and nc1.coddoc = i1.codies1
                            where I.DataDoc BETWEEN to_date(vDataStart, 'DD.MM.YYYY') and to_date(vDataStop, 'DD.MM.YYYY')
                              and i1.codobiect &gt; 0
                              and I1.CodObiect not in (current_setting ('PKG_NOTECREDIT.KArtDiscPrimVol', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtDiscPrimCant', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtPenPrimTer', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceF', true) ::numeric)
                              AND INSTR(current_setting ('PKG_NOTECREDIT.KArtDiscPrimTer', true) , TO_CHAR(I1.CODOBIECT)) = 0
                              AND nc1.tip = tncVolum
                              and nc1.codncredit = RecId
                           group by I1.CodIes1
                           ) a_pg group by codies1
                           )
          SELECT NC1.CodNCredit1, NC1.CodNCredit, NC1.Valoare + COALESCE( CORECTII.VALOARE, 0), NC1.CodObligStins,
                 NC1.CodDoc, NC1.TipDoc, NC1.CodObligStingator, NC1.Obs, NC1.ValDif, NC1.Valoare + COALESCE( CORECTII.VALOARE, 0),
                 I.PREFIXDOC DOC, I.NRDOC NRDOC, I.DATADOC DATADOC,
                 (SELECT PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT FROM PKG_MONEDE_GET_SIMBOL_MONEDA(NULL, G.MONEDA)) MONEDA,
                 A.OBS SEDIU,
                 CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END  CURS,
                 ROUND( V.ValM, 4) VALDOC,
                 ROUND( V.ValM * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END , 4) VALLEI,
                 (SELECT pkg_notecredit_GetDiscVolum.WME_RESULT FROM pkg_notecredit_GetDiscVolum(NULL, I1.CodIes1, vCodContract, 1, RecId, 0, vCurs)),
                 ROUND( V.ValM_b, 4) VALDOC_B,
                 ROUND( V.ValM_b * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END , 4) VALLEI_B,
                 (SELECT pkg_notecredit_GetDiscVolum.WME_RESULT FROM pkg_notecredit_GetDiscVolum(NULL, I1.CodIes1, vCodContract, 1, RecId, 1, vCurs)),
                 i1.codobiect, obj.denumire, I.CODIES, NC1.CODCLASEDISC, OBJ.CODINTERN,
                 COALESCE(NC1.PROCTVA,24),
                 NC1.CODANALIZANOD,
                 NC1.CODCENTRU
          FROM NOTECREDIT1 NC1
          INNER JOIN IESIRI1                   I1   ON  NC1.Coddoc      = I1.CodIes1
          INNER JOIN IESIRI                    I    ON  I1.CODIES       = I.CODIES AND  NC1.TipDoc = I.TipDoc
          INNER JOIN VALAFIS                   V    ON  V.CODIES1       = I1.CODIES1
          INNER JOIN NARTOBJ                   OBJ  ON  OBJ.CODOBIECT   = I1.CODOBIECT
          LEFT  JOIN GENERAL                   G    ON  I.CODIES        = G.CODDOC AND  I.TipDoc = G.TipDoc
          LEFT  JOIN TMP_CURS_REGULARIZAT_LUNA GREG ON  GREG.CODGENERAL = G.CODGENERAL
          LEFT  JOIN NAGENDA                   A    ON  A.CODAGENDA     = I.CODLOCATIE
          LEFT  JOIN (SELECT SUM( COALESCE( N1.VALOARE, 0) - COALESCE( N1.VALOAREOLD, 0)) VALOARE, N1.CODNCREDIT1ORIG
                      FROM NOTECREDIT1 N1 INNER JOIN NOTECREDIT N ON  N1.CODNCREDIT = N.CODNCREDIT
                      WHERE N.CODNCREDIT &lt;&gt; RECID
                      GROUP BY N1.CODNCREDIT1ORIG
                     ) CORECTII ON  CORECTII.CODNCREDIT1ORIG = NC1.CODNCREDIT1
          WHERE NC1.CodNCredit = RecId AND  NC1.Tip = TO_NUMBER((current_setting('PKG_NOTECREDIT.tncVolum', true)),'999999999999999999');
        END IF;
      END IF;
    ELSE
      IF  vCodContract &gt; 0 THEN
        IF  vTipDiscV = 0 THEN
          INSERT INTO TMP_NOTECREDITV_MAN(CodNCredit1, CodNCredit, Valoare, CodObligStins, CodDoc, TipDoc, CodObligStingator, Obs, ValDif, Valoareold, DOC, NRDOC,
          DATADOC, MONEDA, SEDIU, CURS, VALDOC_N, VALLEI_N, DISCOUNT_N, VALDOC_B, VALLEI_B, DISCOUNT_B, CODOBIECT, DENUMIRE, CODDOCMASTER, CODCLASEDISC,
          PROCTVA, CODANALIZANOD, CODCENTRU)
          with ValAfis as ( select codintr, sum(valm) valm, sum(valm_b) valm_b from (
                            select I.CodIntr, SUM(I1.Cant*I1.PretOrig*I1.Coefdiscmaj) ValM,
                                   SUM(I1.Cant*I1.PretOrig) ValM_b
                            FROM notecredit1 nc1
                                 inner join INTRARI I on nc1.coddoc = i.codintr and nc1.tipdoc = i.tipdoc
                                 inner join intrari1 I1 on i.codintr = i1.codintr
                            where I.DataDoc BETWEEN to_date(vDataStart, 'DD.MM.YYYY') and to_date(vDataStop, 'DD.MM.YYYY')
                            and i1.codobiect &gt; 0
                              and I1.CodObiect not in (current_setting ('PKG_NOTECREDIT.KArtDiscPrimVol', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtDiscPrimCant', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtPenPrimTer', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceF', true) ::numeric)
                              AND INSTR(current_setting ('PKG_NOTECREDIT.KArtDiscPrimTer', true) , TO_CHAR(I1.CODOBIECT)) = 0
                              AND nc1.tip = tncVolum
                              and nc1.codncredit = RecId
                           group by I.CodIntr
                           ) a_pg group by codintr )
          SELECT NC1.CodNCredit1, NC1.CodNCredit, NC1.Valoare + COALESCE( CORECTII.VALOARE, 0), NC1.CodObligStins,
                 NC1.CodDoc, NC1.TipDoc, NC1.CodObligStingator, NC1.Obs, NC1.ValDif, NC1.Valoare + COALESCE( CORECTII.VALOARE, 0),
                 I.PREFIXDOC DOC, I.NRDOC NRDOC, I.DATADOC DATADOC,
                 (SELECT PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT FROM PKG_MONEDE_GET_SIMBOL_MONEDA(NULL, G.MONEDA)) MONEDA,
                 A.OBS SEDIU,
                 CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END  CURS,
                 ROUND( V.ValM, 4) VALDOC,
                 ROUND( V.ValM * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END , 4) VALLEI,
                 (SELECT pkg_notecredit_GetDiscVolum.WME_RESULT FROM pkg_notecredit_GetDiscVolum(NULL, I.CodIntr, vCodContract, 2, RecId,0, vCurs)),
                 ROUND( V.ValM_b, 4) VALDOC_B,
                 ROUND( V.ValM_b * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END , 4) VALLEI_B,
                 (SELECT pkg_notecredit_GetDiscVolum.WME_RESULT FROM pkg_notecredit_GetDiscVolum(NULL, I.CodIntr, vCodContract, 2, RecId, 1, vCurs)),
                 0, '', I.CODINTR, NC1.CODCLASEDISC,
                 COALESCE(NC1.PROCTVA,24),
                 NC1.CODANALIZANOD,
                 NC1.CODCENTRU
          FROM NOTECREDIT1 NC1
          INNER JOIN INTRARI                   I    ON  NC1.Coddoc      = I.CodIntr AND  NC1.TipDoc = I.TipDoc
          INNER JOIN VALAFIS                   V    ON  I.CODINTR       = V.CODINTR
          LEFT  JOIN GENERAL                   G    ON  I.CODINTR       = G.CODDOC AND  I.TipDoc = G.TipDoc
          LEFT  JOIN TMP_CURS_REGULARIZAT_LUNA GREG ON  GREG.CODGENERAL = G.CODGENERAL
          LEFT  JOIN NAGENDA                   A    ON  A.CODAGENDA     = I.CODLOCATIE
          LEFT  JOIN (SELECT SUM( COALESCE( N1.VALOARE, 0) - COALESCE( N1.VALOAREOLD, 0)) VALOARE, N1.CODNCREDIT1ORIG
                      FROM NOTECREDIT1 N1 INNER JOIN NOTECREDIT N ON  N1.CODNCREDIT = N.CODNCREDIT
                      WHERE N.CODNCREDIT &lt;&gt; RECID
                      GROUP BY N1.CODNCREDIT1ORIG
                     ) CORECTII ON  CORECTII.CODNCREDIT1ORIG = NC1.CODNCREDIT1
          WHERE NC1.CodNCredit = RecId AND  NC1.Tip = TO_NUMBER((current_setting('PKG_NOTECREDIT.tncVolum', true)),'999999999999999999');
        ELSE
          IF  vTipDiscV = 1 THEN
            INSERT INTO TMP_NOTECREDITV_MAN(CodNCredit1, CodNCredit, Valoare, CodObligStins, CodDoc, TipDoc, CodObligStingator, Obs, ValDif, Valoareold, DOC,
            NRDOC, DATADOC, MONEDA, SEDIU, CURS, VALDOC_N, VALLEI_N, DISCOUNT_N, VALDOC_B, VALLEI_B, DISCOUNT_B, CODOBIECT, DENUMIRE, CODDOCMASTER, CODCLASEDISC,
            PROCTVA, CODANALIZANOD, CODCENTRU)
            with ValAfis as ( select codintr, sum(valm) valm, sum(valm_b) valm_b from (
                            select I.CodIntr, SUM(I1.Cant*I1.PretOrig*I1.Coefdiscmaj) ValM,
                                   SUM(I1.Cant*I1.PretOrig) ValM_b
                            FROM notecredit1 nc1
                                 inner join INTRARI I on nc1.coddoc = i.codintr and nc1.tipdoc = i.tipdoc
                                 inner join intrari1 I1 on i.codintr = i1.codintr
                                 inner join contract1 c1 on c1.codcontract1 = GetCodContract1(i1.codobiect, i.datadoc, vCodContract)
                            where I.DataDoc BETWEEN to_date(vDataStart, 'DD.MM.YYYY') and to_date(vDataStop, 'DD.MM.YYYY')
                            and i1.codobiect &gt; 0
                              and I1.CodObiect not in (current_setting ('PKG_NOTECREDIT.KArtDiscPrimVol', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtDiscPrimCant', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtPenPrimTer', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceF', true) ::numeric)
                              AND INSTR(current_setting ('PKG_NOTECREDIT.KArtDiscPrimTer', true) , TO_CHAR(I1.CODOBIECT)) = 0
                              AND nc1.tip = tncVolum and c1.codcontract = vCodContract
                              and nc1.codncredit = RecId
                           group by I.CodIntr
                           ) a_pg group by codintr )
            SELECT NC1.CodNCredit1, NC1.CodNCredit, NC1.Valoare + COALESCE( CORECTII.VALOARE, 0), NC1.CodObligStins,
                   NC1.CodDoc, NC1.TipDoc, NC1.CodObligStingator, NC1.Obs, NC1.ValDif, NC1.Valoare + COALESCE( CORECTII.VALOARE, 0),
                   I.PREFIXDOC DOC, I.NRDOC NRDOC, I.DATADOC DATADOC,
                   (SELECT PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT FROM PKG_MONEDE_GET_SIMBOL_MONEDA(NULL, G.MONEDA)) MONEDA,
                   A.OBS SEDIU,
                   CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END  CURS,
                   ROUND( V.ValM, 4) VALDOC,
                   ROUND( V.ValM * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END , 4) VALLEI,
                   (SELECT pkg_notecredit_GetDiscVolum.WME_RESULT FROM pkg_notecredit_GetDiscVolum(NULL, I.CodIntr, vCodContract, 2, RecID,0, vCurs)),
                   ROUND( V.ValM_b, 4) VALDOC_B,
                   ROUND( V.ValM_b * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END , 4) VALLEI_B,
                   (SELECT pkg_notecredit_GetDiscVolum.WME_RESULT FROM pkg_notecredit_GetDiscVolum(NULL, I.CodIntr, vCodContract, 2, RecID, 1, vCurs)),
                   0, '', I.CODINTR, NC1.CODCLASEDISC,
                   COALESCE(NC1.PROCTVA,24),
                   NC1.CODANALIZANOD,
                   NC1.CODCENTRU
            FROM NOTECREDIT1 NC1
            INNER JOIN INTRARI                  I    ON  NC1.Coddoc      = I.CodIntr AND  NC1.TipDoc = I.TipDoc
            INNER JOIN VALAFIS                  V    ON  I.CODINTR       = V.CODINTR
            LEFT JOIN GENERAL                   G    ON  I.CODINTR       = G.CODDOC  AND  I.TipDoc = G.TipDoc
            LEFT JOIN TMP_CURS_REGULARIZAT_LUNA GREG ON  GREG.CODGENERAL = G.CODGENERAL
            LEFT JOIN NAGENDA                   A    ON  A.CODAGENDA     = I.CODLOCATIE
            LEFT JOIN (SELECT SUM( COALESCE( N1.VALOARE, 0) - COALESCE( N1.VALOAREOLD, 0)) VALOARE, N1.CODNCREDIT1ORIG
                       FROM NOTECREDIT1 N1 INNER JOIN NOTECREDIT N ON  N1.CODNCREDIT = N.CODNCREDIT
                       WHERE N.CODNCREDIT &lt;&gt; RECID
                       GROUP BY N1.CODNCREDIT1ORIG
                      ) CORECTII ON  CORECTII.CODNCREDIT1ORIG = NC1.CODNCREDIT1
            WHERE NC1.CodNCredit = RecId AND  NC1.Tip = TO_NUMBER((current_setting('PKG_NOTECREDIT.tncVolum', true)),'999999999999999999');
          ELSE
            INSERT INTO TMP_NOTECREDITV_MAN(CodNCredit1, CodNCredit, Valoare, CodObligStins, CodDoc, TipDoc, CodObligStingator, Obs, ValDif, Valoareold, DOC,
            NRDOC, DATADOC, MONEDA, SEDIU, CURS, VALDOC_N, VALLEI_N, DISCOUNT_N, VALDOC_B, VALLEI_B, DISCOUNT_B, CODOBIECT, DENUMIRE, CODDOCMASTER, CODCLASEDISC,
            CODINTERN, PROCTVA, CODANALIZANOD, CODCENTRU)
            with ValAfis as ( select codintr1, valm, valm_b from (
            select I1.CodIntr1, I1.Cant*I1.PretOrig*I1.Coefdiscmaj ValM, I1.Cant*I1.PretOrig ValM_b
            FROM notecredit1 nc1
                 inner join INTRARI I on nc1.tipdoc = i.tipdoc
                 inner join intrari1 I1 on i.codintr = i1.codintr and nc1.coddoc = i1.codintr1
                 inner join contract1 c1 on c1.codcontract1 = GetCodContract1(i1.codobiect, i.datadoc, vCodContract)
            where I.DataDoc BETWEEN to_date(vDataStart, 'DD.MM.YYYY') and to_date(vDataStop, 'DD.MM.YYYY')
              and i1.codobiect &gt; 0
              and I1.CodObiect not in (current_setting ('PKG_NOTECREDIT.KArtDiscPrimVol', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtDiscPrimCant', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtPenPrimTer', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceF', true) ::numeric)
                        AND INSTR(current_setting ('PKG_NOTECREDIT.KArtDiscPrimTer', true) , TO_CHAR(I1.CODOBIECT)) = 0

              AND nc1.tip = tncVolum and c1.codcontract = vCodContract
              and nc1.codncredit = RecId
           ) a_pg )
            SELECT NC1.CodNCredit1, NC1.CodNCredit, NC1.Valoare + COALESCE( CORECTII.VALOARE, 0), NC1.CodObligStins,
                   NC1.CodDoc, NC1.TipDoc, NC1.CodObligStingator, NC1.Obs, NC1.ValDif, NC1.Valoare + COALESCE( CORECTII.VALOARE, 0),
                   I.PREFIXDOC DOC, I.NRDOC NRDOC, I.DATADOC DATADOC,
                   (SELECT PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT FROM PKG_MONEDE_GET_SIMBOL_MONEDA(NULL, G.MONEDA)) MONEDA,
                   A.OBS SEDIU,
                   CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END  CURS,
                   ROUND( V.ValM, 4) VALDOC,
                   ROUND( V.ValM * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END , 4) VALLEI,
                   (SELECT pkg_notecredit_GetDiscVolum.WME_RESULT FROM pkg_notecredit_GetDiscVolum(NULL, NC1.CodDoc, vCodContract, 2, RecID,0, vCurs)),
                   ROUND( V.ValM_b, 4) VALDOC_B,
                   ROUND( V.ValM_b * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END , 4) VALLEI_B,
                   (SELECT pkg_notecredit_GetDiscVolum.WME_RESULT FROM pkg_notecredit_GetDiscVolum(NULL, NC1.CodDoc, vCodContract, 2, RecID, 1, vCurs)),
                   I1.CODOBIECT, OBJ.DENUMIRE, I.CODINTR, NC1.CODCLASEDISC, OBJ.CODINTERN,
                   COALESCE(NC1.PROCTVA,24),
                   NC1.CODANALIZANOD,
                   NC1.CODCENTRU
            FROM NOTECREDIT1 NC1
            INNER JOIN INTRARI                   I    ON  NC1.TipDoc      = I.TipDoc
            INNER JOIN INTRARI1                  I1   ON  NC1.Coddoc      = I1.CodIntr1 AND  I1.CodIntr = I.CodIntr
            INNER JOIN VALAFIS                   V    ON  I1.CODINTR1     = V.CODINTR1
            INNER JOIN NARTOBJ                   OBJ  ON  OBJ.CodObiect   = I1.CodObiect
            LEFT  JOIN GENERAL                   G    ON  I.CODINTR       = G.CODDOC AND  I.TipDoc = G.TipDoc
            LEFT  JOIN TMP_CURS_REGULARIZAT_LUNA GREG ON  GREG.CODGENERAL = G.CODGENERAL
            LEFT  JOIN NAGENDA                   A    ON  A.CODAGENDA     = I.CODLOCATIE
            LEFT  JOIN (SELECT SUM( COALESCE( N1.VALOARE, 0) - COALESCE( N1.VALOAREOLD, 0)) VALOARE, N1.CODNCREDIT1ORIG
                        FROM NOTECREDIT1 N1 INNER JOIN NOTECREDIT N ON  N1.CODNCREDIT = N.CODNCREDIT
                        WHERE N.CODNCREDIT &lt;&gt; RECID
                        GROUP BY N1.CODNCREDIT1ORIG
                       ) CORECTII ON  CORECTII.CODNCREDIT1ORIG = NC1.CODNCREDIT1
            WHERE NC1.CodNCredit = RecId AND  NC1.Tip = TO_NUMBER((current_setting('PKG_NOTECREDIT.tncVolum', true)),'999999999999999999');
          END IF;
        END IF;
      ELSE
        IF  vVolumPeArticole = 0 THEN
          INSERT INTO TMP_NOTECREDITV_MAN(CodNCredit1, CodNCredit, Valoare, CodObligStins, CodDoc, TipDoc, CodObligStingator, Obs, ValDif, Valoareold, DOC, NRDOC,
          DATADOC, MONEDA, SEDIU, CURS, VALDOC_N, VALLEI_N, DISCOUNT_N, VALDOC_B, VALLEI_B, DISCOUNT_B, CODOBIECT, DENUMIRE, CODDOCMASTER, CODCLASEDISC,
          PROCTVA, CODANALIZANOD, CODCENTRU)
          with ValAfis as ( select codintr, sum(valm) valm, sum(valm_b) valm_b from (
                            select I.CodIntr, SUM(I1.Cant*I1.PretOrig*I1.Coefdiscmaj) ValM,
                                   SUM(I1.Cant*I1.PretOrig) ValM_b
                            FROM notecredit1 nc1
                                 inner join INTRARI I on nc1.coddoc = i.codintr and nc1.tipdoc = i.tipdoc
                                 inner join intrari1 I1 on i.codintr = i1.codintr
                            where I.DataDoc BETWEEN to_date(vDataStart, 'DD.MM.YYYY') and to_date(vDataStop, 'DD.MM.YYYY')
                            and i1.codobiect &gt; 0
                              and I1.CodObiect not in (current_setting ('PKG_NOTECREDIT.KArtDiscPrimVol', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtDiscPrimCant', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtPenPrimTer', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceF', true) ::numeric)
                              AND INSTR(current_setting ('PKG_NOTECREDIT.KArtDiscPrimTer', true) , TO_CHAR(I1.CODOBIECT)) = 0
                              AND nc1.tip = tncVolum
                              and nc1.codncredit = RecId
                           group by I.CodIntr
                           ) a_pg group by codintr )
          SELECT NC1.CodNCredit1, NC1.CodNCredit, NC1.Valoare + COALESCE( CORECTII.VALOARE, 0), NC1.CodObligStins,
                 NC1.CodDoc, NC1.TipDoc, NC1.CodObligStingator, NC1.Obs, NC1.ValDif, NC1.Valoare + COALESCE( CORECTII.VALOARE, 0),
                 I.PREFIXDOC DOC, I.NRDOC NRDOC, I.DATADOC DATADOC,
                 (SELECT PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT FROM PKG_MONEDE_GET_SIMBOL_MONEDA(NULL, G.MONEDA)) MONEDA,
                 A.OBS SEDIU,
                 CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END  CURS,
                 ROUND( V.ValM, 4) VALDOC,
                 ROUND( V.ValM * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END , 4) VALLEI,
                 (SELECT pkg_notecredit_GetDiscVolum.WME_RESULT FROM pkg_notecredit_GetDiscVolum(NULL, I.CodIntr, vCodContract, 2, RecID, 0, vCurs)),
                 ROUND( V.ValM_b, 4) VALDOC_B,
                 ROUND( V.ValM_b * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END , 4) VALLEI_B,
                 (SELECT pkg_notecredit_GetDiscVolum.WME_RESULT FROM pkg_notecredit_GetDiscVolum(NULL, I.CodIntr, vCodContract, 2, RecID, 1, vCurs)),
                 0, '', I.CODINTR, NC1.CODCLASEDISC,
                 COALESCE(NC1.PROCTVA,24),
                 NC1.CODANALIZANOD,
                 NC1.CODCENTRU
          FROM NOTECREDIT1 NC1
          INNER JOIN INTRARI                   I    ON  NC1.Coddoc      = I.CodIntr AND  NC1.TipDoc = I.TipDoc
          INNER JOIN VALAFIS                   V    ON  I.CODINTR       = V.CODINTR
          LEFT  JOIN GENERAL                   G    ON  I.CODINTR       = G.CODDOC  AND  I.TipDoc = G.TipDoc
          LEFT  JOIN TMP_CURS_REGULARIZAT_LUNA GREG ON  GREG.CODGENERAL = G.CODGENERAL
          LEFT  JOIN NAGENDA                   A    ON  A.CODAGENDA     = I.CODLOCATIE
          LEFT  JOIN (SELECT SUM( COALESCE( N1.VALOARE, 0) - COALESCE( N1.VALOAREOLD, 0)) VALOARE, N1.CODNCREDIT1ORIG
                      FROM NOTECREDIT1 N1 INNER JOIN NOTECREDIT N ON  N1.CODNCREDIT = N.CODNCREDIT
                      WHERE N.CODNCREDIT &lt;&gt; RECID
                      GROUP BY N1.CODNCREDIT1ORIG
                     ) CORECTII ON  CORECTII.CODNCREDIT1ORIG = NC1.CODNCREDIT1
          WHERE NC1.CodNCredit = RecId AND  NC1.Tip = TO_NUMBER((current_setting('PKG_NOTECREDIT.tncVolum', true)),'999999999999999999');
        ELSE
          INSERT INTO TMP_NOTECREDITV_MAN(CodNCredit1, CodNCredit, Valoare, CodObligStins, CodDoc, TipDoc, CodObligStingator, Obs, ValDif, Valoareold, DOC, NRDOC,
          DATADOC, MONEDA, SEDIU, CURS, VALDOC_N, VALLEI_N, DISCOUNT_N, VALDOC_B, VALLEI_B, DISCOUNT_B, CODOBIECT, DENUMIRE, CODDOCMASTER, CODCLASEDISC, CODINTERN,
          PROCTVA, CODANALIZANOD, CODCENTRU)
          with ValAfis as ( select codintr1, valm, valm_b from (
                              select I1.CodIntr1, I1.Cant*I1.PretOrig*I1.Coefdiscmaj ValM, I1.Cant*I1.PretOrig ValM_b
                              FROM notecredit1 nc1
                                   inner join INTRARI I on nc1.tipdoc = i.tipdoc
                                   inner join intrari1 I1 on i.codintr = i1.codintr and nc1.coddoc = i1.codintr1
                              where I.DataDoc BETWEEN to_date(vDataStart, 'DD.MM.YYYY') and to_date(vDataStop, 'DD.MM.YYYY')
                              and i1.codobiect &gt; 0
                                and I1.CodObiect not in (current_setting ('PKG_NOTECREDIT.KArtDiscPrimVol', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtDiscPrimCant', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtPenPrimTer', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceF', true) ::numeric)
                                AND INSTR(current_setting ('PKG_NOTECREDIT.KArtDiscPrimTer', true) , TO_CHAR(I1.CODOBIECT)) = 0
                                AND nc1.tip = tncVolum
                                and nc1.codncredit = RecId
                             ) a_pg)
          SELECT NC1.CodNCredit1, NC1.CodNCredit, NC1.Valoare + COALESCE( CORECTII.VALOARE, 0), NC1.CodObligStins,
                 NC1.CodDoc, NC1.TipDoc, NC1.CodObligStingator, NC1.Obs, NC1.ValDif, NC1.Valoare + COALESCE( CORECTII.VALOARE, 0),
                 I.PREFIXDOC DOC, I.NRDOC NRDOC, I.DATADOC DATADOC,
                 (SELECT PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT FROM PKG_MONEDE_GET_SIMBOL_MONEDA(NULL, G.MONEDA)) MONEDA,
                 A.OBS SEDIU,
                 CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END  CURS,
                 ROUND( V.ValM, 4) VALDOC,
                 ROUND( V.ValM * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END , 4) VALLEI,
                 (SELECT pkg_notecredit_GetDiscVolum.WME_RESULT FROM pkg_notecredit_GetDiscVolum(NULL, NC1.CodDoc, vCodContract, 2, RecID, 0, vCurs)),
                 ROUND( V.ValM_b, 4) VALDOC_B,
                 ROUND( V.ValM_b * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END , 4) VALLEI_B,
                 (SELECT pkg_notecredit_GetDiscVolum.WME_RESULT FROM pkg_notecredit_GetDiscVolum(NULL, NC1.CodDoc, vCodContract, 2, RecID, 1, vCurs)),
                 I1.CODOBIECT, OBJ.DENUMIRE, I.CODINTR, NC1.CODCLASEDISC, OBJ.CODINTERN,
                 COALESCE(NC1.PROCTVA,24),
                 NC1.CODANALIZANOD,
                 NC1.CODCENTRU
          FROM NOTECREDIT1 NC1
          INNER JOIN INTRARI                   I    ON  NC1.TipDoc      = I.TipDoc
          INNER JOIN INTRARI1                  I1   ON  NC1.Coddoc      = I1.CodIntr1 AND  I1.CodIntr = I.CodIntr
          INNER JOIN VALAFIS                   V    ON  I1.CODINTR1     = V.CODINTR1
          INNER JOIN NARTOBJ                   OBJ  ON  OBJ.CodObiect   = I1.CodObiect
          LEFT  JOIN GENERAL                   G    ON  I.CODINTR       = G.CODDOC AND  I.TipDoc = G.TipDoc
          LEFT  JOIN TMP_CURS_REGULARIZAT_LUNA GREG ON  GREG.CODGENERAL = G.CODGENERAL
          LEFT  JOIN NAGENDA                   A    ON  A.CODAGENDA     = I.CODLOCATIE
          LEFT  JOIN (SELECT SUM( COALESCE( N1.VALOARE, 0) - COALESCE( N1.VALOAREOLD, 0)) VALOARE, N1.CODNCREDIT1ORIG
                      FROM NOTECREDIT1 N1 INNER JOIN NOTECREDIT N ON  N1.CODNCREDIT = N.CODNCREDIT
                      WHERE N.CODNCREDIT &lt;&gt; RECID
                      GROUP BY N1.CODNCREDIT1ORIG
                     ) CORECTII ON  CORECTII.CODNCREDIT1ORIG = NC1.CODNCREDIT1
          WHERE NC1.CodNCredit = RecId AND  NC1.Tip = TO_NUMBER((current_setting('PKG_NOTECREDIT.tncVolum', true)),'999999999999999999');
        END IF;
      END IF;
    END IF;
  END IF;

  BEGIN
    SELECT COALESCE( PretBrutV, 0) INTO vPretBrutV FROM tmp_notecredit_man;
  EXCEPTION WHEN others THEN
    vPretBrutV := 0;
  END;

  IF  vPretBrutV = 1 THEN
    UPDATE tmp_notecreditv_man
    SET
    ValDoc   = ValDoc_b,
    ValLei   = ValLei_b,
    Discount = Discount_b;
  ELSE
    UPDATE tmp_notecreditv_man
    SET
    ValDoc   = ValDoc_N,
    ValLei   = ValLei_N,
    Discount = Discount_N;
  END IF;

  SELECT count( *) INTO vCount FROM notecredit1
  WHERE codncredit = recid and  tip = TO_NUMBER((current_setting('PKG_NOTECREDIT.tncTermen', true)),'999999999999999999');

  IF  vCount &gt; 0 THEN
    PERFORM PKG_NOTECREDIT_MAKE_MANEVRA_T( vCodContract);
    IF  vTipDoc = 58 THEN
      INSERT INTO TMP_NOTECREDITT_MAN(CODNCREDIT1, CODNCREDIT, VALOARE, CODOBLIGSTINS, CODDOC, TIPDOC, CODOBLIGSTINGATOR, Obs, ValDif, Valoareold, doc, Cont,
      Moneda, Termen, Subunitatea, Sediu, Curs, ValDoc, ValLei, ValPlata, DocPlata, ZilePlata, Discount, Articol, CodObiect, Cant, ValFaraTVA, CODCLASEDISC,
      PROCTVA, CODANALIZANOD, CODCENTRU)
      SELECT NC1.CodNCredit1, NC1.CodNCredit,
             CASE WHEN TOT.VALTOT &lt;&gt; 0 THEN NC1.Valoare - NC1.VALOARE * COALESCE(CNC.FACTURAT,0)/TOT.VALTOT ELSE 0 END,
             NC1.CodObligStins, NC1.CodDoc, NC1.TipDoc, NC1.CodObligStingator,
             NC1.Obs, NC1.ValDif,
             CASE WHEN TOT.VALTOT &lt;&gt; 0 THEN NC1.Valoare - NC1.VALOARE * COALESCE(CNC.FACTURAT,0)/TOT.VALTOT ELSE 0 END,
             I.prefixdoc || ' ' || I.nrdoc || '/' || to_char( I.datadoc, 'dd.mm.yyyy'),
             (SELECT PKG_LIST_BASE_UTILS_decode_iCont.WME_RESULT FROM PKG_LIST_BASE_UTILS_decode_iCont(NULL, obstins.icont, obstins.codpart, i.an * 12 + i.luna, obstins.semnificatie)),
             (SELECT PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT FROM PKG_MONEDE_GET_SIMBOL_MONEDA(NULL, COALESCE( gstins.MONEDA, 0))),
             obstins.termen, i.subunitatea, A.Obs,
             CASE WHEN  COALESCE( GREG.CURS, GSTINS.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, GSTINS.CURS) END ,
             CASE WHEN  i.tipdoc = 21 THEN i1.pretorig * i1.cant * i1.coefdiscmaj
                  ELSE i1.pretorig * i1.cant * i1.coefdiscmaj + i1.tva
             END ,
             ROUND( CASE WHEN  i.tipdoc = 21 THEN i1.pretorig * i1.cant * i1.coefdiscmaj
                         ELSE i1.pretorig * i1.cant * i1.coefdiscmaj + i1.tva
                    END  * CASE WHEN  COALESCE( GREG.CURS, GSTINS.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, GSTINS.CURS) END , 4),
             CASE
               when coalesce(i.valdoc,0)=0 then 0---razvan
               when (SELECT pkg_notecredit_IsCumulat.WME_RESULT FROM pkg_notecredit_IsCumulat(NULL, i1.codies1, C.CODCONTRACT, 1)) = 1 then case when i.tipdoc = 21 then i1.pretorig*i1.cant*i1.coefdiscmaj
               else i1.pretorig*i1.cant*i1.coefdiscmaj+i1.tva END
               else sign(obstins.valoare) * stingere.valoare * (case when i.tipdoc = 21 then i1.pretorig*i1.cant*i1.coefdiscmaj
               else i1.pretorig*i1.cant*i1.coefdiscmaj+i1.tva end) / i.valdoc
             END ,
             CASE WHEN (SELECT pkg_notecredit_IsCumulat.WME_RESULT FROM pkg_notecredit_IsCumulat(NULL, i1.codies1, C.CODCONTRACT, 1)) = 1 THEN 'TOTAL CUMULAT'
                  ELSE CASE WHEN  gstingator.tipdoc = 28 THEN 'PV' || ' ' || comp.nrdoc || '/' || to_char( comp.datadoc, 'dd.mm.yyyy')
                            ELSE t1.doc || ' ' || t1.nrdoc || '/' || to_char( t1.datadoc, 'dd.mm.yyyy')
                       END
             END ,
             COALESCE( T1.Datadoc, COMP.datadoc) - I.Datadoc,
             (SELECT pkg_notecredit_GETDISCTERMENCLI.WME_RESULT
              FROM   pkg_notecredit_GETDISCTERMENCLI(NULL, to_char( COALESCE( T1.Datadoc, COMP.datadoc), 'DD.MM.YYYY'),
                                                     COALESCE( T1.Datadoc, COMP.datadoc) - I.Datadoc,
                                                     C.CODCONTRACT, I1.CodIes1,
                                                     CASE WHEN  gstingator.tipdoc = 28 and  obstins.valoare &lt; 0 THEN -stingere.valoare
                                                          ELSE stingere.valoare
                                                     END
                                                     )
             ),
             OBJ.Denumire, I1.CodObiect, I1.Cant,
             CASE WHEN  i.tipdoc = 21 THEN (  i1.pretorig * i1.cant)  * i1.coefdiscmaj - i1.TVA
                  ELSE (i1.pretorig * i1.cant)  * i1.coefdiscmaj
             END ,
             NC1.CODCLASEDISC,
             COALESCE(NC1.PROCTVA,24),
             NC1.CODANALIZANOD,
             NC1.CODCENTRU
      FROM NOTECREDIT1 NC1
          INNER JOIN IESIRI1  I1          ON  NC1.CodDoc   = I1.CodIes1
          INNER JOIN NARTOBJ  OBJ         ON  I1.CodObiect = OBJ.CodObiect
          INNER JOIN IESIRI   I           ON  I1.CodIes    = I.CodIes
          INNER JOIN GENERAL  GSTINS      ON  I.CodIes     = GSTINS.CodDoc AND  I.TipDoc = GSTINS.TipDoc
          INNER JOIN OBLIGPIF obstins     on NC1.CODOBLIGSTINS = obstins.codobligpif and gstins.codgeneral = obstins.codgeneral
          LEFT  JOIN OBLIGPIF obstingator ON  NC1.CODOBLIGSTINGATOR  = obstingator.codobligpif
          LEFT  JOIN stingere             ON  stingere.codstinspif   = obstins.codobligpif AND  stingere.codstingatorpif = obstingator.codobligpif
          LEFT  JOIN GENERAL  GSTINGATOR  ON  obstingator.codgeneral = GSTINGATOR.CODGENERAL
          LEFT  JOIN (SELECT TT1.DOC, TT1.NRDOC, TT1.DATADOC, TT1.CODTREZOR1, TT.TIPDOC
                      FROM TREZOR1 TT1 INNER JOIN TREZOR TT ON  TT.CODTREZOR = TT1.CODTREZOR
                     ) T1                 ON  T1.CODTREZOR1 = GSTINGATOR.CODDOC AND  T1.TIPDOC = GSTINGATOR.TIPDOC
          LEFT  JOIN (SELECT c.datadoc, c.nrdoc, c.codcompens, 28 TIPDOC FROM compens c
                     ) comp               ON  comp.codcompens = gstingator.coddoc and  comp.tipdoc = gstingator.tipdoc
          LEFT  JOIN NAGENDA    A         ON  I.CODLOCATIE    = A.CODAGENDA
          LEFT  JOIN TMP_CURS_REGULARIZAT_LUNA GREG ON  GREG.CODGENERAL = GSTINS.CODGENERAL
          LEFT  JOIN NOTECREDIT NC        ON  NC1.CODNCREDIT  = NC.CODNCREDIT
          LEFT  JOIN CONTRACT   C         ON  NC.CODCONTRACT  = C.CODCONTRACT
          LEFT JOIN CENTRALIZARENC CNC ON CNC.CODNCREDIT = RECID AND CNC.PROCTVA = NC1.PROCTVA AND CNC.CODOBIECTASOC = I1.CODOBIECT
          LEFT JOIN (
            SELECT SUM(nc1.valoare) VALTOT,
                   I1.CODOBIECT, NC1.PROCTVA
              FROM NOTECREDIT1 NC1
              INNER JOIN IESIRI1 I1 ON NC1.CodDoc = I1.CodIes1
              INNER JOIN NARTOBJ OBJ ON I1.CodObiect = OBJ.CodObiect
              INNER JOIN IESIRI I ON I1.CodIes = I.CodIes
              INNER JOIN GENERAL GSTINS ON I.CodIes = GSTINS.CodDoc AND I.TipDoc = GSTINS.TipDoc
              INNER JOIN OBLIGPIF obstins on NC1.CODOBLIGSTINS = obstins.codobligpif  and gstins.codgeneral = obstins.codgeneral
            WHERE gstins.semnificatie &lt;&gt; 240 and gstins.semnificatie &lt;&gt; 500
            and gstins.semnificatie &lt;&gt; 211 and gstins.semnificatie &lt;&gt; 210 and NC1.CodNCredit = RecId AND NC1.Tip = tncTermen
            GROUP BY I1.CODOBIECT, NC1.PROCTVA
          ) TOT ON TOT.CODOBIECT = I1.CODOBIECT AND TOT.PROCTVA = NC1.PROCTVA
      WHERE gstins.semnificatie &lt;&gt; 240 and  gstins.semnificatie &lt;&gt; 500 and  gstins.semnificatie &lt;&gt; 211 and  gstins.semnificatie &lt;&gt; 210 and  NC1.CodNCredit = RecId AND  NC1.Tip = TO_NUMBER((current_setting('PKG_NOTECREDIT.tncTermen', true)),'999999999999999999');
    ELSE
      INSERT INTO TMP_NOTECREDITT_MAN(CODNCREDIT1, CODNCREDIT, VALOARE, CODOBLIGSTINS, CODDOC, TIPDOC, CODOBLIGSTINGATOR, Obs, ValDif, Valoareold, doc, Cont,
      Moneda, Termen, Subunitatea, Sediu, Curs, ValDoc, ValLei, ValPlata, DocPlata, ZilePlata, Discount, Articol, CodObiect, Cant, ValFaraTVA, CODCLASEDISC,
      PROCTVA, CODANALIZANOD, CODCENTRU)
      SELECT NC1.CodNCredit1, NC1.CodNCredit,
             CASE WHEN TOT.VALTOT &lt;&gt; 0 THEN NC1.Valoare - NC1.VALOARE * COALESCE(CNC.FACTURAT,0)/TOT.VALTOT ELSE 0 END,
             NC1.CodObligStins, NC1.CodDoc, NC1.TipDoc, NC1.CodObligStingator,
             NC1.Obs, NC1.ValDif,
             CASE WHEN TOT.VALTOT &lt;&gt; 0 THEN NC1.Valoare - NC1.VALOARE * COALESCE(CNC.FACTURAT,0)/TOT.VALTOT ELSE 0 END,
             I.prefixdoc || ' ' || I.nrdoc || '/' || to_char( I.datadoc, 'dd.mm.yyyy'),
             (SELECT PKG_LIST_BASE_UTILS_decode_iCont.WME_RESULT FROM PKG_LIST_BASE_UTILS_decode_iCont(NULL, obstins.icont, obstins.codpart, i.an * 12 + i.luna, obstins.semnificatie)),
             (SELECT PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT FROM PKG_MONEDE_GET_SIMBOL_MONEDA(NULL, COALESCE( gstins.MONEDA, 0))),
             obstins.termen, i.subunitatea, A.Obs,
             CASE WHEN  COALESCE( GREG.CURS, GSTINS.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, GSTINS.CURS) END ,
             i1.pu * i1.cant + i1.tva,
             ROUND((i1.pu * i1.cant + i1.tva) * CASE WHEN  COALESCE( GREG.CURS, GSTINS.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, GSTINS.CURS) END , 4),
             CASE
               when coalesce (i.valdoc,0)=0 then 0 ---razvan
               WHEN (SELECT pkg_notecredit_IsCumulat.WME_RESULT FROM pkg_notecredit_IsCumulat(NULL, i1.codintr1, C.CODCONTRACT, 2)) = 1 THEN i1.pu * i1.cant + i1.tva
                  ELSE sign( obstins.valoare) * stingere.valoare * (  i1.pu * i1.cant + i1.tva)  / i.valdoc
             END ,
             CASE WHEN (SELECT pkg_notecredit_IsCumulat.WME_RESULT FROM pkg_notecredit_IsCumulat(NULL, i1.codintr1, C.CODCONTRACT, 2)) = 1 THEN 'TOTAL CUMULAT'
                  ELSE CASE WHEN  gstingator.tipdoc = 28 THEN 'PV' || ' ' || comp.nrdoc || '/' || to_char( comp.datadoc, 'dd.mm.yyyy')
                            ELSE t1.doc || ' ' || t1.nrdoc || '/' || to_char( t1.datadoc, 'dd.mm.yyyy')
                       END
             END ,
             COALESCE( T1.Datadoc, comp.datadoc) - I.Datadoc,
             (SELECT pkg_notecredit_GETDISCTERMENFURN.WME_RESULT
              FROM   pkg_notecredit_GETDISCTERMENFURN(NULL, to_char( COALESCE( T1.Datadoc, comp.datadoc), 'DD.MM.YYYY'),
                                                      COALESCE( T1.Datadoc, comp.datadoc) - I.Datadoc,
                                                      C.CODCONTRACT, I1.CodIntr1,
                                                      CASE WHEN  gstingator.tipdoc = 28 and  obstins.valoare &lt; 0 THEN -stingere.valoare
                                                           ELSE stingere.valoare
                                                      END
                                                     )
             ),
             OBJ.Denumire, I1.CodObiect, I1.Cant, i1.pretorig * i1.cant * i1.coefdiscmaj, NC1.CODCLASEDISC,
             COALESCE(NC1.PROCTVA,24),
             NC1.CODANALIZANOD,
             NC1.CODCENTRU
      FROM NOTECREDIT1 NC1
          INNER JOIN INTRARI1 I1          ON  NC1.CodDoc             = I1.CodIntr1
          INNER JOIN NARTOBJ  OBJ         ON  I1.CodObiect           = OBJ.CodObiect
          INNER JOIN INTRARI  I           ON  I1.CodIntr             = I.CodIntr
          INNER JOIN GENERAL  GSTINS      ON  I.CodIntr              = GSTINS.CodDoc AND  I.TipDoc = GSTINS.TipDoc
          INNER JOIN OBLIGPIF obstins     on NC1.CODOBLIGSTINS       = obstins.codobligpif and gstins.codgeneral = obstins.codgeneral
          LEFT  JOIN OBLIGPIF obstingator ON  NC1.CODOBLIGSTINGATOR  = obstingator.codobligpif
          LEFT  JOIN stingere             ON  stingere.codstinspif   = obstins.codobligpif AND  stingere.codstingatorpif = obstingator.codobligpif
          LEFT  JOIN GENERAL  GSTINGATOR  ON  obstingator.codgeneral = GSTINGATOR.CODGENERAL
          LEFT  JOIN (SELECT TT1.DOC, TT1.NRDOC, TT1.DATADOC, TT1.CODTREZOR1, TT.TIPDOC
                      FROM TREZOR1 TT1 INNER JOIN TREZOR TT ON  TT.CODTREZOR = TT1.CODTREZOR
                     ) T1   ON  T1.CODTREZOR1 = GSTINGATOR.CODDOC AND  T1.TIPDOC = GSTINGATOR.TIPDOC
          LEFT  JOIN (SELECT c.datadoc, c.nrdoc, c.codcompens, 28 TIPDOC FROM compens c
                     ) comp ON  comp.codcompens = gstingator.coddoc and  comp.tipdoc = gstingator.tipdoc
          LEFT JOIN CENTRALIZARENC CNC ON CNC.CODNCREDIT = RECID AND CNC.PROCTVA = NC1.PROCTVA AND CNC.CODOBIECTASOC = I1.CODOBIECT
          LEFT JOIN (
            SELECT SUM(nc1.valoare) VALTOT,
              I1.CODOBIECT, NC1.PROCTVA
            FROM NOTECREDIT1 NC1
              INNER JOIN INTRARI1 I1 ON NC1.CodDoc = I1.CodIntr1
              INNER JOIN NARTOBJ OBJ ON I1.CodObiect = OBJ.CodObiect
              INNER JOIN INTRARI I ON I1.CodINTR = I.CodINTR
              INNER JOIN GENERAL GSTINS ON I.CodINTR = GSTINS.CodDoc AND I.TipDoc = GSTINS.TipDoc
              INNER JOIN OBLIGPIF obstins on NC1.CODOBLIGSTINS = obstins.codobligpif  and gstins.codgeneral = obstins.codgeneral
            WHERE gstins.semnificatie &lt;&gt; 140 and gstins.semnificatie &lt;&gt; 600 and gstins.semnificatie &lt;&gt; 130
              and NC1.CodNCredit = RecId AND NC1.Tip = tncTermen
              GROUP BY I1.CODOBIECT, NC1.PROCTVA
           ) TOT ON TOT.CODOBIECT = I1.CODOBIECT AND TOT.PROCTVA = NC1.PROCTVA
          LEFT  JOIN NAGENDA                   A    ON  I.CODLOCATIE    = A.CODAGENDA
          LEFT  JOIN TMP_CURS_REGULARIZAT_LUNA GREG ON  GREG.CODGENERAL = GSTINS.CODGENERAL
          LEFT  JOIN NOTECREDIT                NC   ON  NC1.CODNCREDIT  = NC.CODNCREDIT
          LEFT  JOIN CONTRACT                  C    ON  NC.CODCONTRACT  = C.CODCONTRACT
      WHERE gstins.semnificatie &lt;&gt; 140 and  gstins.semnificatie &lt;&gt; 600 and  gstins.semnificatie &lt;&gt; 130 and  NC1.CodNCredit = RecId AND  NC1.Tip = TO_NUMBER((current_setting('PKG_NOTECREDIT.tncTermen', true)),'999999999999999999');
    END IF;
  END IF;

  IF  vCodContract &gt; 0 THEN
    DELETE FROM tmp_notecreditt_man WHERE discount = 0;
  END IF;

  SELECT count( *) INTO vCount FROM notecredit1
  WHERE codncredit = recid and  tip = TO_NUMBER((current_setting('PKG_NOTECREDIT.tncCantitate', true)),'999999999999999999');

  IF  vCount &gt; 0 THEN
    IF  vTipDoc = 58 THEN
      IF  vCodContract &gt; 0 THEN
        INSERT INTO TMP_NOTECREDITC_MAN(CodNCredit1, CodNCredit, Valoare, CodObligStins, CodDoc, TipDoc, CodObligStingator, Obs, ValDif, Valoareold, ARTICOL,
        CANT, DOC, MONEDA, SEDIU, CURS, CODOBIECT, PROCDISC, PRET_N, PRET_B, VAL_N, VAL_B, VALLEI_N, VALLEI_B, DISCOUNT_N, DISCOUNT_B, ValFaraTVA_N,
        ValFaraTVA_B, CODCLASEDISC, CODINTERN, OBSNAV,
        PROCTVA, CODANALIZANOD, CODCENTRU)
        with CumulCant as
                            (
                              select
                                i1.codobiect,
                                sum(i1.cant) totalcant,
                                c1.codcontract1,
                                  sum(
                                    case when i.tipdoc = 21 then (i1.PretOrig*i1.cant*nvl(i1.coefdiscmaj,1) - i1.PretOrig*i1.cant*nvl(i1.coefdiscmaj,1)*
                                    PKG_LIST_BASE_UTILS_get_cota_tva_art(i1.codobiect, i.an, i.luna)/100) else i1.PretOrig*i1.cant*nvl(i1.coefdiscmaj,1) end
                                     )/sum(i1.cant) pretmediu,
                                  sum(
                                    case when i.tipdoc = 21 then (i1.PretOrig*i1.cant - i1.PretOrig*i1.cant*
                                    PKG_LIST_BASE_UTILS_get_cota_tva_art(i1.codobiect, i.an, i.luna)/100) else i1.PretOrig*i1.cant end
                                     )/sum(i1.cant) pretmediu_b
                              from notecredit1 nc1
                                   inner join iesiri1 i1 on nc1.coddoc = i1.codies1
                                   inner join iesiri   i on i1.codies    = i.codies
                                   inner join contract1 c1 on c1.codcontract1 = GetCodContract1(i1.codobiect, i.datadoc, vCodContract)
                                   inner join contract c on c1.codcontract = c.codcontract
                              where (NVL(i.anulat, 0) = 0)
                                    and c.codcontract = vCodContract
                                    and nc1.tip = tncCantitate and nc1.codncredit = RecId
                                    and I.Datadoc between To_Date(vDataStart, 'DD.MM.YYYY') and To_Date(vDataStop, 'DD.MM.YYYY')
                              group by i1.codobiect, c1.codcontract1
                            )
        SELECT NC1.CodNCredit1, NC1.CodNCredit, NC1.Valoare, NC1.CodObligStins, NC1.CodDoc, NC1.TipDoc, NC1.CodObligStingator,
               NC1.Obs, NC1.ValDif, NC1.Valoare, OBJ.Denumire ARTICOL, I1.cant,
               i.prefixdoc || ' ' || i.nrdoc || '/' || to_char( i.datadoc, 'dd.mm.yyyy') DOC,
               (SELECT PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT FROM PKG_MONEDE_GET_SIMBOL_MONEDA(NULL, COALESCE( g.MONEDA, 0))) MONEDA,
               A.obs SEDIU,
               CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END  CURS,
               i1.codobiect, 0,
               CASE WHEN  i.tipdoc = 21 THEN round( (  I1.Pretorig * i1.cant * i1.coefdiscmaj - i1.tva)  / i1.cant, 2)
                    ELSE i1.pretorig * i1.coefdiscmaj
               END  PRET,
               CASE WHEN  i.tipdoc = 21 THEN round((I1.Pretorig * i1.cant - i1.tva) / i1.cant, 2) ELSE i1.pretorig END  PRET_B,
               CASE WHEN  i.tipdoc = 21 THEN (  I1.cant * I1.Pretorig)  * i1.coefdiscmaj - i1.tva
                    ELSE I1.cant * I1.Pretorig * i1.coefdiscmaj
               END  VAL,
               CASE WHEN  i.tipdoc = 21 THEN (I1.cant * I1.Pretorig - i1.tva) ELSE I1.cant * I1.Pretorig END  VAL_B,
               CASE WHEN  i.tipdoc = 21 THEN (  I1.cant * I1.Pretorig)  * i1.coefdiscmaj - i1.tva
                    ELSE I1.cant * I1.Pretorig * i1.coefdiscmaj
               END  * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END  VALLEI,
               CASE WHEN  i.tipdoc = 21 THEN (  I1.cant * I1.Pretorig - i1.tva)
                    ELSE I1.cant * I1.Pretorig
               END  * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END  VALLEI_B,
               round( (SELECT pkg_notecredit_GetDiscCant.WME_RESULT
                       FROM   pkg_notecredit_GetDiscCant(NULL, I1.cant,
                                                         CASE WHEN  i.tipdoc = 21 THEN (I1.cant * I1.Pretorig) * i1.coefdiscmaj - i1.tva
                                                              ELSE I1.cant * I1.Pretorig * i1.coefdiscmaj
                                                         END ,
                                                         CumulCant.totalcant, CumulCant.codcontract1, CUmulCant.pretmediu, 0, vCurs
                                                        )), 2),
               round( (SELECT pkg_notecredit_GetDiscCant.WME_RESULT
                       FROM   pkg_notecredit_GetDiscCant(NULL, I1.cant,
                                                         CASE WHEN  i.tipdoc = 21 THEN (I1.cant * I1.Pretorig - i1.tva)
                                                              ELSE I1.cant * I1.Pretorig
                                                         END ,
                                                         CumulCant.totalcant, CumulCant.codcontract1, CUmulCant.pretmediu_b, 0, V_curs
                                                        )), 2),
               CASE WHEN  i.tipdoc = 21 THEN (I1.Pretorig * i1.cant * i1.coefdiscmaj - i1.tva)
                    ELSE i1.Pretorig * i1.Cant * i1.coefdiscmaj
               END ,
               CASE WHEN  i.tipdoc = 21 THEN (  I1.Pretorig * i1.cant - i1.tva) ELSE i1.Pretorig * i1.Cant END ,
               NC1.CODCLASEDISC, OBJ.CODINTERN, NC1.OBSNAV,
               COALESCE(NC1.PROCTVA,24),
               NC1.CODANALIZANOD,
               NC1.CODCENTRU
        FROM NOTECREDIT1 NC1
            INNER JOIN iesiri1 i1  ON  nc1.coddoc   = i1.codies1
            INNER JOIN iesiri  i   ON  i1.codies    = i.codies
            INNER JOIN CumulCant   ON  i1.codobiect = CumulCant.codobiect and  CumulCant.CodContract1 = (SELECT PKG_NOTECREDIT_GETCODCONTRACT1.WME_RESULT FROM PKG_NOTECREDIT_GETCODCONTRACT1(NULL, i1.codobiect, i.datadoc, vCodContract))
            INNER JOIN general g   ON  g.coddoc     = i.codies and  g.tipdoc = i.tipdoc and g.semnificatie IN (500, 240, 211, 100, 140, 400)
            INNER JOIN NARTOBJ OBJ ON  I1.CodObiect = OBJ.Codobiect
            LEFT  JOIN NAGENDA A   ON  A.codagenda  = i.codlocatie
            LEFT  JOIN TMP_CURS_REGULARIZAT_LUNA GREG ON  GREG.CODGENERAL = G.CODGENERAL
        WHERE NC1.CodNCredit = RecId AND  NC1.Tip = TO_NUMBER((current_setting('PKG_NOTECREDIT.tncCantitate', true)),'999999999999999999');
      ELSE
        INSERT INTO TMP_NOTECREDITC_MAN(CodNCredit1, CodNCredit, Valoare, CodObligStins, CodDoc, TipDoc, CodObligStingator, Obs, ValDif, Valoareold, ARTICOL,
        CANT, DOC, MONEDA, SEDIU, CURS, CODOBIECT, PROCDISC, PRET_N, PRET_B, VAL_N, VAL_B, VALLEI_N, VALLEI_B, DISCOUNT_N, DISCOUNT_B, ValFaraTVA_N,
        ValFaraTVA_B, CODCLASEDISC, CODINTERN, OBSNAV,
        PROCTVA, CODANALIZANOD, CODCENTRU)
         with CumulCant as
                            (
                              select
                                i1.codobiect,
                                sum(i1.cant) totalcant
                              from notecredit1 nc1
                                   inner join iesiri1 i1 on nc1.coddoc = i1.codies1
                                   inner join iesiri   i on i1.codies  = i.codies
                              where (NVL(i.anulat, 0) = 0)
                                    and nc1.tip = tncCantitate and nc1.codncredit = RecId
                                    and I.Datadoc between To_Date(vDataStart, 'DD.MM.YYYY') and To_Date(vDataStop, 'DD.MM.YYYY')
                              group by i1.codobiect
                            )
        SELECT NC1.CodNCredit1, NC1.CodNCredit, NC1.Valoare, NC1.CodObligStins, NC1.CodDoc, NC1.TipDoc, NC1.CodObligStingator,
               NC1.Obs, NC1.ValDif, NC1.Valoare, OBJ.Denumire ARTICOL, I1.cant,
               i.prefixdoc || ' ' || i.nrdoc || '/' || to_char( i.datadoc, 'dd.mm.yyyy') DOC,
               (SELECT PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT FROM PKG_MONEDE_GET_SIMBOL_MONEDA(NULL, COALESCE( g.MONEDA, 0))) MONEDA,
               A.obs SEDIU,
               CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END  CURS,
               i1.codobiect,
               NC1.Valoare / CASE WHEN  I1.cant * I1.PU * CASE WHEN COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE COALESCE( GREG.CURS, G.CURS) END =0 THEN 1
                                  ELSE  I1.cant * I1.PU * CASE WHEN COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE COALESCE( GREG.CURS, G.CURS) END
                             END  * 100,
               CASE WHEN  i.tipdoc = 21 THEN round( (I1.Pretorig * i1.cant * i1.coefdiscmaj - i1.tva)  / i1.cant, 2)
                    ELSE i1.pretorig * i1.coefdiscmaj
               END  PRET,
               CASE WHEN  i.tipdoc = 21 THEN round( (I1.Pretorig * i1.cant - i1.tva)  / i1.cant, 2) ELSE i1.pretorig END  PRET_B,
               CASE WHEN  i.tipdoc = 21 THEN (  I1.cant * I1.Pretorig)  * i1.coefdiscmaj - i1.tva
                    ELSE I1.cant * I1.Pretorig * i1.coefdiscmaj
               END  VAL,
               CASE WHEN  i.tipdoc = 21 THEN (I1.cant * I1.Pretorig - i1.tva) ELSE I1.cant * I1.Pretorig END  VAL_B,
               CASE WHEN  i.tipdoc = 21 THEN (I1.cant * I1.Pretorig)  * i1.coefdiscmaj - i1.tva
                    ELSE I1.cant * I1.Pretorig * i1.coefdiscmaj
               END  * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END  VALLEI,
               CASE WHEN  i.tipdoc = 21 THEN (I1.cant * I1.Pretorig - i1.tva)
                    ELSE I1.cant * I1.Pretorig
               END  * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END  VALLEI_B,
               0, 0,
               CASE WHEN  i.tipdoc = 21 THEN (I1.Pretorig * i1.cant * i1.coefdiscmaj - i1.tva)
                    ELSE i1.Pretorig * i1.Cant * i1.coefdiscmaj
               END ,
               CASE WHEN  i.tipdoc = 21 THEN (I1.Pretorig * i1.cant - i1.tva) ELSE i1.Pretorig * i1.Cant END ,
               NC1.CODCLASEDISC, OBJ.CODINTERN, NC1.OBSNAV,
               COALESCE(NC1.PROCTVA,24),
               NC1.CODANALIZANOD,
               NC1.CODCENTRU
        FROM NOTECREDIT1 NC1
            INNER JOIN iesiri1 i1  ON  nc1.coddoc   = i1.codies1
            INNER JOIN CumulCant   ON  i1.codobiect = CumulCant.codobiect
            INNER JOIN iesiri  i   ON  i1.codies    = i.codies
            INNER JOIN general g   ON  g.coddoc     = i.codies and  g.tipdoc = i.tipdoc and g.semnificatie IN (500, 240, 211, 100, 140, 400)
            INNER JOIN NARTOBJ OBJ ON  I1.CodObiect = OBJ.Codobiect
            LEFT  JOIN NAGENDA A   ON  A.codagenda  = i.codlocatie
            LEFT  JOIN TMP_CURS_REGULARIZAT_LUNA GREG ON  GREG.CODGENERAL = G.CODGENERAL
        WHERE NC1.CodNCredit = RecId AND  NC1.Tip = TO_NUMBER((current_setting('PKG_NOTECREDIT.tncCantitate', true)),'999999999999999999');
      END IF;
    ELSE
      IF  vCodContract &gt; 0 THEN
        INSERT INTO TMP_NOTECREDITC_MAN(CodNCredit1, CodNCredit, Valoare, CodObligStins, CodDoc, TipDoc, CodObligStingator, Obs, ValDif, Valoareold, ARTICOL,
        CANT, DOC, MONEDA, SEDIU, CURS, CODOBIECT, PROCDISC, PRET_N, PRET_B, VAL_N, VAL_B, VALLEI_N, VALLEI_B, DISCOUNT_N, DISCOUNT_B, ValFaraTVA_N,
        ValFaraTVA_B, CODCLASEDISC, CODINTERN, OBSNAV,
        PROCTVA, CODANALIZANOD, CODCENTRU)
        with CumulCant as
                            (
                              select
                                i1.codobiect,
                                sum(i1.cant) totalcant,
                                c1.codcontract1,
                                sum(I1.cant * I1.Pretorig * I1.COEFDISCMAJ)/sum(i1.cant) pretmediu,
                                sum(I1.cant * I1.Pretorig)/sum(i1.cant) pretmediu_b
                              from notecredit1 nc1
                                   inner join intrari1 i1 on nc1.coddoc = i1.codintr1
                                   inner join intrari   i on i1.codintr    = i.codintr
                                   inner join contract1 c1 on c1.codcontract1 = GetCodContract1(i1.codobiect, i.datadoc, vCodContract)
                                   inner join contract c on c.codcontract = c1.codcontract
                              where (NVL(i.anulat, 0) = 0)
                                    and c.codcontract = vCodContract
                                    and nc1.codncredit = RecId and nc1.tip = tncCantitate
                                    and I.Datadoc between To_Date(vDataStart, 'DD.MM.YYYY') and To_Date(vDataStop, 'DD.MM.YYYY')
                              group by i1.codobiect, c1.codcontract1
                            )
        SELECT NC1.CodNCredit1, NC1.CodNCredit, NC1.Valoare, NC1.CodObligStins, NC1.CodDoc, NC1.TipDoc, NC1.CodObligStingator,
               NC1.Obs, NC1.ValDif, NC1.Valoare, OBJ.Denumire ARTICOL, I1.cant,
               i.prefixdoc || ' ' || i.nrdoc || '/' || to_char( i.datadoc, 'dd.mm.yyyy') DOC,
               (SELECT PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT FROM PKG_MONEDE_GET_SIMBOL_MONEDA(NULL, COALESCE( g.MONEDA, 0))) MONEDA,
               A.obs SEDIU,
               CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END  CURS,
               i1.codobiect,
               CASE WHEN  vCodContract = 0 THEN NC1.Valoare / CASE WHEN  I1.cant * I1.Pretorig * I1.CoefDiscMaj * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END =0 THEN 1
                                                                   ELSE  I1.cant * I1.Pretorig * I1.CoefDiscMaj * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END
                                                              END
                    ELSE 0
               END ,
               I1.PU PRET,
               I1.PretOrig PRET,
               I1.cant * I1.Pretorig * I1.COEFDISCMAJ VAL,
               I1.cant * I1.Pretorig VAL_B,
               I1.cant * I1.Pretorig * I1.COEFDISCMAJ * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END  VALLEI,
               I1.cant * I1.Pretorig * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END  VALLEI_B,
               round( (SELECT pkg_notecredit_GetDiscCant.WME_RESULT
                       FROM   pkg_notecredit_GetDiscCant(NULL, I1.cant,
                                                         I1.cant * I1.Pretorig * I1.CoefDiscMaj * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END ,
                                                         CumulCant.totalcant, CumulCant.CodContract1, cumulcant.pretmediu, 0, vCurs
                                                        )
                      ), 2),
               round( (SELECT pkg_notecredit_GetDiscCant.WME_RESULT
                       FROM   pkg_notecredit_GetDiscCant(NULL, I1.cant,
                                                         I1.cant * I1.Pretorig * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END ,
                                                         CumulCant.totalcant, CumulCant.CodContract1, cumulcant.pretmediu_b, 0, Vcurs
                                                        )
                      ), 2),
               I1.cant * I1.PretOrig * I1.COEFDISCMAJ, I1.cant * I1.PretOrig, NC1.CODCLASEDISC, OBJ.CODINTERN, NC1.OBSNAV,
               COALESCE(NC1.PROCTVA,24),
               NC1.CODANALIZANOD,
               NC1.CODCENTRU
        FROM NOTECREDIT1 NC1
            INNER JOIN intrari1 i1  ON  nc1.coddoc   = i1.codintr1
            INNER JOIN CumulCant    ON  i1.codobiect = CumulCant.codobiect
            INNER JOIN intrari  i   ON  i1.codintr   = i.codintr
            INNER JOIN general  g   ON  g.coddoc     = i.codintr and  g.tipdoc = i.tipdoc and g.semnificatie IN (500, 111, 200, 140, 300, 240)
            INNER JOIN NARTOBJ  OBJ ON  I1.CodObiect = OBJ.Codobiect
            LEFT  JOIN NAGENDA  A   ON  A.codagenda  = i.codlocatie
            LEFT  JOIN TMP_CURS_REGULARIZAT_LUNA GREG ON  GREG.CODGENERAL = G.CODGENERAL
        WHERE NC1.CodNCredit = RecId AND  NC1.Tip = TO_NUMBER((current_setting('PKG_NOTECREDIT.tncCantitate', true)),'999999999999999999');
      ELSE
        INSERT INTO TMP_NOTECREDITC_MAN(CodNCredit1, CodNCredit, Valoare, CodObligStins, CodDoc, TipDoc, CodObligStingator, Obs, ValDif, Valoareold, ARTICOL,
        CANT, DOC, MONEDA, SEDIU, CURS, CODOBIECT, PROCDISC, PRET_N, PRET_B, VAL_N, VAL_B, VALLEI_N, VALLEI_B, DISCOUNT_N, DISCOUNT_B, ValFaraTVA_N,
        ValFaraTVA_B, CODCLASEDISC, CODINTERN, OBSNAV,
        PROCTVA, CODANALIZANOD, CODCENTRU)
        with CumulCant as
                          (
                            select
                              i1.codobiect,
                              sum(i1.cant) totalcant
                            from notecredit1 nc1
                                 inner join intrari1 i1 on nc1.coddoc = i1.codintr1
                                 inner join intrari   i on i1.codintr    = i.codintr
                            where (NVL(i.anulat, 0) = 0)
                                  and nc1.codncredit = RecId and nc1.tip = tncCantitate
                                  and I.Datadoc between To_Date(vDataStart, 'DD.MM.YYYY') and To_Date(vDataStop, 'DD.MM.YYYY')
                            group by i1.codobiect
                          )
        SELECT NC1.CodNCredit1, NC1.CodNCredit, NC1.Valoare, NC1.CodObligStins, NC1.CodDoc, NC1.TipDoc, NC1.CodObligStingator,
               NC1.Obs, NC1.ValDif, NC1.Valoare, OBJ.Denumire ARTICOL, I1.cant,
               i.prefixdoc || ' ' || i.nrdoc || '/' || to_char( i.datadoc, 'dd.mm.yyyy') DOC,
               (SELECT PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT FROM PKG_MONEDE_GET_SIMBOL_MONEDA(NULL, COALESCE( g.MONEDA, 0))) MONEDA,
               A.obs SEDIU,
               CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END  CURS,
               i1.codobiect,
               CASE WHEN  vCodContract = 0 THEN NC1.Valoare / CASE WHEN  I1.cant * I1.Pretorig * I1.CoefDiscMaj * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END =0 THEN 1
                                                                   ELSE  I1.cant * I1.Pretorig * I1.CoefDiscMaj * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END
                                                              END
                    ELSE 0
               END ,
               I1.PU PRET,
               I1.PretOrig PRET_B,
               I1.cant * I1.Pretorig * I1.COEFDISCMAJ VAL,
               I1.cant * I1.Pretorig VAL_B,
               I1.cant * I1.Pretorig * I1.COEFDISCMAJ * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END  VALLEI,
               I1.cant * I1.Pretorig * CASE WHEN  COALESCE( GREG.CURS, G.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, G.CURS) END  VALLEI_B,
               0, 0, I1.cant * I1.PretOrig * I1.COEFDISCMAJ, I1.cant * I1.PretOrig, NC1.CODCLASEDISC, OBJ.CODINTERN, NC1.OBSNAV,
               COALESCE(NC1.PROCTVA,24),
               NC1.CODANALIZANOD,
               NC1.CODCENTRU
        FROM NOTECREDIT1 NC1
            INNER JOIN intrari1 i1  ON  nc1.coddoc   = i1.codintr1
            INNER JOIN CumulCant    ON  i1.codobiect = CumulCant.codobiect
            INNER JOIN intrari  i   ON  i1.codintr   = i.codintr
            INNER JOIN general  g   ON  g.coddoc     = i.codintr and  g.tipdoc = i.tipdoc and g.semnificatie IN (500, 111, 200, 140, 300, 240)
            INNER JOIN NARTOBJ  OBJ ON  I1.CodObiect = OBJ.Codobiect
            LEFT  JOIN NAGENDA  A   ON  A.codagenda  = i.codlocatie
            LEFT  JOIN TMP_CURS_REGULARIZAT_LUNA GREG ON  GREG.CODGENERAL = G.CODGENERAL
        WHERE NC1.CodNCredit = RecId AND  NC1.Tip = TO_NUMBER((current_setting('PKG_NOTECREDIT.tncCantitate', true)),'999999999999999999');
      END IF;
    END IF;
  END IF;

  BEGIN
    SELECT COALESCE( PretBrutC, 0) INTO vPretBrutC FROM tmp_notecredit_man;
  EXCEPTION WHEN others THEN
    vPretBrutC := 0;
  END;

  IF  vPretBrutC = 1 THEN
    UPDATE tmp_notecreditc_man
    SET
    Pret       = PRET_B,
    Val        = VAL_B,
    VALLEI     = VALLEI_B,
    DISCOUNT   = DISCOUNT_B,
    VALFARATVA = VALFARATVA_B;
  ELSE
    UPDATE tmp_notecreditc_man
    SET
    Pret       = PRET_N,
    Val        = VAL_N,
    VALLEI     = VALLEI_N,
    DISCOUNT   = DISCOUNT_N,
    VALFARATVA = VALFARATVA_N;
  END IF;

  SELECT count( *) INTO vCount FROM notecredit1
  WHERE codncredit = recid and  tip = TO_NUMBER((current_setting('PKG_NOTECREDIT.tncPenalizari', true)),'999999999999999999');

  IF  vCount &gt; 0 THEN
    IF  vTipDoc = 58 THEN
      INSERT INTO TMP_NOTECREDITP_MAN(CodNCredit1, CodNCredit, Valoare, CodObligStins, CodDoc, TipDoc, CodObligStingator, Obs, ValDif, Valoareold, DOC, CONT,
      MONEDA, TERMEN, SUBUNITATEA, SEDIU, CURS, VALDOC, VALLEI, VALPLATA, DOCPLATA, ZILEPLATA, DISCOUNT,
      CODANALIZANOD, CODCENTRU)
      SELECT NC1.CodNCredit1, NC1.CodNCredit, NC1.Valoare, NC1.CodObligStins, NC1.CodDoc, NC1.TipDoc, NC1.CodObligStingator,
             NC1.Obs, NC1.ValDif, NC1.Valoare,
             i.prefixdoc || ' ' || i.nrdoc || '/' || to_char( i.datadoc, 'dd.mm.yyyy') DOC,
             (SELECT PKG_LIST_BASE_UTILS_decode_iCont.WME_RESULT FROM PKG_LIST_BASE_UTILS_decode_iCont(NULL, obstins.icont, obstins.codpart, i.an * 12 + i.luna, obstins.semnificatie)) CONT,
             (SELECT PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT FROM PKG_MONEDE_GET_SIMBOL_MONEDA(NULL, COALESCE( gstins.MONEDA, 0))) MONEDA,
             obstins.termen TERMEN, i.subunitatea SUBUNITATEA, A.obs SEDIU,
             CASE WHEN  COALESCE( GREG.CURS, GSTINS.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, GSTINS.CURS) END  CURS,
             obstins.valoare VALDOC,
             obstins.valoare * CASE WHEN  COALESCE( GREG.CURS, Gstins.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, Gstins.CURS) END  VALLEI,
             stingere.valoare, t1.doc || ' ' || t1.nrdoc || '/' || to_char( t1.datadoc, 'dd.mm.yyyy') DOCPLATA,
             t1.datadoc - i.datadoc,
             CASE WHEN  t1.datadoc &gt; obstins.termen THEN stingere.Valoare * (SELECT pkg_notecredit_GETPROCCONTRACTPEN.WME_RESULT FROM pkg_notecredit_GETPROCCONTRACTPEN(NULL, vCodContract)) / 100
                  ELSE 0
             END,
             NC1.CODANALIZANOD,
             NC1.CODCENTRU
      FROM NOTECREDIT1 NC1
          LEFT JOIN obligpif obstins     ON  nc1.codobligstins     = obstins.codobligpif
          LEFT JOIN obligpif obstingator ON  nc1.codobligstingator = obstingator.codobligpif
          LEFT JOIN stingere             ON  stingere.codstinspif  = obstins.codobligpif and  stingere.codstingatorpif = obstingator.codobligpif
          LEFT JOIN general  gstins      ON  gstins.codgeneral     = obstins.codgeneral
          LEFT JOIN general  gstingator  ON  gstingator.codgeneral = obstingator.codgeneral
          LEFT JOIN iesiri   i           ON  gstins.coddoc         = i.codies and  gstins.tipdoc = i.tipdoc
          LEFT JOIN trezor1  t1          ON  gstingator.coddoc     = t1.codtrezor1
          LEFT JOIN trezor   t           ON  t1.codtrezor          = t.codtrezor and  gstingator.tipdoc = t.tipdoc
          LEFT JOIN nagenda  a           ON  i.codlocatie          = a.codagenda
          LEFT JOIN TMP_CURS_REGULARIZAT_LUNA GREG ON  GREG.CODGENERAL = GSTINS.CODGENERAL
      WHERE NC1.CodNCredit = RecId AND  NC1.Tip = TO_NUMBER((current_setting('PKG_NOTECREDIT.tncPenalizari', true)),'999999999999999999');
    ELSE
      INSERT INTO TMP_NOTECREDITP_MAN(CodNCredit1, CodNCredit, Valoare, CodObligStins, CodDoc, TipDoc, CodObligStingator, Obs, ValDif, Valoareold, DOC, CONT,
      MONEDA, TERMEN, SUBUNITATEA, SEDIU, CURS, VALDOC, VALLEI, VALPLATA, DOCPLATA, ZILEPLATA, DISCOUNT,
      CODANALIZANOD,
      CODCENTRU)
      SELECT NC1.CodNCredit1, NC1.CodNCredit, NC1.Valoare, NC1.CodObligStins, NC1.CodDoc, NC1.TipDoc, NC1.CodObligStingator,
             NC1.Obs, NC1.ValDif, NC1.Valoare,
             i.prefixdoc || ' ' || i.nrdoc || '/' || to_char( i.datadoc, 'dd.mm.yyyy') DOC,
             (SELECT PKG_LIST_BASE_UTILS_decode_iCont.WME_RESULT FROM PKG_LIST_BASE_UTILS_decode_iCont(NULL, obstins.icont, obstins.codpart, i.an * 12 + i.luna, obstins.semnificatie)) CONT,
             (SELECT PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT FROM PKG_MONEDE_GET_SIMBOL_MONEDA(NULL, COALESCE( gstins.MONEDA, 0))) MONEDA,
             obstins.termen TERMEN, i.subunitatea SUBUNITATEA, A.obs SEDIU,
             CASE WHEN  COALESCE( GREG.CURS, GSTINS.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, GSTINS.CURS) END  CURS,
             obstins.valoare VALDOC,
             obstins.valoare * CASE WHEN  COALESCE( GREG.CURS, Gstins.CURS)=0 THEN 1 ELSE  COALESCE( GREG.CURS, Gstins.CURS) END  VALLEI,
             stingere.valoare, t1.doc || ' ' || t1.nrdoc || '/' || to_char( t1.datadoc, 'dd.mm.yyyy') DOCPLATA,
             t1.datadoc - i.datadoc,
             CASE WHEN  t1.datadoc &gt; obstins.termen THEN stingere.Valoare * (SELECT pkg_notecredit_GETPROCCONTRACTPEN.WME_RESULT FROM pkg_notecredit_GETPROCCONTRACTPEN(NULL, vCodContract)) / 100
                  ELSE 0
             END,
             NC1.CODANALIZANOD,
             NC1.CODCENTRU
      FROM NOTECREDIT1 NC1
          LEFT JOIN obligpif obstins     ON  nc1.codobligstins     = obstins.codobligpif
          LEFT JOIN obligpif obstingator ON  nc1.codobligstingator = obstingator.codobligpif
          LEFT JOIN stingere             ON  stingere.codstinspif  = obstins.codobligpif and  stingere.codstingatorpif = obstingator.codobligpif
          LEFT JOIN general  gstins      ON  gstins.codgeneral     = obstins.codgeneral
          LEFT JOIN general  gstingator  ON  gstingator.codgeneral = obstingator.codgeneral
          LEFT JOIN intrari  i           ON  gstins.coddoc         = i.codintr and  gstins.tipdoc = i.tipdoc
          LEFT JOIN trezor1  t1          ON  gstingator.coddoc     = t1.codtrezor1
          LEFT JOIN trezor   t           ON  t1.codtrezor          = t.codtrezor and  gstingator.tipdoc = t.tipdoc
          LEFT JOIN nagenda  a           ON  i.codlocatie          = a.codagenda
          LEFT JOIN TMP_CURS_REGULARIZAT_LUNA GREG ON  GREG.CODGENERAL = GSTINS.CODGENERAL
      WHERE NC1.CodNCredit = RecId AND  NC1.Tip = TO_NUMBER((current_setting('PKG_NOTECREDIT.tncPenalizari', true)),'999999999999999999');
    END IF;
  END IF;

  IF  vTipDoc = 58 THEN
    INSERT INTO tmp_notecreditfact_man(codncfact, CodNCredit, coddoc, tipdoc, prefixdoc, nrdoc, datadoc, valdoc, valt,coddoc1)
    SELECT NCF.codncfact, NCF.CodNCredit, NCF.coddoc, NCF.tipdoc, NCF.prefixdoc, NCF.nrdoc, NCF.datadoc, NCF.valdoc, NCF.valdoc, ncf.coddoc1
    FROM Notecreditfact NCF INNER JOIN iesiri i ON  NCF.Coddoc = i.codies and  ncf.tipdoc = i.tipdoc
    WHERE codncredit = RecId;
  ELSE
    INSERT INTO tmp_notecreditfact_man(codncfact, CodNCredit, coddoc, tipdoc, prefixdoc, nrdoc, datadoc, valdoc, valt, coddoc1)
    SELECT NCF.codncfact, NCF.CodNCredit, NCF.coddoc, NCF.tipdoc, NCF.prefixdoc, NCF.nrdoc, NCF.datadoc, NCF.valdoc, NCF.ValT, ncf.coddoc1
    FROM Notecreditfact NCF
        LEFT JOIN intrari i   ON  NCF.Coddoc = i.codintr  and  ncf.tipdoc = i.tipdoc
        LEFT JOIN iesiri  ies ON  ncf.coddoc = ies.codies and  ncf.tipdoc = ies.tipdoc
    WHERE codncredit = RecId and (ies.codies &gt; 0 or  i.codintr &gt; 0) ;
  END IF;

  INSERT INTO tmp_nccadouri(codnccadouri, codncredit, codobiect, codobiectasoc, codobiectasocsec, cant, cantfact, codarticol, umsec, diferente, denumire,
  denumireasoc, denumireasocsec, den_um1, tiparticol, Pret, Paritate,
  CODANALIZANOD, CODCENTRU)
  SELECT c.codnccadouri, c.codncredit, c.codobiect, c.codobiectasoc, c.codobiectasocsec, c.cant, c.cantfact, c.codarticol, c.umsec, c.diferente, obj.denumire,
  objasoc.denumire, objasocsec.denumire, num1.den_um1, art.tiparticol, 0, num1.paritate,
  C.CODANALIZANOD,
  C.CODCENTRU
  FROM nccadouri c
      LEFT JOIN nartobj obj        ON  c.codobiect        = obj.codobiect
      LEFT JOIN nart    art        ON  obj.codarticol     = art.codarticol
      LEFT JOIN nartobj objasoc    ON  c.codobiectasoc    = objasoc.codobiect
      LEFT JOIN nartobj objasocsec ON  c.codobiectasocsec = objasocsec.codobiect
      LEFT JOIN num1               ON  num1.codum1        = c.umsec
  WHERE c.codncredit = RecId;

  INSERT INTO TMP_CENTRALIZARENC_MAN(CODCENTRALIZARE, CODNCREDIT, CODARTICOL, CODOBIECT, CODOBIECTASOC, CODOBIECTASOCSEC, UMSEC, DIFERENTE, TIPARTICOL, DENUMIRE,
  DENUMIREASOC, DENUMIREASOCSEC, DEN_UM1, PARITATE, FACTURAT, PROCTVA, CODCENTRU,
  CODANALIZANOD,
  OBS, CANT)
  SELECT C.CODCENTRALIZARE, C.CODNCREDIT, C.CODARTICOL, C.CODOBIECT, C.CODOBIECTASOC, C.CODOBIECTASOCSEC, C.UMSEC, C.DIFERENTE, NART.TIPARTICOL, O.DENUMIRE,
         CASE WHEN  o.codobiect &lt;&gt; COALESCE( (fnc_GetValConstantaLucru('ArtPenAc')::numeric), 0) THEN OS.DENUMIRE
              ELSE CASE WHEN  vTipDoc = 58 THEN iI.prefixdoc || ' ' || iI.nrdoc || '/' || to_char( ii.datadoc, 'dd.mm.yyyy')
                        ELSE it.prefixdoc || ' ' || it.nrdoc || '/' || to_char( it.datadoc, 'dd.mm.yyyy')
                   END
         END ,
         OSS.DENUMIRE, NUM1.DEN_UM1, 0, C.FACTURAT, COALESCE( C.PROCTVA, 24), C.CODCENTRU, C.CODANALIZANOD, C.OBS, C.CANT
  FROM CENTRALIZARENC C
      LEFT JOIN NART        ON  NART.CODARTICOL = C.CODARTICOL
      LEFT JOIN NARTOBJ O   ON  C.CODOBIECT     = O.CODOBIECT
      LEFT JOIN NARTOBJ OS  ON  OS.CODOBIECT    = C.CODOBIECTASOC
      LEFT JOIN NARTOBJ OSS ON  OSS.CODOBIECT   = C.CODOBIECTASOCSEC
      LEFT JOIN NUM1        ON  NUM1.CODUM1     = C.UMSEC
      LEFT JOIN IESIRI  II  ON  II.CODIES       = C.CODOBIECTASOC
      LEFT JOIN INTRARI IT  ON  IT.CODINTR      = C.CODOBIECTASOC
  WHERE C.CODNCREDIT = RECID;

  IF  vTipDoc = 58 THEN
    FOR v_rec IN
    (
      SELECT COALESCE( i1.codobiect, 0) CODOBIECT, COALESCE( i1.codobiectorig, 0) CODOBIECTORIG,
             CASE WHEN  art.tiparticol = 0 THEN i1.cant
                  ELSE CASE WHEN  i.tipdoc = 21 THEN I1.Cant * I1.PU - I1.TVA ELSE I1.Cant * I1.PU END
             END  VALOARE
      FROM tmp_notecreditfact_man tmp
          INNER JOIN iesiri1 i1  ON  i1.codies      = tmp.coddoc
          INNER JOIN iesiri  i   ON  i.codies       = i1.codies
          INNER JOIN nartobj obj ON  i1.codobiect   = obj.codobiect
          INNER JOIN nart    art ON  obj.codarticol = art.codarticol
      WHERE tmp.codncredit = recid
    )
    LOOP
      UPDATE tmp_centralizarenc_man
      SET
        paritate = paritate + v_Rec.valoare
      WHERE  COALESCE( codobiect, 0) = v_rec.codobiect and  COALESCE( codobiectasoc, 0) = v_Rec.codobiectorig and  codncredit = recid;
    END LOOP;
  ELSE
    FOR v_rec IN
    (
      SELECT COALESCE( i1.codobiect, 0) CODOBIECT, COALESCE( i1.codobiectorig, 0) CODOBIECTORIG,
             CASE WHEN  art.tiparticol &lt;&gt; 0 THEN I1.Cant * I1.PU ELSE i1.cant END  VALOARE
      FROM tmp_notecreditfact tmp
          INNER JOIN intrari  i   ON  tmp.coddoc     = i.codintr and  i.tipdoc = tmp.tipdoc
          INNER JOIN intrari1 i1  ON  tmp.coddoc     = i1.codintr
          INNER JOIN nartobj  obj ON  i1.codobiect   = obj.codobiect
          INNER JOIN nart     art ON  obj.codarticol = art.codarticol
      WHERE tmp.codncredit = recid
        and i1.codobiect IN (TO_NUMBER((current_setting('PKG_NOTECREDIT.KArtDiscPrimVol'    , true)),'999999999999999999'),
                             TO_NUMBER((current_setting('PKG_NOTECREDIT.KArtDiscPrimCant'   , true)),'999999999999999999'),
                             TO_NUMBER((current_setting('PKG_NOTECREDIT.KArtPenPrimTer'     , true)),'999999999999999999'),
                             TO_NUMBER((current_setting('PKG_NOTECREDIT.KArtDiscOffInvoiceF', true)),'999999999999999999')
                             OR INSTR(current_setting('PKG_NOTECREDIT.KArtDiscPrimTer'    , true), TO_CHAR(I1.CODOBIECT)) &gt; 0
                            )
      union ALL
      SELECT COALESCE( i1.codobiect, 0) CODOBIECT, COALESCE( i1.codobiectorig, 0) CODOBIECTORIG,
             -CASE WHEN  art.tiparticol &lt;&gt; 0 THEN I1.Cant * I1.PU ELSE i1.cant END  VALOARE
      FROM tmp_notecreditfact tmp
          INNER JOIN iesiri  i   ON  tmp.coddoc     = i.codies and  i.tipdoc = tmp.tipdoc
          INNER JOIN iesiri1 i1  ON  tmp.coddoc     = i1.codies
          INNER JOIN nartobj obj ON  i1.codobiect   = obj.codobiect
          INNER JOIN nart    art ON  obj.codarticol = art.codarticol
      WHERE tmp.codncredit = recid
        and i1.codobiect IN (TO_NUMBER((current_setting('PKG_NOTECREDIT.KArtDiscPrimVol'    , true)),'999999999999999999'),
                             TO_NUMBER((current_setting('PKG_NOTECREDIT.KArtDiscPrimCant'   , true)),'999999999999999999'),
                             TO_NUMBER((current_setting('PKG_NOTECREDIT.KArtPenPrimTer'     , true)),'999999999999999999'),
                             TO_NUMBER((current_setting('PKG_NOTECREDIT.KArtDiscOffInvoiceF', true)),'999999999999999999')
                             OR INSTR(current_setting('PKG_NOTECREDIT.KArtDiscPrimTer'    , true), TO_CHAR(I1.CODOBIECT)) &gt; 0
                            )
    )
    LOOP
      UPDATE tmp_centralizarenc_man
      SET
        paritate = paritate + v_Rec.valoare
      WHERE COALESCE( codobiect, 0) = v_rec.codobiect and  COALESCE( codobiectasoc, 0) = v_Rec.codobiectorig and  codncredit = recid;
    END LOOP;
  END IF;

  UPDATE tmp_centralizarenc_man SET diferente = diferente + COALESCE( facturat, 0) - COALESCE( paritate, 0);
  UPDATE tmp_centralizarenc_man
  SET
  facturat = paritate,
  den_um1  = (SELECT den_um1 FROM num1 WHERE codum1 = umsec);

  SELECT count( *) INTO vCount1 FROM tmp_centralizarenc_man;

  IF  vCount1 = 0 THEN
    SELECT count( *) INTO vCount FROM tmp_notecreditfact_man;

    IF  vCount &gt; 0 THEN
      IF  vTipDoc = 58 THEN
        INSERT INTO tmp_centralizarenc_man(CodArticol, CodObiect, DenumireAsoc, CodObiectAsoc, Denumire, Facturat, UMSec, Den_UM1, TIPARTICOL, paritate, DenumireAsocSec, CodObiectAsocSec)
        SELECT ART.CodArticol, OBJ.CodObiect, objasoc.denumire AS DENUMIREASOC,
               COALESCE( objasoc.codobiect, 0) AS CODOBIECTASOC, OBJ.Denumire,
               SUM( CASE  WHEN  art.tiparticol = 1 THEN CASE WHEN  i.tipdoc = 21 THEN I1.Cant * I1.PU - i1.tva
                                                             ELSE I1.Cant * I1.PU
                                                        END
                          ELSE I1.Cant
                    END ) FACTURAT,
               Num1.CODUM1 UMSEC, NUM1.Den_UM1, ART.TIPARTICOL, num1.paritate, objasocsec.denumire AS DENUMIREASOCSEC,
               COALESCE( objasocsec.codobiect, 0) AS CODOBIECTASOCSEC
        FROM IESIRI I
            INNER JOIN iesiri1                I1         ON  i.codies         = i1.codies
            INNER JOIN nartobj                OBJ        ON  i1.codobiect     = obj.codobiect
            INNER JOIN nart                   ART        ON  OBJ.codarticol   = ART.codarticol
            INNER JOIN num1                              ON  art.um           = num1.codum and  COALESCE( num1.secundara, 0) = 0
            INNER JOIN tmp_notecreditfact_man tmp        ON  i.codies         = tmp.coddoc and  tmp.tipdoc = i.tipdoc
            INNER JOIN tmp_notecredit_man     nc         ON  tmp.codncredit   = nc.codncredit
            LEFT  JOIN nartobj                OBJASOC    ON  i1.codobiectorig = objasoc.codobiect
            LEFT  JOIN contract1              c1         ON  i1.codobiectorig = c1.codcadou
            LEFT  JOIN contract               c          ON  c1.codcontract   = c.codcontract and  c.codcontract = vCodContract
            LEFT  JOIN nartobj                OBJASOCSEC ON  c1.codobiectsec  = objasocsec.codobiect
        WHERE I.TipDoc IN (19, 21, 26) AND  I.Partener = vCodPart
          AND I1.CodObiect IN (TO_NUMBER((current_setting('PKG_NOTECREDIT.KArtDiscPrimVol'    , true)),'999999999999999999'),
                             TO_NUMBER((current_setting('PKG_NOTECREDIT.KArtDiscPrimCant'   , true)),'999999999999999999'),
                             TO_NUMBER((current_setting('PKG_NOTECREDIT.KArtPenPrimTer'     , true)),'999999999999999999'),
                             TO_NUMBER((current_setting('PKG_NOTECREDIT.KArtDiscOffInvoiceF', true)),'999999999999999999')
                             AND INSTR(current_setting('PKG_NOTECREDIT.KArtDiscPrimTer'    , true), TO_CHAR(I1.CODOBIECT)) = 0
                            )
          AND  I1.TipLinie &lt;&gt; 'T' AND  I1.TipLinie &lt;&gt; 'G' AND  I.Subunitatea = nc.subunitatea
        GROUP BY OBJ.CodObiect, Obj.Denumire, ART.CodArticol, NUM1.CodUM1, NUM1.Den_UM1, objasoc.denumire, objasoc.codobiect, Art.TipArticol, num1.paritate, objasocsec.denumire, objasocsec.codobiect;
      ELSE
        INSERT INTO tmp_centralizarenc_man(CodArticol, CodObiect, DenumireAsoc, CodObiectAsoc, Denumire, Facturat, UMSec, Den_UM1, TIPARTICOL, paritate, DenumireAsocSec, CodObiectAsocSec)
        SELECT ART.CodArticol, OBJ.CodObiect, objasoc.denumire, COALESCE( objasoc.codobiect, 0), OBJ.Denumire,
               SUM( CASE WHEN  art.tiparticol = 1 THEN I1.Cant * I1.PU ELSE i1.Cant END ),
               Num1.CODUM1, NUM1.Den_UM1, Art.TipArticol, num1.paritate, objasocsec.denumire, COALESCE( objasocsec.codobiect, 0)
        FROM INTRARI I
            INNER JOIN INTRARI1               I1         ON  i.codintr        = i1.codintr
            INNER JOIN nartobj                OBJ        ON  i1.codobiect     = obj.codobiect
            INNER JOIN nart                   ART        ON  OBJ.codarticol   = ART.codarticol
            INNER JOIN num1                              ON  art.um           = num1.codum and  COALESCE( num1.secundara, 0) = 0
            INNER JOIN tmp_notecreditfact_man tmp        ON  i.codintr        = tmp.coddoc and  tmp.tipdoc = i.tipdoc
            LEFT  JOIN nartobj                OBJASOC    ON  i1.codobiectorig = objasoc.codobiect
            LEFT  JOIN contract1              c1         ON  i1.codobiectorig = c1.codcadou
            LEFT  JOIN contract               c          ON  c1.codcontract   = c.codcontract and  c.codcontract = vCodContract
            LEFT  JOIN nartobj                OBJASOCSEC ON  c1.codobiectsec  = objasocsec.codobiect
        WHERE I.TipDoc IN (1, 3, 4, 5, 9) AND  I.Partener = vCodPart
          AND I1.CodObiect IN (TO_NUMBER((current_setting('PKG_NOTECREDIT.KArtDiscPrimVol'    , true)),'999999999999999999'),
                             TO_NUMBER((current_setting('PKG_NOTECREDIT.KArtDiscPrimCant'   , true)),'999999999999999999'),
                             TO_NUMBER((current_setting('PKG_NOTECREDIT.KArtPenPrimTer'     , true)),'999999999999999999'),
                             TO_NUMBER((current_setting('PKG_NOTECREDIT.KArtDiscOffInvoiceF', true)),'999999999999999999')
                             OR INSTR(current_setting('PKG_NOTECREDIT.KArtDiscPrimTer'    , true), TO_CHAR(I1.CODOBIECT)) &gt; 0
                            )
          AND  I1.TipLinie &lt;&gt; 'T' AND  I1.TipLinie &lt;&gt; 'G' AND  I.Subunitatea = (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL))
        GROUP BY OBJ.CodObiect, Obj.Denumire, ART.CodArticol, NUM1.CodUM1, NUM1.Den_UM1, objasoc.denumire, objasoc.codobiect, Art.TipArticol, num1.paritate, objasocsec.denumire, objasocsec.codobiect;
      END IF;
    END IF;
  END IF;

  UPDATE TMP_CENTRALIZARENC_MAN SET PROCTVA = 24 WHERE PROCTVA IS NULL;

  UPDATE tmp_notecredit_man
  SET
  TOTALT     = (SELECT sum( valdoc)   FROM tmp_notecreditt_man),
  TOTALLEIT  = (SELECT sum( vallei)   FROM tmp_notecreditt_man),
  TOTALV     = (SELECT sum( valdoc)   FROM tmp_notecreditv_man),
  TOTALLEIV  = (SELECT sum( vallei)   FROM tmp_notecreditv_man),
  TOTALC     = (SELECT sum( val)      FROM tmp_notecreditc_man),
  TOTALLEIC  = (SELECT sum( vallei)   FROM tmp_notecreditc_man),
  TOTALP     = (SELECT sum( valdoc)   FROM tmp_notecreditp_man),
  TOTALLEIP  = (SELECT sum( vallei)   FROM tmp_notecreditp_man),
  TOTALZ     = (SELECT sum( valdoc)   FROM tmp_notecreditz_man),
  TOTALLEIZ  = (SELECT sum( vallei)   FROM tmp_notecreditz_man),
  TOTALDISCZ = (SELECT sum( discount) FROM tmp_notecreditz_man);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_sp_insertrecord</obj_name>
  <obj_hashval>003b6224461ba6751a227427e25a387f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NOTECREDIT (CodNCredit, VolumPeArticole, Trimestriala)
  VALUES(0, 0, 0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_test</obj_name>
  <obj_hashval>09f871ad97210b2b162b50492c46792b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_test()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aVal     numeric;
  aRest    numeric;
  dataref  date;
  sDataRef varchar;
  vdataref date;
  aIdx     numeric;
begin
  PERFORM PKG_NOTECREDIT_MAKE_MANEVRA_T(108);
  aVal := (SELECT pkg_notecredit_GETDISCTERMENFURN.WME_RESULT FROM pkg_notecredit_GETDISCTERMENFURN(NULL,'25.06.2020', 0, 108, 7013, 14388));
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_tnccadouri</obj_name>
  <obj_hashval>6a979f0465489f09f4ab2abd833012aa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_tnccadouri(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.tncCadouri', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 4;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_tnccantitate</obj_name>
  <obj_hashval>89b8456b5b61c20886ba4f9cea1183ff</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_tnccantitate(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.tncCantitate', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 3;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_tncprovizioane</obj_name>
  <obj_hashval>54bd94b22fb2b248f8bc3cd0c1741f1e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_tncprovizioane(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.tncProvizioane', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 5;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_tncvolum</obj_name>
  <obj_hashval>8a7ac3d395572beedf3fff5196c39e26</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_tncvolum(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.tncVolum', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 2;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_update_records</obj_name>
  <obj_hashval>ec943490d90bde722bdd4b830b02e780</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_update_records(atipdoc numeric, acoddoc1 numeric, acodcentralizare numeric, anrdoc numeric, adatadoc date, avalt numeric, aoldpu numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aPu numeric(20,7);
  aCodNCredit numeric(20);
  n NUMERIC;
  aValDoc NUMERIC(20,7);
  aVT NUMERIC(20,7);
BEGIN
  --Florin 17.12.2024 - fixat 64295
  --Florin 21.11.2024 - sinc. Oracle
  --Florin 04.05.2023 - sinc. Oracle
  if aTipDoc = 19 THEN
    select pu, pu*cant, pu*cant +tva into aPu, aValDoc, aVT from iesiri1 where codies1 = aCodDoc1;
    update centralizarenc set facturat = facturat - aOldPU + aPu, diferente = diferente + aOldPU - aPu where codcentralizare = aCodCentralizare;
  END IF;
  if aTipDoc = 1 THEN
    select pu, pu*cant, pu*cant +tva into aPu, aValDoc, aVT from intrari1 where codintr1 = aCodDoc1;
    update centralizarenc set facturat = facturat - aOldPU + aPu, diferente = diferente + aOldPU - aPu where codcentralizare = aCodCentralizare;
  END IF;
  select CodNCredit into aCodNCredit from CENTRALIZARENC where CODCENTRALIZARE = aCodCentralizare;
  SELECT count(*) INTO n FROM  NOTECREDITFACT F WHERE F.CODDOC1 = aCODDOC1 and F.TIPDOC = aTIPDOC AND F.CODNCREDIT = aCodNCredit;
  IF n= 0 THEN
    INSERT INTO NOTECREDITFACT(CODNCFACT,
            CODNCREDIT,
            TIPDOC,
            PREFIXDOC,
            NRDOC,
            DATADOC,
            VALDOC,
            VALT,
            CODDOC1)
    VALUES
            (NEXTVAL('SEQ_NOTECREDITFACT_CODNCFACT'),
            aCODNCREDIT,
            aTIPDOC,
            'F',
            aNRDOC,
            aDATADOC,
            aPu,
            aVALT,
            aCODDOC1);
  ELSE
    UPDATE NOTECREDITFACT SET VALDOC = aValDoc, VALT = aVT;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_updatecentralizare</obj_name>
  <obj_hashval>d1696c807765b448775ea7ea76227c24</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_updatecentralizare(acoddoc numeric, acodnc numeric, acoddoc1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  vtipdoc numeric;
  vVal    NUMERIC(20);
  v_tmp   record;
BEGIN
  --Florin 27.06.2024 - sinc. Oracle
  --Florin 11.09.2023 - sinc. Oracle
   select TipDoc into vTipDoc from notecredit where codncredit = acodnc;
  if aCodDoc1 &gt; 0 then
    if vTipDoc = 58 then
      for v_rec in (select nvl(i1.codobiect,0) codobiect, nvl(i1.codobiectorig,0) codobiectorig,
                           case
                             when art.tiparticol = 0 then i1.cant
                           else
                             case when i.tipdoc = 21 then I1.Cant*I1.PU - I1.TVA else I1.Cant*I1.PU end
                           end  valoare
                    from iesiri1 i1
                         inner join iesiri i on i.codies = i1.codies
                         inner join nartobj obj on i1.codobiect = obj.codobiect
                         inner join nart art on obj.codarticol = art.codarticol
                    where i1.codies = Abs(aCodDoc)) loop

        update centralizarenc
        set
          diferente = nvl(diferente,0) - Sign(aCodDoc) * v_Rec.valoare,
          facturat  = nvl(facturat,0) + Sign(aCodDoc) * v_rec.valoare
        where nvl(codobiect,0) = v_Rec.codobiect and nvl(codobiectasoc,0) = v_Rec.codobiectorig and codncredit = aCodNC;

        update tmp_centralizarenc
        set
          diferente = nvl(diferente,0) - Sign(aCodDoc) * v_Rec.valoare,
          facturat  = nvl(facturat,0) + Sign(aCodDoc) * v_rec.valoare
        where nvl(codobiect,0) = v_rec.codobiect and nvl(codobiectasoc,0) = v_Rec.codobiectorig and codncredit = aCodNC;

      end loop;
    else
      for v_rec in (select nvl(i1.codobiect,0) codobiect, nvl(i1.codobiectorig,0) codobiectorig,
                           case when art.tiparticol = 0 then I1.Cant*I1.PU else i1.cant end valoare
                    from intrari1 i1
                         inner join nartobj obj on i1.codobiect = obj.codobiect
                         inner join nart art on obj.codarticol = art.codarticol
                    where i1.codintr = Abs(aCodDoc)) loop
        vVal := v_rec.valoare;
        for v_tmp in (
          select coalesce(facturat,0) facturat, coalesce(diferente,0) diferente, codcentralizare
          from centralizarenc
          where nvl(codobiect,0) = v_rec.codobiect and codncredit = aCodNC and facturat &lt;&gt; 0
        ) loop
          if vVal &gt; v_tmp.facturat then
            vVal := vVal - v_tmp.facturat;
            update centralizarenc
            set
              diferente = nvl(diferente,0) + coalesce(facturat,0),
              facturat  = 0
            where codcentralizare = v_tmp.codcentralizare;

            update tmp_centralizarenc
            set
              diferente = nvl(diferente,0) + coalesce(facturat,0),
              facturat  = 0
            where codcentralizare = v_tmp.codcentralizare;
          else
            update centralizarenc
            set
              diferente = nvl(diferente,0) + vVal,
              facturat  = coalesce(facturat,0) - vVal
            where codcentralizare = v_tmp.codcentralizare;

            update tmp_centralizarenc
            set
              diferente = nvl(diferente,0) + vVal,
              facturat  = coalesce(facturat,0) - vVal
            where codcentralizare = v_tmp.codcentralizare;
            vVal := 0;
          end if;
          if vVal &lt;= 0 then Exit; end if;
        end loop;
      end loop;
    end if;
  else
    if vTipDoc = 58 then
      for v_rec in (select nvl(i1.codobiect,0) codobiect, nvl(i1.codobiectorig,0) codobiectorig,
                           case
                             when art.tiparticol = 0 then i1.cant
                           else
                             case when i.tipdoc = 21 then I1.Cant*I1.PU - I1.TVA else I1.Cant*I1.PU end
                           end  valoare
                    from iesiri1 i1
                         inner join iesiri i on i.codies = i1.codies
                         inner join nartobj obj on i1.codobiect = obj.codobiect
                         inner join nart art on obj.codarticol = art.codarticol
                    where i1.codies = Abs(aCodDoc)) loop

        update centralizarenc
        set
          diferente = nvl(diferente,0) - Sign(aCodDoc) * v_Rec.valoare,
          facturat  = nvl(facturat,0) + Sign(aCodDoc) * v_rec.valoare
        where nvl(codobiect,0) = v_Rec.codobiect and nvl(codobiectasoc,0) = v_Rec.codobiectorig and codncredit = aCodNC;

        update tmp_centralizarenc
        set
          diferente = nvl(diferente,0) - Sign(aCodDoc) * v_Rec.valoare,
          facturat  = nvl(facturat,0) + Sign(aCodDoc) * v_rec.valoare
        where nvl(codobiect,0) = v_rec.codobiect and nvl(codobiectasoc,0) = v_Rec.codobiectorig and codncredit = aCodNC;

      end loop;
    else
      for v_rec in (select nvl(i1.codobiect,0) codobiect, nvl(i1.codobiectorig,0) codobiectorig,
                           case when art.tiparticol = 0 then I1.Cant*I1.PU else i1.cant end valoare
                    from intrari1 i1
                         inner join nartobj obj on i1.codobiect = obj.codobiect
                         inner join nart art on obj.codarticol = art.codarticol
                    where i1.codintr = Abs(aCodDoc)) loop

        update centralizarenc
        set
          diferente = nvl(diferente,0) - Sign(aCodDoc) * v_Rec.valoare,
          facturat  = nvl(facturat,0) + Sign(aCodDoc) * v_rec.valoare
        where nvl(codobiect,0) = v_rec.codobiect and nvl(codobiectasoc,0) = v_Rec.codobiectorig and codncredit = aCodNC;

        update tmp_centralizarenc
        set
          diferente = nvl(diferente,0) - Sign(aCodDoc) * v_Rec.valoare,
          facturat  = nvl(facturat,0) + Sign(aCodDoc) * v_rec.valoare
        where nvl(codobiect,0) = v_rec.codobiect and nvl(codobiectasoc,0) = v_Rec.codobiectorig and codncredit = aCodNC;
      end loop;
    end if;
  end if;
  update tmp_notecredit set
    TOTALZ     = TOTALZ + (select nvl(Round(sum(valdoc),2),0) from tmp_notecreditz where nvl(codobligstins,0) = 0),
    TOTALLEIZ  = TOTALLEIZ + (select nvl(Round(sum(vallei),2),0) from tmp_notecreditz where nvl(codobligstins,0) = 0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_updatecentralizare</obj_name>
  <obj_hashval>e7427985b4625018626b65343db24e13</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_updatecentralizare(acodies numeric, acodnc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  vtipdoc numeric;
BEGIN
  --Florin 11.09.2023 - sinc. Oracle
  SELECT TipDoc INTO vTipDoc FROM notecredit WHERE codncredit = acodnc;

  IF vTipDoc = 58 THEN
    FOR v_rec IN (SELECT COALESCE (i1.codobiect, 0) CODOBIECT, COALESCE (i1.codobiectorig, 0) CODOBIECTORIG,
                         CASE WHEN art.tiparticol::numeric = 0 THEN i1.cant
                              ELSE CASE WHEN i.tipdoc = 21 THEN I1.Cant * I1.PU - I1.TVA
                                        ELSE I1.Cant * I1.PU
                                   END
                         END  VALOARE
                  FROM iesiri1         i1
                    INNER JOIN iesiri  i   ON i.codies       = i1.codies
                    INNER JOIN nartobj obj ON i1.codobiect   = obj.codobiect
                    INNER JOIN nart    art ON obj.codarticol = art.codarticol
                  WHERE
                    i1.codies = abs(aCodIes))
    LOOP
      UPDATE centralizarenc
      SET
        diferente = nvl(diferente,0) - Sign(aCodIes) * v_Rec.valoare,
        facturat  = nvl(facturat,0) + Sign(aCodIes) * v_rec.valoare
      WHERE
        COALESCE (codobiect, 0) = v_Rec.codobiect
        and COALESCE (codobiectasoc, 0) = v_Rec.codobiectorig
        and codncredit = aCodNC;

      UPDATE tmp_centralizarenc
      SET
        diferente = nvl(diferente,0) - Sign(aCodIes) * v_Rec.valoare,
        facturat  = nvl(facturat,0) + Sign(aCodIes) * v_rec.valoare
      WHERE
        COALESCE (codobiect, 0) = v_rec.codobiect
        and COALESCE (codobiectasoc, 0) = v_Rec.codobiectorig
        and codncredit = aCodNC;
    END LOOP;
  ELSE
    FOR v_rec IN (SELECT COALESCE (i1.codobiect, 0) CODOBIECT, COALESCE (i1.codobiectorig, 0) CODOBIECTORIG,
                         CASE WHEN art.tiparticol::numeric = 0 THEN I1.Cant * I1.PU ELSE i1.cant END  VALOARE
                  FROM intrari1          i1
                    INNER JOIN nartobj obj ON i1.codobiect = obj.codobiect
                    INNER JOIN nart    art ON obj.codarticol = art.codarticol
                  WHERE i1.codintr = aCodIes)
    LOOP
      UPDATE centralizarenc
      SET
        diferente = nvl(diferente,0) - Sign(aCodIes) * v_Rec.valoare,
        facturat  = nvl(facturat,0) + Sign(aCodIes) * v_rec.valoare
      WHERE
        COALESCE (codobiect, 0) = v_rec.codobiect
        and COALESCE (codobiectasoc, 0) = v_Rec.codobiectorig
        and codncredit = aCodNC;

      UPDATE tmp_centralizarenc
      SET
        diferente = nvl(diferente,0) - Sign(aCodIes) * v_Rec.valoare,
        facturat  = nvl(facturat,0) + Sign(aCodIes) * v_rec.valoare
      WHERE
        COALESCE (codobiect, 0) = v_rec.codobiect
        and COALESCE (codobiectasoc, 0) = v_Rec.codobiectorig
        and codncredit = aCodNC;

    END LOOP;
  END IF;

  UPDATE tmp_notecredit
  SET
  TOTALZ    = TOTALZ    + (SELECT COALESCE (Round ( (sum (valdoc)) ::numeric, 2) , 0)
                           FROM tmp_notecreditz WHERE COALESCE (codobligstins, 0) = 0) ,
  TOTALLEIZ = TOTALLEIZ + (SELECT COALESCE (Round ( (sum (vallei)) ::numeric, 2) , 0)
                           FROM tmp_notecreditz WHERE COALESCE (codobligstins, 0) = 0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_npartretail_clear_partretail_temps</obj_name>
  <obj_hashval>77666341f1cad7f7e7a6011e6ba1b973</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_npartretail_clear_partretail_temps()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM TMP_NPARTRETAIL;
  DELETE FROM TMP_NSEDIIPARTRETAIL;
  DELETE FROM TMP_NCODFISCRETAIL;
  DELETE FROM TMP_NPARTDISCRETAIL;
  DELETE FROM TMP_NDELEGATRETAIL;
  DELETE FROM TMP_NBANCIRETAIL;
  DELETE FROM TMP_NLOCALIT;
  DELETE FROM TMP_NBANK;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_npartretail_cod_fiscal_unic</obj_name>
  <obj_hashval>5e3a237eb183ac949a484684ae47fd90</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_npartretail_cod_fiscal_unic(INOUT wme_result numeric, INOUT acodpart numeric, INOUT acodfiscal character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  SELECT COUNT( *) INTO NR
  FROM NCODFISCRETAIL
  WHERE
     (SELECT PKG_NOMPART_STR_CODFISCAL.WME_RESULT FROM PKG_NOMPART_STR_CODFISCAL(NULL, CODFISCAL))
     =
     (SELECT PKG_NOMPART_STR_CODFISCAL.WME_RESULT FROM PKG_NOMPART_STR_CODFISCAL(NULL, aCODFISCAL))
     AND  CODPARTRETAIL &lt;&gt; aCODPART;

  IF  NR = 0 THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    WME_Result :=  0;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_npartretail_get_cod_banca</obj_name>
  <obj_hashval>6a4e126a0a9096f7371a28ccd356bb3e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_npartretail_get_cod_banca(INOUT wme_result numeric, INOUT acodbanca numeric, INOUT adenbanca character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODBANK numeric;
begin
  IF  COALESCE( aCODBANCA, 0) &lt;&gt; 0 THEN
    WME_Result :=  aCODBANCA;
    RETURN;
  ELSE
    IF  COALESCE( aDENBANCA, '?') = '?' THEN
      WME_Result :=  0;
      RETURN;
    END IF;

    BEGIN
      SELECT CODBANK INTO aCODBANK FROM NBANK WHERE UPPER( DENUMIRE) = UPPER( aDENBANCA);
    EXCEPTION WHEN OTHERS THEN
      aCODBANK := 0;
    END;

    IF  aCODBANK = 0 THEN
      aCODBANK := NEXTVAL('SEQ_NBANK_CODBANK');

      INSERT INTO NBANK(CODBANK, DENUMIRE, SIMBOL)
      VALUES(aCODBANK, aDENBANCA, SUBSTR( aDENBANCA, 1, 30));

      INSERT INTO TMP_NBANK(CODBANK, DENUMIRE, SIMBOL)
      VALUES(aCODBANK, aDENBANCA, SUBSTR( aDENBANCA, 1, 30));
    END IF;

    WME_Result :=  aCODBANK;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_npartretail_get_cod_localit</obj_name>
  <obj_hashval>3e85adf00f313b593da6dbd0433f7416</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_npartretail_get_cod_localit(INOUT wme_result numeric, INOUT acodlocalit numeric, INOUT adenlocalit character varying, INOUT acodjudet character varying, INOUT acodtara character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NEWCODLOCALIT numeric;
  NR NUMERIC;
BEGIN
  --Bogdan 30.08.2024 - 63204 - PG - Preluare facturi emise la posturi Retail - eroare
  --Florin 13.07.2023 - sinc. Oracle
   IF NVL(aCODLOCALIT, 0) &lt;&gt; 0  THEN
     SELECT COUNT(*) INTO NR FROM NLOCALIT WHERE CODLOCALIT = aCODLOCALIT;
     IF NR &gt; 0 THEN
       wme_result := aCODLOCALIT;
       RETURN;
     END IF;
   END IF;

   IF NVL(aDENLOCALIT, '?') = '?' THEN wme_result := 0; RETURN; END IF;

   BEGIN
     SELECT CODLOCALIT INTO NEWCODLOCALIT FROM NLOCALIT
     WHERE
       UPPER(DEN_LOCALIT) = UPPER(aDENLOCALIT)
       AND NVL(CODJUDET, 0) = NVL(aCODJUDET, 0)
       AND NVL(CODTARA, 0) = NVL(aCODTARA, 0);
       EXCEPTION WHEN OTHERS THEN NEWCODLOCALIT := 0;
   END;

   IF NEWCODLOCALIT = 0 THEN
      SELECT NEXTVAL('SEQ_NLOCALIT_CODLOCALIT') INTO NEWCODLOCALIT;
      INSERT INTO NLOCALIT(CODLOCALIT, DEN_LOCALIT, CODJUDET, CODTARA)
                  VALUES (NEWCODLOCALIT, aDENLOCALIT, aCODJUDET::numeric, aCODTARA::numeric);

      INSERT INTO TMP_NLOCALIT(CODLOCALIT, DEN_LOCALIT, CODJUDET, CODTARA)
                  VALUES (NEWCODLOCALIT, aDENLOCALIT, aCODJUDET::numeric, aCODTARA::numeric);
   END IF;
   wme_result := NEWCODLOCALIT;
   RETURN;


/*
  IF NVL(aCODLOCALIT, 0) &lt;&gt; 0  THEN
    RETURN aCODLOCALIT;
  ELSE

     IF NVL(aDENLOCALIT, '?') = '?' THEN RETURN 0; END IF;


    BEGIN
      SELECT CODLOCALIT INTO NEWCODLOCALIT FROM NLOCALIT
      WHERE
        UPPER(DEN_LOCALIT) = UPPER(aDENLOCALIT)
        AND NVL(CODJUDET, 0) = NVL(aCODJUDET, 0)
        AND NVL(CODTARA, 0) = NVL(aCODTARA, 0);
       EXCEPTION WHEN OTHERS THEN NEWCODLOCALIT := 0;
    END;

    IF NEWCODLOCALIT = 0 THEN
      NEWCODLOCALIT := SEQ_NLOCALIT_CODLOCALIT.NEXTVAL;
      INSERT INTO NLOCALIT(CODLOCALIT, DEN_LOCALIT, CODJUDET, CODTARA)
                  VALUES (NEWCODLOCALIT, aDENLOCALIT, aCODJUDET, aCODTARA);

      INSERT INTO TMP_NLOCALIT(CODLOCALIT, DEN_LOCALIT, CODJUDET, CODTARA)
                  VALUES (NEWCODLOCALIT, aDENLOCALIT, aCODJUDET, aCODTARA);



    END IF;
    RETURN NEWCODLOCALIT;

  END IF;
*/
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_npartretail_get_codiopart_luna_lucru</obj_name>
  <obj_hashval>95833a7040a1a10a94dee742c14f8680</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_npartretail_get_codiopart_luna_lucru(INOUT wme_result numeric, INOUT acodpart numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODIoPart numeric := -1;
  aAN        numeric;
  aLUna      numeric;
begin
  --Florin 30.12.2021 - sinc. Oracle (29.12.2021)
  aAN   := (SELECT PKG_GLOBALS_GETANLUCRU.WME_RESULT   FROM PKG_GLOBALS_GETANLUCRU(NULL,NULL));
  aLUNA := (SELECT PKG_GLOBALS_GETLUNALUCRU.WME_RESULT FROM PKG_GLOBALS_GETLUNALUCRU(NULL,NULL));

  BEGIN
    SELECT COALESCE( CodIoPart, 0) INTO aCodIoPart
    FROM NPart1 n1
      WHERE n1.CodPart = aCodPart AND aAn*12+aLuna BETWEEN n1.alstart AND n1.alstop;
  EXCEPTION WHEN OTHERS THEN
    aCodIoPart := 0;
  END;

  WME_Result :=  aCODIOPART;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_npartretail_prepare_modif_partretail</obj_name>
  <obj_hashval>d94ffddc61e08ddf2dd90022fb0ad841</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_npartretail_prepare_modif_partretail()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM TMP_NPARTRETAIL;
  DELETE FROM TMP_NSEDIIPARTRETAIL;
  DELETE FROM TMP_NCODFISCRETAIL;
  DELETE FROM TMP_NPARTDISCRETAIL;
  DELETE FROM TMP_NDELEGATRETAIL;
  DELETE FROM TMP_NBANCIRETAIL;
  DELETE FROM TMP_NLOCALIT;
  DELETE FROM TMP_NBANK;

  INSERT INTO TMP_NPARTRETAIL
  SELECT * FROM NPARTRETAIL WHERE CODPARTRETAIL &gt; 0 AND  COALESCE( CODPART, 0) &gt; 0 AND  TIPMODIF = 'M';

  INSERT INTO TMP_NSEDIIPARTRETAIL
  SELECT * FROM NSEDIIPARTRETAIL WHERE CODPARTRETAIL IN (SELECT CODPARTRETAIL FROM TMP_NPARTRETAIL);

  INSERT INTO TMP_NCODFISCRETAIL
  SELECT * FROM NCODFISCRETAIL WHERE CODPARTRETAIL IN (SELECT CODPARTRETAIL FROM TMP_NPARTRETAIL);

  INSERT INTO TMP_NPARTDISCRETAIL
  SELECT * FROM NPARTDISCRETAIL WHERE CODPARTRETAIL IN (SELECT CODPARTRETAIL FROM TMP_NPARTRETAIL);

  INSERT INTO TMP_NDELEGATRETAIL
  SELECT * FROM NDELEGATRETAIL WHERE CODPARTRETAIL IN (SELECT CODPARTRETAIL FROM TMP_NPARTRETAIL);

  INSERT INTO TMP_NBANCIRETAIL
  SELECT * FROM NBANCIRETAIL WHERE CODPARTRETAIL IN (SELECT CODPARTRETAIL FROM TMP_NPARTRETAIL);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_npartretail_prepare_new_partretail</obj_name>
  <obj_hashval>9045b2a06417e6af69b168f80640e185</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_npartretail_prepare_new_partretail()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM TMP_NPARTRETAIL;
  DELETE FROM TMP_NSEDIIPARTRETAIL;
  DELETE FROM TMP_NCODFISCRETAIL;
  DELETE FROM TMP_NPARTDISCRETAIL;
  DELETE FROM TMP_NDELEGATRETAIL;
  DELETE FROM TMP_NBANCIRETAIL;
  DELETE FROM TMP_NLOCALIT;
  DELETE FROM TMP_NBANK;

  INSERT INTO TMP_NPARTRETAIL
  SELECT * FROM NPARTRETAIL WHERE CODPARTRETAIL &gt; 0 AND  COALESCE( CODPART, 0) = 0;

  INSERT INTO TMP_NSEDIIPARTRETAIL
  SELECT * FROM NSEDIIPARTRETAIL WHERE CODPARTRETAIL IN (SELECT CODPARTRETAIL FROM TMP_NPARTRETAIL);

  INSERT INTO TMP_NCODFISCRETAIL
  SELECT * FROM NCODFISCRETAIL WHERE CODPARTRETAIL IN (SELECT CODPARTRETAIL FROM TMP_NPARTRETAIL);

  INSERT INTO TMP_NPARTDISCRETAIL
  SELECT * FROM NPARTDISCRETAIL WHERE CODPARTRETAIL IN (SELECT CODPARTRETAIL FROM TMP_NPARTRETAIL);

  INSERT INTO TMP_NDELEGATRETAIL
  SELECT * FROM NDELEGATRETAIL WHERE CODPARTRETAIL IN (SELECT CODPARTRETAIL FROM TMP_NPARTRETAIL);

  INSERT INTO TMP_NBANCIRETAIL
  SELECT * FROM NBANCIRETAIL WHERE CODPARTRETAIL IN (SELECT CODPARTRETAIL FROM TMP_NPARTRETAIL);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_npartretail_sp_gotorecord</obj_name>
  <obj_hashval>657a0475025c7a5d7e2026927b9fd310</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_npartretail_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 18.11.2022 - sinc. Oracle
  --Florin 14.11.2022 - sinc. Oracle
  --Florin 08.11.2022 - sinc. Oracle
  --Bogdan 29.01.2021
  INSERT INTO TMP_NPARTRETAIL (CODPARTRETAIL, CODPART, DENUMIRE, REGCOM, OBS, CODEXTERN, CODINTERN, TIPPART, COLDISCOUNT, CODCLASA, FIDELIZARE, DATANASTERE, BLOCAT, INFOBLOCAT, CODCATEGPRET)
  SELECT CODPARTRETAIL, CODPART, DENUMIRE, REGCOM, OBS, CODEXTERN, CODINTERN, TIPPART, COLDISCOUNT, CODCLASA, FIDELIZARE, DATANASTERE, BLOCAT, INFOBLOCAT, CODCATEGPRET
  FROM NPARTRETAIL
  WHERE CODPARTRETAIL = RECID;

  INSERT INTO TMP_NSEDIIPARTRETAIL (CODSEDIU, CODPARTRETAIL, DENUMIRE, CODLOCALIT, DENLOCALIT, CODJUDET, CODTARA, TELEFON, FAX, EMAIL, STRADA, NR1, NR2, BLOC, SCARA, ETAJ, APART, SECTOR, CODPOSTAL, SEDIUSOCIAL)
  SELECT CODSEDIU, CODPARTRETAIL, DENUMIRE, CODLOCALIT, DENLOCALIT, CODJUDET, CODTARA, TELEFON, FAX, EMAIL, STRADA, NR1, NR2, BLOC, SCARA, ETAJ, APART, SECTOR, CODPOSTAL, SEDIUSOCIAL
  FROM NSEDIIPARTRETAIL
  WHERE CODPARTRETAIL = RECID;

  INSERT INTO TMP_NCODFISCRETAIL (COD, CODPARTRETAIL, CODFISCAL, PRINCIPAL)
  SELECT COD, CODPARTRETAIL, CODFISCAL, PRINCIPAL FROM NCODFISCRETAIL WHERE CODPARTRETAIL = RECID;

  INSERT INTO TMP_NPARTDISCRETAIL (COD, CODPARTRETAIL, CODCATEGDISC, INDEXLOCAL)
  SELECT COD, CODPARTRETAIL, CODCATEGDISC, INDEXLOCAL FROM NPARTDISCRETAIL WHERE CODPARTRETAIL = RECID;

  INSERT INTO TMP_NDELEGATRETAIL (COD, CODPARTRETAIL, DELEGAT, CNP, DOC, SERIEDOC, NRDOC, ELIBERAT, MIJLTRANSP, NRTRANSP, ACTIV, DATADOC, IMPLICIT, OBS)
  SELECT COD, CODPARTRETAIL, DELEGAT, CNP, DOC, SERIEDOC, NRDOC, ELIBERAT, MIJLTRANSP, NRTRANSP, ACTIV, DATADOC, IMPLICIT, OBS
  FROM NDELEGATRETAIL
  WHERE CODPARTRETAIL = RECID;

  INSERT INTO TMP_NBANCIRETAIL (COD, CODPARTRETAIL, CODBANK, IMPLICIT, CODLOCALIT, CONTBANCA, SUCURSALA, CODMONEDA, DENBANCA, DENLOCALIT, CODJUDET, CODTARA)
  SELECT COD, CODPARTRETAIL, CODBANK, IMPLICIT, CODLOCALIT, CONTBANCA, SUCURSALA, CODMONEDA, DENBANCA, DENLOCALIT, CODJUDET, CODTARA
  FROM NBANCIRETAIL
  WHERE CODPARTRETAIL = RECID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_npartretail_sp_lockrecord</obj_name>
  <obj_hashval>5e48271306794854c73868faf80c22a7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_npartretail_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodPARTRETAIL INTO Tmp FROM NPARTRETAIL WHERE CodPARTRETAIL = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nzone_sp_lockrecord</obj_name>
  <obj_hashval>3c72a3306eddd66f1cb2ace4cfd198d5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nzone_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  tmp numeric;
begin
  SELECT codzona INTO tmp FROM nzone WHERE codzona = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_obiective_sp_deleterecord</obj_name>
  <obj_hashval>028fe0096b588c7ff054fe32b3e22cce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_obiective_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_OBIECTIVE_SP_LOCKRECORD( RecId);
  DELETE FROM OBIECTIVE WHERE CodOBIECTIV = RecId;
  PERFORM NotifyModif( 2, RECID, 'OBIECTIVE');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_obiective_sp_insertrecord</obj_name>
  <obj_hashval>7f314476e5e098e96682c02db4d5b1ac</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_obiective_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_OBIECTIVE(CodOBIECTIV) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_obiective_sp_lockrecord</obj_name>
  <obj_hashval>0d97e05503ca908e2dd6525d0a786dc7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_obiective_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodOBIECTIV INTO Tmp FROM OBIECTIVE WHERE CodOBIECTIV = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_obiective_sp_postrecords</obj_name>
  <obj_hashval>621ae155a74a29a3774925a6aa966e09</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_obiective_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    BEGIN
      SELECT CodOBIECTIV INTO RECID FROM TMP_OBIECTIVE;
    EXCEPTION WHEN OTHERS THEN
      RECID := 0;
    END;

    UPDATE OBIECTIVE
    SET
    (DEN_OBIECTIV, TIP) = (SELECT DEN_OBIECTIV, TIP FROM TMP_OBIECTIVE)
    WHERE
     CodOBIECTIV = RECID;
  ELSE
    SELECT NEXTVAL('SEQ_OBIECTIVE_CODOBIECTIV') INTO RecId;

    INSERT INTO OBIECTIVE(CodOBIECTIV, DEN_OBIECTIV, TIP)
    SELECT RECID, DEN_OBIECTIV, TIP FROM TMP_OBIECTIVE;
  END IF;

  PERFORM NotifyModif( OPERATION, RECID, 'OBIECTIVE');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oferta_ct_monitor</obj_name>
  <obj_hashval>a3caba184da586132f6c27ef6ac2a9d7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oferta_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_OFERTA.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_28';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oferta_debug</obj_name>
  <obj_hashval>d74dec0e07d0ed8700a2c6613bd40f40</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oferta_debug()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM pkg_globals_SETFIRMANAME( 'AAAAA');
  PERFORM PKG_OFERTA_SP_GOTORECORD( 105);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oferta_existaofertavalabila</obj_name>
  <obj_hashval>9381ab550c8de807f9e1cfd97618a69a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oferta_existaofertavalabila(INOUT wme_result numeric, INOUT acodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCount numeric;
begin
  SELECT count( *)
  INTO aCount
  FROM oferta1 o1
      INNER JOIN oferta o  ON  o.codoferta = o1.codoferta
      INNER JOIN num1   um ON  o1.umsec    = um.codum1
  WHERE  o1.codobiect = aCodObiect
    and  COALESCE( o.operat, 0) = 1
    and  COALESCE( o.anulat, 0) &lt;&gt; 1
    and CURRENT_TIMESTAMP BETWEEN o.datastart AND o.dataend
    and  o.tipdoc = 51;

  WME_Result :=  aCount;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oferta_getcodoferta1</obj_name>
  <obj_hashval>3f38c7a1f0e288da1fe3ff999db6c242</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oferta_getcodoferta1(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT adata date, INOUT acodpart numeric, INOUT acodlocatie numeric, INOUT asubunitatea numeric, INOUT atipdoc numeric, INOUT acant numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCodOferta1 numeric;
begin
  BEGIN
    SELECT o1.codoferta1
    INTO vCodOferta1
    FROM oferta1 o1
        INNER JOIN oferta o ON  o.codoferta = o1.codoferta and (   o.subunitatea = aSubunitatea or  COALESCE( o.toatesubunit, 0) = 1)
    WHERE
       o1.codobiect = aCodObiect
       and (o.codlocatie = aCodLocatie or  COALESCE( o.codlocatie, 0) = 0)
       and COALESCE( aData, current_setting('PKG_GLOBALS.data0', true)) BETWEEN o.datastart AND o.dataend
       and  o.partener = aCodpart
       and  o.tipdoc = aTipDoc
       and  o1.cantmin = (SELECT max( oo1.cantmin)
                          FROM oferta1 oo1
                              INNER JOIN oferta oo ON oo.codoferta = oo1.codoferta and (oo.subunitatea = aSubunitatea or COALESCE( oo.toatesubunit, 0) = 1)
                          WHERE oo1.codobiect = aCodObiect
                                and (oo.codlocatie = aCodLocatie or COALESCE(oo.codlocatie, 0) = 0)
                                and aData BETWEEN oo.datastart AND oo.dataend
                                and  oo.partener = aCodPart
                                and  oo.tipdoc = 51
                                and  aCant &gt;= oo1.cantmin
    );
  EXCEPTION WHEN others THEN
    vCodOferta1 := 0;
  END;

  WME_Result :=  vCodOferta1;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oferta_getcodoferta1pretmin</obj_name>
  <obj_hashval>dd58f2d5d7a115e617ae752b16269c0d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oferta_getcodoferta1pretmin(acodobiect numeric, adata date)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  vCodOferta1 numeric;
  vPret       double precision;
BEGIN
  --Adina 02 septembrie 2020
  vPret       := 0.0;
  vCodOferta1 := 0;
  FOR v_rec IN
  (
    SELECT o1.codoferta1, o1.pret
    FROM   nartobj obj
          INNER JOIN nartcli acli ON  acli.codobiect = obj.codobiect and  acli.implicit = 1
          INNER JOIN oferta1 o1   ON  o1.codobiect   = obj.codobiect
          INNER JOIN oferta  o    ON  o.codoferta    = o1.codoferta  and  o.partener = acli.codpart
    WHERE o1.codobiect = aCodObiect
          and COALESCE( aData, to_date(current_setting('PKG_GLOBALS.data0', true),'dd.mm.yyyy') ) BETWEEN o.datastart AND o.dataend
          and  o.tipdoc = 51
          and (GETSUBUNITATE() = 1 or  o.subunitatea = GETSUBUNITATE())
  )
  LOOP
    IF  v_rec.pret &gt; vPret THEN
      vPret       := v_rec.Pret;
      vCodOferta1 := v_rec.codoferta1;
    END IF;
  END LOOP;

  RETURN vCodOferta1;
END ;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oferta_getcodoferta1pretmin</obj_name>
  <obj_hashval>39c36932b9189ef89f70a10e143e0484</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oferta_getcodoferta1pretmin(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT adata date)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  vCodOferta1 numeric;
  vPret       double precision;
begin
  vPret       := 0.0;
  vCodOferta1 := 0;

  FOR v_rec IN
  (
  SELECT o1.codoferta1, o1.pret
  FROM nartobj obj
      INNER JOIN nartcli acli ON  acli.codobiect = obj.codobiect and  acli.implicit = 1
      INNER JOIN oferta1 o1   ON  o1.codobiect   = obj.codobiect
      INNER JOIN oferta  o    ON  o.codoferta    = o1.codoferta  and  o.partener = acli.codpart
  WHERE
     o1.codobiect = aCodObiect
     and COALESCE( aData, current_setting('PKG_GLOBALS.data0', true)) BETWEEN o.datastart AND o.dataend
     and  o.tipdoc = 51
     and ((SELECT pkg_globals_GETSUBUNITATE.WME_RESULT FROM pkg_globals_GETSUBUNITATE(NULL,NULL)) = 1 or  o.subunitatea = (SELECT pkg_globals_GETSUBUNITATE.WME_RESULT FROM pkg_globals_GETSUBUNITATE(NULL,NULL)))
  )
  LOOP
    IF  v_rec.pret &gt; vPret
    THEN
      vPret       := v_rec.Pret;
      vCodOferta1 := v_rec.codoferta1;
    END IF;
  END LOOP;

  WME_Result :=  vCodOferta1;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oferta_getpmpoferte</obj_name>
  <obj_hashval>9101a0eaa8daf022c671a14e9eda2c2d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oferta_getpmpoferte(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT adate character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aPret double precision;
begin
  BEGIN
    SELECT COALESCE( Round( (avg( O1.PRET * UM.Paritate * Coalesce( 1 + O1.PROCADAOS / 100, 1) * (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL, o.moneda, (SELECT pkg_categconst_GetValConstanta.WME_RESULT FROM pkg_categconst_GetValConstanta(NULL, 'BancaCursPUV', (SELECT PKG_GLOBALS_GETANLUCRU.WME_RESULT FROM PKG_GLOBALS_GETANLUCRU(NULL,NULL)), (SELECT PKG_GLOBALS_GETLUNALUCRU.WME_RESULT FROM PKG_GLOBALS_GETLUNALUCRU(NULL,NULL)))), to_date( aDate, 'dd.mm.yyyy')))))::numeric, 7), 0)
    INTO aPret
    FROM oferta1 o1
        INNER JOIN oferta o  ON  o.codoferta = o1.codoferta
        INNER JOIN num1   um ON  o1.umsec    = um.codum1
    WHERE
       o1.codobiect = aCodObiect and  COALESCE( o.operat, 0) = 1 and  COALESCE( o.anulat, 0) &lt;&gt; 1 and to_date( aDate, 'dd.mm.yyyy') BETWEEN o.datastart AND o.dataend and  o.tipdoc = 51;
  EXCEPTION WHEN others THEN
    aPret := 0;
  END;

  WME_Result :=  aPret;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oferta_getpretmediuoferte</obj_name>
  <obj_hashval>30edbb7738c4629ec0545a43eed908b8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oferta_getpretmediuoferte(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT acodarticol numeric DEFAULT 0, INOUT aretgenerica boolean DEFAULT false, INOUT acodatribut numeric DEFAULT '-1'::integer, INOUT amodgenerice numeric DEFAULT 0)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aPret double precision;
begin
  IF  COALESCE( aModGenerice, 0) = 1 THEN
    BEGIN
      SELECT COALESCE( avg( Round( (O1.PRET * UM.Paritate * Coalesce( 1 + O1.PROCADAOS / 100, 1))::numeric, 7) *
                            (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT
                             FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL, o.moneda,
                                                                       (SELECT pkg_categconst_GetValConstanta.WME_RESULT FROM pkg_categconst_GetValConstanta(NULL, 'BancaCursPUV', (SELECT PKG_GLOBALS_GETANLUCRU.WME_RESULT FROM PKG_GLOBALS_GETANLUCRU(NULL,NULL)), (SELECT PKG_GLOBALS_GETLUNALUCRU.WME_RESULT FROM PKG_GLOBALS_GETLUNALUCRU(NULL,NULL)))),
                                                                       last_day( to_date( '01.' || coalesce(CASE WHEN (SELECT pkg_globals_GetLUNALUCRU.WME_RESULT FROM pkg_globals_GetLUNALUCRU(NULL,NULL)) &lt; 10 THEN '0' || coalesce(( (SELECT pkg_globals_GetLUNALUCRU.WME_RESULT FROM pkg_globals_GetLUNALUCRU(NULL,NULL)))::varchar,'')
                                                                                                                 ELSE ((SELECT pkg_globals_GetLUNALUCRU.WME_RESULT FROM pkg_globals_GetLUNALUCRU(NULL,NULL)))::varchar
                                                                                                            END ,'')
                                                                                 || '.' || coalesce(( (SELECT pkg_globals_GetanLUCRU.WME_RESULT FROM pkg_globals_GetanLUCRU(NULL,NULL)))::varchar,''), 'dd.mm.yyyy')
                                                                               )
                                                                      )
                            )
                          ), 0)
      INTO aPret
      FROM oferta1 o1
          INNER JOIN nartobj obj ON  o1.codobiect = obj.codobiect
          INNER JOIN oferta  o   ON  o.codoferta  = o1.codoferta
          INNER JOIN num1    um  ON  o1.umsec     = um.codum1
      WHERE
         obj.codarticol = COALESCE( aCodArticol, 0)
         and  COALESCE( o.operat, 0) = 1
         and  COALESCE( o.anulat, 0) &lt;&gt; 1
         and CURRENT_TIMESTAMP BETWEEN o.datastart AND o.dataend
         and  o.tipdoc = 51;
    EXCEPTION WHEN others THEN
      aPret := 0;
    END;
  ELSE
    IF aRetGenerica and  COALESCE( aCodAtribut, -1) = 0 THEN
      BEGIN
        SELECT COALESCE( avg( Round( (O1.PRET * UM.Paritate * Coalesce( 1 + O1.PROCADAOS / 100, 1))::numeric, 7) *
                              (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT
                               FROM   PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL, o.moneda,
                                                                           (SELECT pkg_categconst_GetValConstanta.WME_RESULT FROM pkg_categconst_GetValConstanta(NULL, 'BancaCursPUV', (SELECT PKG_GLOBALS_GETANLUCRU.WME_RESULT FROM PKG_GLOBALS_GETANLUCRU(NULL,NULL)), (SELECT PKG_GLOBALS_GETLUNALUCRU.WME_RESULT FROM PKG_GLOBALS_GETLUNALUCRU(NULL,NULL)))),
                                                                           last_day( to_date( '01.' || coalesce(CASE WHEN  (SELECT pkg_globals_GetLUNALUCRU.WME_RESULT FROM pkg_globals_GetLUNALUCRU(NULL,NULL)) &lt; 10 THEN '0' || coalesce(( (SELECT pkg_globals_GetLUNALUCRU.WME_RESULT FROM pkg_globals_GetLUNALUCRU(NULL,NULL)))::varchar,'')
                                                                                                                     ELSE ((SELECT pkg_globals_GetLUNALUCRU.WME_RESULT FROM pkg_globals_GetLUNALUCRU(NULL,NULL)))::varchar
                                                                                                                END ,'')
                                                                                     || '.' || coalesce(( (SELECT pkg_globals_GetanLUCRU.WME_RESULT FROM pkg_globals_GetanLUCRU(NULL,NULL)))::varchar,''), 'dd.mm.yyyy')
                                                                                   )
                                                                          )
                              )
                            ), 0)
        INTO aPret
        FROM oferta1 o1
            INNER JOIN nartobj obj ON  o1.codobiect = obj.codobiect
            INNER JOIN oferta  o   ON  o.codoferta = o1.codoferta
            INNER JOIN num1    um  ON  o1.umsec = um.codum1
        WHERE
           obj.codarticol = COALESCE( aCodArticol, 0)
           and  COALESCE( o.operat, 0) = 1
           and  COALESCE( o.anulat, 0) &lt;&gt; 1
           and CURRENT_TIMESTAMP BETWEEN o.datastart AND o.dataend
           and  o.tipdoc = 51;
      EXCEPTION WHEN others THEN
        aPret := 0;
      END;
    ELSE
      BEGIN
        SELECT COALESCE( avg( Round( (O1.PRET * UM.Paritate * Coalesce( 1 + O1.PROCADAOS / 100, 1))::numeric, 7) *
                              (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT
                               FROM   PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL, o.moneda,
                                                                           (SELECT pkg_categconst_GetValConstanta.WME_RESULT FROM pkg_categconst_GetValConstanta(NULL, 'BancaCursPUV', (SELECT PKG_GLOBALS_GETANLUCRU.WME_RESULT FROM PKG_GLOBALS_GETANLUCRU(NULL,NULL)), (SELECT PKG_GLOBALS_GETLUNALUCRU.WME_RESULT FROM PKG_GLOBALS_GETLUNALUCRU(NULL,NULL)))),
                                                                           last_day( to_date( '01.' || coalesce(CASE WHEN  (SELECT pkg_globals_GetLUNALUCRU.WME_RESULT FROM pkg_globals_GetLUNALUCRU(NULL,NULL)) &lt; 10 THEN '0' || coalesce(( (SELECT pkg_globals_GetLUNALUCRU.WME_RESULT FROM pkg_globals_GetLUNALUCRU(NULL,NULL)))::varchar,'')
                                                                                                                     ELSE ((SELECT pkg_globals_GetLUNALUCRU.WME_RESULT FROM pkg_globals_GetLUNALUCRU(NULL,NULL)))::varchar
                                                                                                                END ,'')
                                                                                     || '.' || coalesce(( (SELECT pkg_globals_GetanLUCRU.WME_RESULT FROM pkg_globals_GetanLUCRU(NULL,NULL)))::varchar,''), 'dd.mm.yyyy')
                                                                                   )
                                                                          )
                              )
                            ), 0)
        INTO aPret
        FROM oferta1 o1
            INNER JOIN oferta o  ON  o.codoferta = o1.codoferta
            INNER JOIN num1   um ON  o1.umsec    = um.codum1
        WHERE
           o1.codobiect = aCodObiect
           and  COALESCE( o.operat, 0) = 1
           and  COALESCE( o.anulat, 0) &lt;&gt; 1
           and CURRENT_TIMESTAMP BETWEEN o.datastart AND o.dataend
           and  o.tipdoc = 51;
      EXCEPTION WHEN others THEN
        aPret := 0;
      END;
    END IF;
  END IF;

  WME_Result :=  aPret;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oferta_getpretoferta</obj_name>
  <obj_hashval>556bebb2ad32da7074e9213d320fc17d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oferta_getpretoferta(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT acant numeric, INOUT adataref character varying, INOUT acodpart numeric, INOUT acodlocatie numeric, INOUT asubunitatea numeric, INOUT atipofe numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aPretOfe double precision := 0;
  dDataRef date := To_Date( aDataRef, 'dd.mm.yyyy');
begin
  BEGIN
    SELECT  DISTINCT Min( o1.pret) OVER (ORDER BY o1.cantmin )
    INTO aPretOfe
    FROM oferta1 o1
        INNER JOIN oferta o ON  o.codoferta = o1.codoferta
    WHERE
       o1.codobiect = aCodObiect
       AND dDataRef BETWEEN o.datastart AND o.dataend
       AND  COALESCE( o.partener, 0) = aCodpart
       AND (o.subunitatea = aSubunitatea OR  Coalesce( o.toatesubunit, 0) = 1)
       AND (o.codlocatie = aCodLocatie OR  Coalesce( o.codlocatie, 0) = 0)
       AND  o.tipdoc = aTipOfe
       AND  aCant &gt;= o1.cantmin;
  EXCEPTION WHEN others THEN
    aPretOfe := 0;
  END;

  WME_Result :=  aPretOfe;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oferta_ofertaval</obj_name>
  <obj_hashval>2a6341d46ce5031b941806fc0dee8169</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oferta_ofertaval(INOUT wme_result numeric, INOUT acodoferta numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  M1 numeric;
  M2 numeric;
begin
  BEGIN
    SELECT Extract( MONTH FROM O.DataStart) + 12 * Extract( Year FROM O.DataStart)
    INTO M1
    FROM oferta O
    WHERE O.Codoferta = aCodOferta;
  EXCEPTION WHEN others THEN
    M1 := 99999999999999;
  END;

  BEGIN
    SELECT Extract( MONTH FROM O.Dataend) + 12 * Extract( Year FROM O.DataEnd)
    INTO M2
    FROM oferta O
    WHERE O.Codoferta = aCodOferta;
  EXCEPTION WHEN others THEN
    M2 := 0;
  END;

  IF ((SELECT PKG_GLOBALS_GETANLUCRU.WME_RESULT FROM PKG_GLOBALS_GETANLUCRU(NULL,NULL)) * 12 + (SELECT PKG_GLOBALS_GETLUNALUCRU.WME_RESULT FROM PKG_GLOBALS_GETLUNALUCRU(NULL,NULL)) &lt;= M2)
     AND
     ((SELECT PKG_GLOBALS_GETANLUCRU.WME_RESULT FROM PKG_GLOBALS_GETANLUCRU(NULL,NULL)) * 12 + (SELECT PKG_GLOBALS_GETLUNALUCRU.WME_RESULT FROM PKG_GLOBALS_GETLUNALUCRU(NULL,NULL)) &gt;= M1)
  THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    WME_Result :=  0;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oferta_sp_deleterecord</obj_name>
  <obj_hashval>ad045c828ca9bf23b32daf5b42c76653</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oferta_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCarnetDoc  numeric;
  aNrDoc      numeric;
  aCodSubunit numeric;
  aDataDoc    date;
  aDoc        varchar;
  aTIPOFERTA  numeric;
BEGIN
  --Florin 01.06.2023 - monitor
  --Florin 31.03.2023 - sinc. Oracle
  --Florin pkg_userfirme_postlogcucommit
  perform pkg_oferta_setct_monitor('MON_28');
  PERFORM PKG_OFERTA_SP_LOCKRECORD( RecId);

  SELECT CarnetDoc, NrDoc, Subunitatea, DataStart,
         coalesce(CASE WHEN  TipDoc=50 THEN 'OC'
                       WHEN  TipDoc=51 THEN 'OF' END ,'') || coalesce(NrDoc::varchar ,'') || '/' || coalesce(To_Char(DataStart,'dd.mm.yyyy'),'') || '-' || coalesce(To_Char(DataEnd,'dd.mm.yyyy'),''),
         TIPDOC
  INTO aCarnetDoc, aNrDoc, aCodSubunit, aDataDoc, aDoc, aTIPOFERTA
  FROM OFERTA
  WHERE CodOferta = recId;
  PERFORM PKG_CFGTABLES_EXT_DELETERECORD(recId, aTIPOFERTA);

  IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_OFERTA.CT_MONITOR', true)))
  THEN
    PERFORM pkg_userfirme_postlogcucommit( 'OFERTA', current_setting('PKG_GLOBALS.USERNAME', true), 'S', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), aCodSubunit, aDataDoc, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  DELETE FROM OFERTA1 WHERE CodOferta = RecId;
  DELETE FROM OFERTA   WHERE CodOferta = RecId;

  DELETE FROM CMDAPROBARI WHERE CODDOC = RECID AND  TIPDOC = aTIPOFERTA;

  PERFORM PKG_CARNETEDOC_RELEASENUMARDOC( aCarnetDoc, aNrDoc);
  PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE( aCarnetDoc);

  PERFORM NotifyModif( 2, RECID, 'OFERTA');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oferta_sp_insertrecord</obj_name>
  <obj_hashval>ec475ac50bb6bee5f414b32476bd54e3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oferta_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 03.04.2023
  --Florin 31.03.2023 - sinc. Oracle
  INSERT INTO TMP_OFERTA (CodOferta) VALUES(0);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD((SELECT wme_result FROM PKG_GLOBALS_GetTipOferta(NULL, NULL)));
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oferta_sp_lockrecord</obj_name>
  <obj_hashval>e81d5e1fffb327019ab691b03c8e6de8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oferta_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodOferta INTO Tmp FROM OFERTA WHERE CodOferta = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oferta_umple_tmp_selartofe</obj_name>
  <obj_hashval>9489ed39b2758df962935b165ccfa9c1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oferta_umple_tmp_selartofe(ptipofe numeric, pdataref character varying, pcodpart numeric, pcodlocatie numeric, psubunit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vDataRef      date := To_Date( pDataRef, 'dd.mm.yyyy');
  aCodIdentPart varchar;
begin
  DELETE FROM TMP_SelArtOfe;

  BEGIN
    SELECT CODIDENT
    INTO aCodIdentPart
    FROM NPART P, NCLASEP CLP
    WHERE
       CODPART = pCodPart AND  COALESCE( P.CODCLASA, 0) = CLP.CODCLASEP;
  EXCEPTION WHEN OTHERS THEN
    aCodIdentPart := '0';
  END;

  IF  pCodPart &lt;&gt; 0 AND  pCodLocatie &lt;&gt; 0 THEN
    INSERT INTO TMP_SelArtOfe(CodOferta1, CodObiect)
    SELECT O1.CodOferta1, O1.CodObiect
    FROM OFERTA O INNER JOIN OFERTA1 O1 ON  O1.CodOferta = O.CodOferta
    WHERE
       O.Operat = 1
       AND  O.Anulat &lt;&gt; 1
       AND  O.Blocat &lt;&gt; 1
       AND  O.TipDoc = pTipOfe
       AND ((O.DataCerere IS NULL) OR (OFERTAT = 1))
       AND  O.DataStart &lt;= vDataRef AND  O.DataEnd &gt;= vDataRef
       AND  COALESCE( O.Partener, 0) = pCodPart
       AND  COALESCE( O.CodLocatie, 0) = pCodLocatie
       AND (O.ToateSubunit = 1 OR  O.Subunitatea = pSubunit) ;
  END IF;

  IF  pCodPart &lt;&gt; 0 THEN
    INSERT INTO TMP_SelArtOfe(CodOferta1, CodObiect)
    SELECT O1.CodOferta1, O1.CodObiect
    FROM OFERTA O INNER JOIN OFERTA1 O1 ON  O1.CodOferta = O.CodOferta
    WHERE
       O.Operat = 1
       AND  O.Anulat &lt;&gt; 1
       AND  O.Blocat &lt;&gt; 1
       AND  O.TipDoc = pTipOfe
       AND ((O.DataCerere IS NULL) OR (OFERTAT = 1) )
       AND  O.DataStart &lt;= vDataRef AND  O.DataEnd &gt;= vDataRef
       AND  COALESCE( O.Partener, 0) = pCodPart
       AND  COALESCE( O.CodLocatie, 0) = 0
       AND (O.ToateSubunit = 1 OR  O.Subunitatea = pSubunit)
       AND  NOT  EXISTS (SELECT TMP.CODOFERTA1 FROM TMP_SelArtOfe TMP WHERE TMP.CODOFERTA1 = O1.CODOFERTA1);
  END IF;

  IF  pCodPart = 0 THEN
    INSERT INTO TMP_SelArtOfe(CodOferta1, CodObiect)
    SELECT O1.CodOferta1, O1.CodObiect
    FROM OFERTA O INNER JOIN OFERTA1 O1 ON  O1.CodOferta = O.CodOferta
    WHERE
       O.Operat = 1
       AND  O.Anulat &lt;&gt; 1
       AND  O.Blocat &lt;&gt; 1
       AND  O.TipDoc = pTipOfe
       AND ((O.DataCerere IS NULL) OR (OFERTAT = 1) )
       AND  O.DataStart &lt;= vDataRef AND  O.DataEnd &gt;= vDataRef
       AND  COALESCE( O.Partener, 0) &gt; 0
       AND (O.ToateSubunit = 1 OR  O.Subunitatea = pSubunit) ;
  END IF;

  INSERT INTO TMP_SelArtOfe(CodOferta1, CodObiect)
  SELECT O1.CodOferta1, O1.CodObiect
  FROM OFERTA O
      INNER JOIN OFERTA1 O1   ON  O1.CodOferta   = O.CodOferta
      LEFT  JOIN NCLASEP CLAP ON  CLAP.CODCLASEP = O.CODCLASEP
  WHERE
     O.Operat = 1
     AND  O.Anulat &lt;&gt; 1
     AND  O.Blocat &lt;&gt; 1
     AND  O.TipDoc = pTipOfe
     AND ((O.DataCerere IS NULL) OR (OFERTAT = 1) )
     AND  O.DataStart &lt;= vDataRef AND  O.DataEnd &gt;= vDataRef
     AND (COALESCE( O.Partener, 0) = 0 AND (COALESCE( O.CODCLASEP, 0) = 0)  OR  INSTRB(aCodIdentPart, CLAP.CODIDENT) = 1)
     AND (O.ToateSubunit = 1 OR O.Subunitatea = pSubunit)
     AND  NOT  EXISTS (SELECT TMP.CODOFERTA1 FROM TMP_SelArtOfe TMP WHERE TMP.CODOFERTA1 = O1.CODOFERTA1);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oferta_updatecomandaxoferta</obj_name>
  <obj_hashval>4bc919819e9ac7bafada54057b03b5ba</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oferta_updatecomandaxoferta(INOUT wme_result character varying, INOUT pcodoferta numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  V_REC       RECORD;
  listaComenziDeModificat numeric[];
  codComandaModificata numeric(20);
  valDoc numeric(20,7);
  vPretLinie numeric(20,7);
  listaComenziModificate Varchar(3000);
  listaComenziBlocate Varchar(3000);
  existaComenziBLocate boolean;
  tmpCod numeric(20);
  it numeric;

  lista_comenzi CURSOR FOR  select cmd1.codcomanda1 as codComanda1,
              cmd.codcomanda as codComanda,
              cmd.nrdoc as nrDoc,
              cmd.datadoc as dataDoc,
              ofr1.codoferta1 as codOferta1,
              cmd1.addim as adDim,
              cmd1.PU as cmdPU,
              cmd1.pretorig as cmdPretOrig,
              ofr1.pret as ofrPret,
              obj.rotunjire as rotunjire
         from comanda cmd
         join comanda1 cmd1
           on cmd1.codcomanda = cmd.codcomanda
         join oferta1 ofr1
           on ofr1.codoferta1 = cmd1.codoferta1
         join oferta ofr
           on ofr.codoferta = ofr1.codoferta
         join npart part
           on part.codpart = cmd.partener
        join nartobj obj on obj.codobiect = cmd1.codobiect
        where ofr.codoferta = pCodOferta
          and cmd1.termen between ofr.datastart and
              ofr.dataend
          and cmd1.restacceptat &gt; 0
          and coalesce(cmd.anulat, 0) = 0
          and coalesce(cmd.inchisa, 0) = 0
          and coalesce(part.preofefurnvar, 0) = 1
          and ofr.partener = cmd.partener
          and ofr1.pret &lt;&gt; cmd1.pretorig
          and cmd.tipdoc = 8
         order by cmd1.codcomanda;
BEGIN
  --Florin 24.04.2024 - fixat 65459
  --Bogdan 29.09.2022 - 55428 : Oferte furnizori - data/termen
  codComandaModificata := -1;
  valDoc := 0.0;
  listaComenziModificate := '';
  listaComenziBlocate :='';
  existaComenziBLocate := false;
  it := 0;
  for v_rec in lista_comenzi
  loop
    if codComandaModificata = -1 or codComandaModificata != v_rec.codComanda then
      codComandaModificata := v_rec.codComanda;
      begin
      perform lockdoceditat('COMANDA', 'CodComanda', v_rec.codComanda, 0);
      listaComenziDeModificat[it] := v_rec.codComanda;
      it := it+1;
      exception
         when others  then
           listaComenziBlocate := listaComenziBlocate || v_rec.nrdoc ||'/'|| to_char(v_rec.datadoc,'dd.mm.yyyy')||'; ';
           existaComenziBLocate := true;
      end;
    end if;
  end loop;
  if existaComenziBLocate then
    wme_result := 'ERR#$'||listaComenziBlocate;
  else
    codComandaModificata := -1;
    for v_rec in lista_comenzi
    loop
      if codComandaModificata = -1 then
        codComandaModificata := v_rec.codComanda;
        listaComenziModificate := v_rec.nrdoc ||'/'|| to_char(v_rec.datadoc,'dd.mm.yyyy');
      else
        if codComandaModificata != v_rec.codComanda then
          select sum(pkg_oferta_roundpret(((100 + coalesce(cmd1.procdisc,0)) / 100) * cmd1.cantacceptat * cmd1.pu, obj.rotunjire)) into valDoc
          from comanda1 cmd1
          join nartobj obj on obj.codobiect = cmd1.codobiect
          where cmd1.codcomanda = codComandaModificata
                and coalesce(cmd1.anulat,0) = 0;
           update comanda cmd set valoare = valDoc where cmd.codcomanda = codComandaModificata;
          codComandaModificata := v_rec.codComanda;
          listaComenziModificate := listaComenziModificate || '; '|| v_rec.nrdoc ||'/'|| to_char(v_rec.datadoc,'dd.mm.yyyy');
        end if;
      end if ;

      vPretLinie := pkg_oferta_roundpret(((100 + coalesce(v_rec.addim,0)) / 100) * v_rec.ofrpret, v_rec.rotunjire);

      update comanda1 cmd1
         set pretorig = v_rec.ofrpret,
             pu = vPretLinie
         where cmd1.codcomanda1 = v_rec.codcomanda1;
    end loop;
    if codComandaModificata != -1 then
          select sum(pkg_oferta_roundpret(((100 + coalesce(cmd1.procdisc,0)) / 100) * cmd1.cantacceptat * cmd1.pu, obj.rotunjire)) into valDoc
          from comanda1 cmd1
           join nartobj obj on obj.codobiect = cmd1.codobiect
          where cmd1.codcomanda = codComandaModificata
                and coalesce(cmd1.anulat,0) = 0;
          update comanda cmd set valoare = valDoc where codcomanda = codComandaModificata;
     end if;
       wme_result :=  listaComenziModificate ;
  end if;
  IF (listaComenziDeModificat) IS NOT NULL THEN
    foreach it in array listaComenziDeModificat loop
      perform unlockdoceditat('COMANDA', it, current_setting('PKG_GLOBALS.USERID', true)::numeric);
    end loop;
  END IF;

end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_onorarecomenzi_clr_lck_comenzi</obj_name>
  <obj_hashval>974e000b32a5ebb0967bc8e0bff5955a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_onorarecomenzi_clr_lck_comenzi()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  UPDATE Comanda SET UserIDBlocaj = NULL WHERE UserIDBlocaj = TO_NUMBER((current_setting('PKG_GLOBALS.UserID', true)),'999999999999999999');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_onorarecomenzi_get_tmp_comenzi</obj_name>
  <obj_hashval>721a999a68b673f9de015d9d7c699d01</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_onorarecomenzi_get_tmp_comenzi(sursapu numeric, carepu numeric, dataref character varying, arez numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Florin 26.08.2022 - sinc. Oracle
  PERFORM PKG_ONORARECOMENZI_GET_TMP_OperLivr_Articole(aRez);
  PERFORM PKG_ONORARECOMENZI_GET_TMP_OperLivr_Comenzi();
  IF SursaPU = 1 THEN
    IF CarePU = 0 THEN
      FOR v_rec IN (SELECT c1.codcomanda1, c1.codobiect, c.codclient, c.codsediu
                    FROM TMP_OnorCom_Comenzi c
                         INNER JOIN TMP_OnorCom_Articole c1 ON c1.codcomanda = c.codcomanda
                   )
      LOOP
        UPDATE TMP_OnorCom_Articole
        SET pret = (SELECT pkg_oferta_GetPretOfertaPartLocObj.WME_RESULT
                    FROM   pkg_oferta_GetPretOfertaPartLocObj (NULL, v_rec.codclient, v_rec.codsediu, v_rec.CodObiect, DataRef, 50))
        WHERE
          codcomanda1 = v_rec.codcomanda1;
      END LOOP;
    ELSE
      FOR v_rec IN (SELECT c1.codcomanda1, c1.codobiect, c.codclient, c.codsediu
                    FROM TMP_OnorCom_Comenzi c
                         INNER JOIN TMP_OnorCom_Articole c1 ON c1.codcomanda = c.codcomanda
                    WHERE COALESCE (c1.pret, 0) = 0
                   )
      LOOP
        UPDATE TMP_OnorCom_Articole
        SET pret = (SELECT pkg_oferta_GetPretOfertaPartLocObj.WME_RESULT
                    FROM   pkg_oferta_GetPretOfertaPartLocObj (NULL, v_rec.codclient, v_rec.codsediu, v_rec.CodObiect, DataRef, 50))
        WHERE
          codcomanda1 = v_rec.codcomanda1;
      END LOOP;
    END IF;
  ELSE
    IF SursaPU = 2 THEN
      IF CarePU = 0 THEN
        FOR v_rec IN (SELECT c1.codcomanda1, pm.lei
                      FROM TMP_OnorCom_Comenzi          c
                          INNER JOIN TMP_OnorCom_Articole c1 ON c1.codcomanda = c.codcomanda
                          INNER JOIN npart                p  ON c.codclient   = p.codpart
                          LEFT  JOIN pretm                pm ON pm.codcatpret = p.codcategpret and pm.subunitatea = c.subunitatea and pm.codobiect = c1.codobiect
                     )
        LOOP
          UPDATE TMP_OnorCom_Articole SET pret = v_rec.lei WHERE codcomanda1 = v_rec.codcomanda1;
        END LOOP;
      ELSE
        FOR v_rec IN (SELECT c1.codcomanda1, pm.lei
                      FROM TMP_OnorCom_Comenzi            c
                          INNER JOIN TMP_OnorCom_Articole c1 ON c1.codcomanda = c.codcomanda
                          INNER JOIN npart                p  ON c.codclient   = p.codpart
                          LEFT  JOIN pretm                pm ON pm.codcatpret = p.codcategpret and pm.subunitatea = c.subunitatea and pm.codobiect = c1.codobiect
                      WHERE COALESCE (c1.pret, 0) = 0)
        LOOP
          UPDATE TMP_OnorCom_Articole SET pret = v_rec.lei WHERE codcomanda1 = v_rec.codcomanda1;
        END LOOP;
      END IF;
    ELSE
      IF SursaPU = 3 THEN
        IF CarePU = 0 THEN
          FOR v_rec IN (SELECT c1.codcomanda1, pm.lei
                        FROM TMP_OnorCom_Comenzi            c
                            INNER JOIN TMP_OnorCom_Articole c1 ON c1.codcomanda = c.codcomanda
                            LEFT JOIN pretm                 pm ON pm.implicit = 1 and pm.subunitatea = c.subunitatea and pm.codobiect = c1.codobiect
                       )
          LOOP
            UPDATE TMP_OnorCom_Articole SET pret = v_rec.lei WHERE codcomanda1 = v_rec.codcomanda1;
          END LOOP;
        ELSE
          FOR v_rec IN (SELECT c1.codcomanda1, pm.lei
                        FROM TMP_OnorCom_Comenzi            c
                            INNER JOIN TMP_OnorCom_Articole c1 ON c1.codcomanda = c.codcomanda
                            LEFT JOIN pretm                 pm ON pm.implicit = 1 and pm.subunitatea = c.subunitatea and pm.codobiect = c1.codobiect
                       )
          LOOP
            UPDATE TMP_OnorCom_Articole SET pret = v_rec.lei WHERE codcomanda1 = v_rec.codcomanda1;
          END LOOP;
        END IF;
      END IF;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_onorarecomenzi_get_tmp_grupcom</obj_name>
  <obj_hashval>9ab1c7d39b65365279db9470c58eb641</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_onorarecomenzi_get_tmp_grupcom()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  T2 RECORD;
  C  RECORD;
begin
  UPDATE TMP_OnorCom_Comenzi  SET idxgrup = 0;
  UPDATE TMP_OnorCom_Articole SET idxgrup = 0;

  FOR T2 IN (SELECT ctid XROWID,
                    Dense_Rank() OVER (ORDER BY CODCLIENT, CODSEDIU, CODFISCAL, CODAGENT, CODDELEGAT, CODPERS, FARATRANSPORT, CODMIJLTRANSP, CODTRASEULIVR,
                                                CODMONEDA, SUBUNITATEA, SCADENTAV, CURS, TIPDOC, TIPDOCAMB) IDXGRUP
             FROM TMP_OnorCom_Comenzi C
             WHERE C.MODDOC = 3 AND  C.CODDOC = 0 AND  Coalesce( C.GDI, 0) = 0
               AND  EXISTS (SELECT 1 FROM TMP_OnorCom_Articole A WHERE A.LivrStoc &gt; 0 AND  A.CodComanda = C.CodComanda)
            )
  LOOP
    UPDATE  TMP_OnorCom_Comenzi T1 SET IDXGRUP = T2.IDXGRUP WHERE T1.ctid = T2.xROWID;
  END LOOP;

  FOR C IN (SELECT * FROM TMP_OnorCom_Comenzi C) LOOP
    UPDATE  TMP_OnorCom_Articole A SET IDXGRUP = C.IDXGRUP WHERE A.CodComanda = C.CodComanda;
  END LOOP;

  INSERT INTO TMP_OnorCom_GrupCom(IdxGrup, TipDoc, TipDocAmb, A1, A2, A3, A4, A5, A6)
  SELECT IdxGrup, Min( TipDoc), Min( TipDocAmb), Sum( A1), Sum( A2), Sum( A3), Sum( A4), Sum( A5), Sum( A6)
  FROM TMP_OnorCom_Comenzi WHERE idxgrup &gt; 0 GROUP BY idxgrup;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_onorarecomenzi_get_tmp_grupcombycod</obj_name>
  <obj_hashval>992f310f6b762317ad43240eee7de8b4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_onorarecomenzi_get_tmp_grupcombycod()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  T2 RECORD;
  CR RECORD;
begin
  UPDATE TMP_OnorCom_Comenzi  SET idxgrup = 0;
  UPDATE TMP_OnorCom_Articole SET idxgrup = 0;

  FOR T2 IN (SELECT C.ctid XROWID,
                    Dense_Rank() over(ORDER BY CODCLIENT, CODSEDIU, CODFISCAL, CODAGENT, CODDELEGAT, CODPERS, FARATRANSPORT, CODMIJLTRANSP, CODTRASEULIVR,
                                               CODMONEDA, SUBUNITATEA, SCADENTAV, CURS, TIPDOC, TIPDOCAMB) IDXGRUP
             FROM TMP_OnorCom_Comenzi C
                  INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE::numeric = C.CODCOMANDA AND TMP.FILTRU = 'CODCOMANDA'
             WHERE C.MODDOC = 3 AND C.CODDOC = 0 AND Coalesce (C.GDI, 0) = 0
               AND EXISTS (SELECT 1 FROM TMP_OnorCom_Articole A WHERE A.LivrStoc &gt; 0 AND A.CodComanda = C.CodComanda)
            )
  LOOP
    UPDATE TMP_OnorCom_Comenzi T1 SET IDXGRUP = T2.IDXGRUP WHERE T1.ctid = T2.xROWID;
  END LOOP;

  FOR CR IN (SELECT * FROM TMP_OnorCom_Comenzi C) LOOP
    UPDATE TMP_OnorCom_Articole A SET IDXGRUP = CR.IDXGRUP WHERE A.CodComanda = CR.CodComanda;
  END LOOP;

  INSERT INTO TMP_OnorCom_GrupCom (IdxGrup, TipDoc, TipDocAmb, A1, A2, A3, A4, A5, A6)
  SELECT C.IdxGrup, Min (C.TipDoc) , Min (C.TipDocAmb) , Sum (C.A1) , Sum (C.A2) , Sum (C.A3) , Sum (C.A4) , Sum (C.A5) , Sum (C.A6)
  FROM TMP_OnorCom_Comenzi C
       INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE::numeric = C.CODCOMANDA AND TMP.FILTRU = 'CODCOMANDA'
  WHERE C.idxgrup &gt; 0
  GROUP BY C.idxgrup;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_onorarecomenzi_getpdatatermlivr</obj_name>
  <obj_hashval>50e33a4a1235ec752d95870f8476b2cc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_onorarecomenzi_getpdatatermlivr(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_ONORARECOMENZI.pDataTermLivr', true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_onorarecomenzi_getpflagclaseart</obj_name>
  <obj_hashval>d5ecf1a19766d628f7a1d9ab17df6c7a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_onorarecomenzi_getpflagclaseart(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_ONORARECOMENZI.pFlagClaseArt', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_onorarecomenzi_getpflagtermlivr</obj_name>
  <obj_hashval>3fa144d5f825be2290815cd4fc75948d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_onorarecomenzi_getpflagtermlivr(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_ONORARECOMENZI.pFlagTermLivr', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_onorarecomenzi_pdatasys</obj_name>
  <obj_hashval>dfd09a841c7e3955a78984d4f043e9a9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_onorarecomenzi_pdatasys(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_ONORARECOMENZI.pDataSys', true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_onorarecomenzi_pdatatermlivr</obj_name>
  <obj_hashval>9c39b6e4797277b934cb669fa7144564</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_onorarecomenzi_pdatatermlivr(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_ONORARECOMENZI.pDataTermLivr', true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_onorarecomenzi_pflagclaseart</obj_name>
  <obj_hashval>c2f177a80a11d927bfa428f0963a391f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_onorarecomenzi_pflagclaseart(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_ONORARECOMENZI.pFlagClaseArt', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_onorarecomenzi_pflagtermlivr</obj_name>
  <obj_hashval>2e29fa96f228176ea44f79bb7dab9ec0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_onorarecomenzi_pflagtermlivr(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_ONORARECOMENZI.pFlagTermLivr', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_onorarecomenzi_rezervare_stoc</obj_name>
  <obj_hashval>1c6dc004b036e9d17f296c46635fdac7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_onorarecomenzi_rezervare_stoc(INOUT pcodobiect numeric, INOUT pcodioart numeric, INOUT pcodgest numeric, INOUT pmg numeric, INOUT pdatalivr date, INOUT pcant numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCursor REFCURSOR;
  vCantRest   numeric;
  vCantRez    numeric;
  vCantPrel   numeric;
  vCodnirstoc numeric;
  vCodnirser  numeric;
  vDataMax    date := pDataLivr;
BEGIN
  --Bogdan 25.01.2021
  vCantRest := pCant;
  vCantRez  := 0;
  OPEN vCursor for execute
           'SELECT ns.codnirstoc, coalesce(nse.codnirser,0) codnirser
            FROM nirstoc ns
                 INNER JOIN nir    n   ON n.codnir       = ns.codnir
                 LEFT  JOIN nirser nse ON nse.codnirstoc = ns.codnirstoc
                 LEFT  JOIN nserii s   ON s.codserie     = nse.codserie
            WHERE ns.rest &gt; 0 AND ns.codobiect = $1 AND ns.codioart = $2 AND n.gest = $3 AND n.datanir &lt;= $4
            ORDER BY ns.dataachiz ' || CASE WHEN pMG = 2 THEN 'DESC' ELSE 'ASC' END
              ||', CASE WHEN ns.tipserie &gt; 0 THEN s.serie ELSE NULL END ASC'
            USING pCodObiect, pCodIOArt, pCodGest, vDataMax;
  LOOP
    FETCH vCursor INTO vCodnirstoc, vCodnirser;

    IF NOT FOUND THEN EXIT; END IF;

    vCantPrel := (SELECT pkg_globals_GET_STOC_REAL_EXT.WME_RESULT FROM pkg_globals_GET_STOC_REAL_EXT (NULL,vCodnirstoc, vCodnirser,NULL));

    IF vCantRest &gt; 0 AND vCantPrel &gt; 0 THEN
      IF vCantPrel  &gt; vCantRest THEN
        vCantPrel := vCantRest;
      END IF;

      PERFORM pkg_globals_LOCK_STOC_CANT (vCodnirstoc, vCodnirser, vCantPrel);

      INSERT INTO TMP_OnorCom_StocBuf (codnirstoc, codnirser, preluat) VALUES (vCodnirstoc, vCodnirser, vCantPrel);

      vCantRez  := vCantRez  + vCantPrel;
      vCantRest := vCantRest - vCantPrel;
    END IF;

    EXIT  WHEN vCantRest = 0;
  END LOOP;

  pCant := vCantRez;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_onorarecomenzi_setpflagtermlivr</obj_name>
  <obj_hashval>86ee2ca28d0fadbac61fd0b681deb338</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_onorarecomenzi_setpflagtermlivr(apflagtermlivr numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_ONORARECOMENZI.pFlagTermLivr',to_char(apFlagTermLivr,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_onorarecomenzi_settermen</obj_name>
  <obj_hashval>e237d76cfbf881804abd3aa97079a6c0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_onorarecomenzi_settermen(atermendela character varying, atermenpanala character varying DEFAULT NULL::character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 18.05.2021 - sinc.Oracle din 17.05.2021 - doar martor la zi
  BEGIN
    perform set_config('PKG_ONORARECOMENZI.pDataSys'           , to_char(DATE_TRUNC('DAY', CURRENT_TIMESTAMP),'dd.mm.yyyy')                 , false);
    perform set_config('PKG_ONORARECOMENZI.pDataTermLivrDeLa'  , to_char(To_Date( COALESCE( aTermenDeLa  , 'X'), 'DD.MM.YYYY'),'dd.mm.yyyy'), false);
    perform set_config('PKG_ONORARECOMENZI.pDataTermLivrPanaLa', to_char(To_Date( COALESCE( aTermenPanaLa, 'X'), 'DD.MM.YYYY'),'dd.mm.yyyy'), false);
    perform set_config('PKG_ONORARECOMENZI.pFlagTermLivr'      , to_char(1,'999999999999999999')                                            , false);
  EXCEPTION WHEN OTHERS THEN
    perform set_config('PKG_ONORARECOMENZI.pDataTermLivrDeLa'  , to_char(DATE_TRUNC('DAY', CURRENT_TIMESTAMP),'dd.mm.yyyy'), false);
    perform set_config('PKG_ONORARECOMENZI.pDataTermLivrPanaLa', to_char(DATE_TRUNC('DAY', CURRENT_TIMESTAMP),'dd.mm.yyyy'), false);
    perform set_config('PKG_ONORARECOMENZI.pFlagTermLivr'      , to_char(0,'999999999999999999')                           , false);
  END;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_operatii_clasa_op</obj_name>
  <obj_hashval>945502b2d3697de4c3569ea41b0161d0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_operatii_clasa_op(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_OPERATII.CLASA_OP', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_operatii_conditieclasa</obj_name>
  <obj_hashval>96f95c9bb842c63ba0c82afc5d497b6a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_operatii_conditieclasa(INOUT wme_result numeric, INOUT aclasa numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  TO_NUMBER((current_setting('PKG_OPERATII.CLASA_OP', true)),'999999999999999999') = 0 THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    IF  aCLASA = TO_NUMBER((current_setting('PKG_OPERATII.CLASA_OP', true)),'999999999999999999') THEN
      WME_Result :=  1;
      RETURN;
    ELSE
      WME_Result :=  0;
      RETURN;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_operatii_setclasa_op</obj_name>
  <obj_hashval>ef9be6c937312d69c0a480e083559050</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_operatii_setclasa_op(aclasa_op numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_OPERATII.CLASA_OP',to_char(aCLASA_OP,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_operatii_setclasaop</obj_name>
  <obj_hashval>13ca292b57b5d93a9324a0b619c3c79e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_operatii_setclasaop(aclasa numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_OPERATII.CLASA_OP',to_char(aCLASA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_operatii_sp_deleterecord</obj_name>
  <obj_hashval>096c094b43b2a5452425e8596cf47a5e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_operatii_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_OPERATII_SP_LOCKRECORD( RecId);
  DELETE FROM NOPER  WHERE CodOp = RecId;
  DELETE FROM NOPER1 WHERE CodOp = RecId;
  PERFORM NotifyModif( 2, RECID, 'NOPER');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_operatii_sp_gotorecord</obj_name>
  <obj_hashval>9e50ba4bfddd9a6319b6158428f3755a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_operatii_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 14.03.2025 - sinc. Oracle
  --Florin 23.09.2022 - fixat 55689
  --Florin 20.09.2022 - fixat 55619
  INSERT INTO TMP_NOPER( CodOp, CodExtern, Denumire, ClasaOp, Tip, Activ, CodServiciu, CodTarif,
                           LocMunca,Marcaauto,Modelauto,Facturabil,Durata, Ore, CodTipLucrare, Subunitatea, Codprestatie)
    ( SELECT CodOp, CodExtern, Denumire, ClasaOp, Tip, Activ, CodServiciu, CodTarif,
             LocMunca,Marcaauto,Modelauto,Facturabil,Durata, Round(Durata/60, 4), CodTipLucrare, Subunitatea, Codprestatie
   FROM NOPER WHERE CodOp = RecId
  );

  INSERT INTO TMP_NOPER1(Codop1, CODOP, CODOBIECT, CANT, UMSEC, PRET, DENUM, DENOBIECT)
  (SELECT O.Codop1, O.CODOP, O.CODOBIECT, O.CANT, O.UMSEC, O.PRET, U.DEN_UM DENUM, J.Denumire DENOBIECT
   FROM NOper1 O
        LEFT JOIN NUM     U ON  U.Codum     = O.UMSEC
        LEFT JOIN NARTOBJ J ON  J.Codobiect = O.CodObiect
   WHERE O.CODoP = RecId ORDER BY O.Codop1
  );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_operatii_sp_insertrecord</obj_name>
  <obj_hashval>eced3217dc716cea8058e706302c200d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_operatii_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NOPER(CodOp) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_operatii_sp_lockrecord</obj_name>
  <obj_hashval>1905927a0b4e829bf20c972f5ed91ff1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_operatii_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodOp INTO Tmp FROM NOPER WHERE CodOp = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_operatii_sp_postrecords</obj_name>
  <obj_hashval>4a29ea43bf3736ab09a8d238d758be09</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_operatii_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Florin 14.03.2025 - sinc. Oracle
  IF  Operation = 0 THEN
    SELECT CodOp INTO RecId FROM TMP_NOPER;

    UPDATE NOPER
    SET
    (CodExtern, Denumire, ClasaOp, Tip, Activ, CodServiciu, CodTarif, LocMunca, Marcaauto, Modelauto, Facturabil, Durata, CodTipLucrare, Subunitatea, CodPrestatie)
    =
    (SELECT CodExtern, Denumire, ClasaOp, Tip, Activ, CodServiciu, CodTarif, LocMunca, Marcaauto, Modelauto, Facturabil, Durata, CodTipLucrare, Subunitatea, CodPrestatie
     FROM TMP_NOPER
    )
    WHERE
     CodOp = RecId;

    DELETE FROM NOper1 WHERE CODOp = RecID and CodOp1 NOT IN (SELECT CODOp1 FROM TMP_NOper1);

    FOR v_rec IN (SELECT * FROM TMP_NOper1 WHERE CODOp1 &lt; 0) LOOP
      INSERT INTO NOPER1(Codop1, CODOP, CODOBIECT, CANT, UMSEC, PRET)
      VALUES(NEXTVAL('SEQ_NOPER1_CODOP1'), RecId, V_REC.CODOBIECT, V_REC.CANT, V_REC.UMSEC, V_REC.PRET);
    END LOOP;

    FOR v_rec IN (SELECT * FROM TMP_NOper1 WHERE CODOp1 &gt; 0) LOOP
      UPDATE NOPER1
      SET
      CODOBIECT = V_REC.CODOBIECT,
      CANT      = V_REC.CANT,
      UMSEC     = V_REC.UMSEC,
      PRET      = V_REC.PRET
      WHERE
       CodOp1 = V_Rec.Codop1;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_NOPER_CODOP') INTO RecId;

    INSERT INTO NOPER(CodOp, CodExtern, Denumire, ClasaOp, Tip, Activ, CodServiciu, CodTarif, LocMunca, Marcaauto, Modelauto, Facturabil, Durata, CodTipLucrare, Subunitatea, CodPrestatie)
    (SELECT RecId, CodExtern, Denumire, ClasaOp, Tip, Activ, CodServiciu, CodTarif, LocMunca, Marcaauto, Modelauto, Facturabil, Durata, CodTipLucrare, Subunitatea, CodPrestatie
     FROM TMP_NOPER
    );

    FOR v_rec IN (SELECT * FROM TMP_NOper1 WHERE CODOp1 &lt; 0) LOOP
      INSERT INTO NOPER1(Codop1, CODOP, CODOBIECT, CANT, UMSEC, PRET)
      VALUES(NEXTVAL('SEQ_NOPER1_CODOP1'), RecId, V_REC.CODOBIECT, V_REC.CANT, V_REC.UMSEC, V_REC.PRET);
    END LOOP;
  END IF;

  PERFORM NotifyModif( OPERATION, RECID, 'NOPER');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oportunitati_adaugacoddoc</obj_name>
  <obj_hashval>f0ad850900bb71ce9896a4493daf6d6a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oportunitati_adaugacoddoc(acodoportunitate numeric, acoddoc numeric, atipdoc numeric, aoldcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vVenitEstimat numeric;
  aTask         varchar;
  TaskFirma     numeric;
BEGIN
  --Adina 03.02.2021
  SELECT COALESCE( (fnc_GetValConstanta('TaskFirma', getANLUCRU(), getlunalucru())), '0')::numeric
  INTO TaskFirma;

  CASE aTipDoc
    WHEN 18 THEN
      SELECT coalesce(Sum(CANTACCEPTAT*PU),0) INTO vVenitEstimat FROM Comanda1 WHERE CodComanda = aCodDoc;
      UPDATE Oportunitati SET CodComanda = aCodDoc, VenitEst = vVenitEstimat WHERE CodOportunitate = aCodOportunitate;
    WHEN 34 THEN
      SELECT coalesce(Sum(CANT*PRET),0) INTO vVenitEstimat FROM Contract1 WHERE CodContract = aCodDoc;
      UPDATE Oportunitati SET CodContract = aCodDoc, VenitEst = vVenitEstimat WHERE CodOportunitate = aCodOportunitate;
      if aOldCodDoc &gt; 0 then
        update contract set anulat = 1 where codcontract = aOldCodDoc;
      end if;
    WHEN 27 THEN
      SELECT coalesce(Sum(CANT*PRET),0) INTO vVenitEstimat FROM Contract1 WHERE CodContract = aCodDoc;
      UPDATE Oportunitati SET CodContract = aCodDoc, VenitEst = vVenitEstimat WHERE CodOportunitate = aCodOportunitate;
      if aOldCodDoc &gt; 0 then
        update contract set anulat = 1 where codcontract = aOldCodDoc;
      end if;
    WHEN 50 THEN
      SELECT coalesce(Sum(CANTMIN*PRET),0) INTO vVenitEstimat FROM Oferta1 WHERE CodOferta = aCodDoc;
      UPDATE Oportunitati SET CodOferta = aCodDoc, VenitEst = vVenitEstimat WHERE CodOportunitate = aCodOportunitate;
      if aOldCodDoc &gt; 0 then
        update oferta set anulat = 1 where codoferta = aOldCodDoc;
      end if;
    WHEN 54 THEN
      UPDATE Oportunitati SET CodTask = aCodDoc WHERE CodOportunitate = aCodOportunitate;
    WHEN -54 THEN
      if TaskFirma = 1 then
        Select Executant||'-'||to_char(DataTask,'dd.mm.yyyy') into aTask from SetTask where CodTask = aCodDoc;
      else
        Select Executant||'-'||to_char(DataTask,'dd.mm.yyyy') into aTask from WinMAdmin.SetTask where CodTask = aCodDoc;
      end if;
      UPDATE Oportunitati1     SET CodTask = aCodDoc               WHERE CodOportunitate1 = aCodOportunitate;
      UPDATE TMP_Oportunitati1 SET CodTask = aCodDoc, Task = aTask WHERE CodOportunitate1 = aCodOportunitate;
  END CASE;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oportunitati_carnetdoc_i</obj_name>
  <obj_hashval>a858d51d099d6dbef9903cce40968911</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oportunitati_carnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_OPORTUNITATI.CARNETDOC_I', true)),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oportunitati_ct_monitor</obj_name>
  <obj_hashval>74f8f69d85bac99fa29e8f4a6226fb5b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oportunitati_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_OPORTUNITATI.CT_MONITOR'));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_55';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oportunitati_docommit</obj_name>
  <obj_hashval>d5ad895826c4296034577d2e8cc4a75f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oportunitati_docommit(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_OPORTUNITATI.DoCommit'));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := true;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oportunitati_getcarnetdoc_i</obj_name>
  <obj_hashval>f899dc6ba1d35b49283a7205cccf978c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oportunitati_getcarnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_OPORTUNITATI.CARNETDOC_I', true)),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oportunitati_getct_monitor</obj_name>
  <obj_hashval>90bc9dcecda9a9afbc051c4c67de5cc0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oportunitati_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_OPORTUNITATI.CT_MONITOR'));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_55';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oportunitati_getdocinfo</obj_name>
  <obj_hashval>afdb5d0eb1983772e50c27876aca4d3f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oportunitati_getdocinfo(INOUT wme_result character varying, INOUT acoddoc numeric, INOUT atipdoc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  lResult   varchar := '-Nedefinit-';
  TaskFirma numeric;
begin
  --Adina 08.03.2021 - sinc.Oracle din 05.03.2021
  --Adina 03.02.2021 - modif.dupa Oracle
  SELECT COALESCE( (fnc_GetValConstanta('TaskFirma', getANLUCRU(), getlunalucru())), '0')::numeric
  INTO TaskFirma;

  case aTipDoc
    when 18 then SELECT PREFIXDOC||SeriaDoc||NrDoc||'/'||To_Char(DataDoc,   'dd.mm.yyyy') INTO lResult FROM Comanda  WHERE CodComanda  = aCodDoc;
    when 34 then SELECT 'C.'||SeriaDoc||NrDoc||'/'||To_Char(DataDoc,   'dd.mm.yyyy')      INTO lResult FROM Contract WHERE CodContract = aCodDoc;
    when 50 then SELECT 'O.'||SeriaDoc||NrDoc||'/'||To_Char(DataOferta,'dd.mm.yyyy')      INTO lResult FROM Oferta   WHERE CodOferta   = aCodDoc;
    when 54 then
      if TaskFirma = 2
      then SELECT Username||'/'||To_Char(DataTask,'dd.mm.yyyy') INTO lResult FROM SetTask           WHERE  CodTask  = aCodDoc;
      else SELECT Username||'/'||To_Char(DataTask,'dd.mm.yyyy') INTO lResult FROM WinMAdmin.SetTask WHERE  CodTask  = aCodDoc;
      end if;
    else lResult := '-Nedefinit-';
  end case;

  WME_Result :=  lResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oportunitati_getdocommit</obj_name>
  <obj_hashval>b8230937cba4b69e382fe46b4593d52a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oportunitati_getdocommit(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_OPORTUNITATI.DoCommit'));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := true;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oportunitati_getnrdoc_i</obj_name>
  <obj_hashval>69292625e7df93b1886c0cbfc34d02e9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oportunitati_getnrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_OPORTUNITATI.NRDOC_I', true)),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oportunitati_nrdoc_i</obj_name>
  <obj_hashval>3b1a96fd75e4f12f432f4094e1a12f6d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oportunitati_nrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_OPORTUNITATI.NRDOC_I', true)),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oportunitati_set_do_commit</obj_name>
  <obj_hashval>70f3a6e385166c42f31205ee3acb10ed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oportunitati_set_do_commit(adocommit boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_OPORTUNITATI.DoCommit',aDoCommit,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oportunitati_setcarnetdoc_i</obj_name>
  <obj_hashval>f673fe7ad7393837a48bc4142a70d923</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oportunitati_setcarnetdoc_i(acarnetdoc_i numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_OPORTUNITATI.CARNETDOC_I',to_char(aCARNETDOC_I,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oportunitati_setct_monitor</obj_name>
  <obj_hashval>2dd038460c4e36933bbee255969fc274</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oportunitati_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_OPORTUNITATI.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oportunitati_setdocommit</obj_name>
  <obj_hashval>650d491419cc1ed96a3a5eb74ffde61d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oportunitati_setdocommit(adocommit boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_OPORTUNITATI.DoCommit',aDoCommit,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oportunitati_sp_deleterecord</obj_name>
  <obj_hashval>9a2041719bc05b4a2eac49213cf74848</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oportunitati_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDoc       varchar;
  ACARNETDOC numeric;
  ANRDOC     numeric;
BEGIN
  --Florin 19.11.2024 - sinc. Oracle
  --Florin 01.06.2023 - monitor
  --Florin 11.11.2020 - fixat #40779
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_oportunitati_setct_monitor('MON_55');
  PERFORM PKG_OPORTUNITATI_SP_LOCKRECORD( RecId);
  SELECT COALESCE( CODCARNETDOC, 0), NRDOC INTO ACARNETDOC, ANRDOC FROM Oportunitati WHERE CodOportunitate = RECID;
  PERFORM PKG_CFGTABLES_EXT_DELETERECORD(recId, 82);

  IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_OPORTUNITATI.CT_MONITOR', true))))
  THEN
    SELECT 'Oportunitate "' || prefixdoc || nrdoc || '/' || datadoc || '"'
    INTO aDoc
    FROM Oportunitati
    WHERE
       codoportunitate = recid;
    PERFORM pkg_userfirme_postlogcucommit( 'Oportunitati', (current_setting('PKG_GLOBALS.USERNAME', true)), 'S', RECID, (current_setting('PKG_GLOBALS.FIRMANAME', true)), TO_NUMBER((current_setting('PKG_GLOBALS.SUBUNITATE', true)),'999999999999999999'), null, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  DELETE FROM Oportunitati1 WHERE CodOportunitate = RecId;
  DELETE FROM Oportunitati   WHERE CodOportunitate = RecId;
  DELETE FROM DocAsoc       WHERE (CODDOC = RECID AND TIPDOC = 82) OR (CODDOCASOC = RECID AND TIPDOCASOC = 82);

  IF  aCARNETDOC &lt;&gt; 0 THEN
    PERFORM PKG_CARNETEDOC_RELEASENUMARDOC( aCARNETDOC, aNRDOC);
    PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE( aCARNETDOC);
  END IF;

  PERFORM NotifyModif( 2, RECID, 'OPORTUNITATI');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oportunitati_sp_gotorecord</obj_name>
  <obj_hashval>10ede194f4f3123e5105dec03c02b1f6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oportunitati_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TaskFirma numeric;
BEGIN
  --Florin 19.11.2024 - sinc. Oracle
  --Adina 08.03.2021 - sinc.Oracle din 05.03.2021
  --Adina 05.02.2021 - modif.Oracle din 04.02.2021 - add codfiscal
  --Adina 03.02.2021 - modif.Oracle din 03.02.2021
  --Florin 16.11.2021 - fixat 52001
  perform pkg_oportunitati_setct_monitor('MON_55');
  SELECT COALESCE( (fnc_GetValConstanta('TaskFirma', getANLUCRU(), getlunalucru())), '1')::numeric
  INTO TaskFirma;

  INSERT INTO Tmp_Oportunitati(CodOportunitate, PrefixDoc, NrDoc, DataDoc, CodCarnetDoc, CodPartener, CodMoneda, Tip, CodAgent, CodCampanie,
                               VenitEst, VenitProb, CodSubunitate, CodOferta, CodComanda, CodContract, An, Luna, ProbVanz, DataSemnare,
                               PartCodFiscal, PartLocalit, PartCifraAfaceri, PartNrAngajati, PartDomeniuAct, SeriaDoc, CodLead, CodTask,
                               UserID, CodProiectCRM, Codclaseopt, Codlocatie, Obs, Curs, CodFiscal
                              )
  SELECT O.CodOportunitate, O.PrefixDoc, O.NrDoc, O.DataDoc, O.CodCarnetDoc, O.CodPartener, O.CodMoneda, O.Tip, O.CodAgent, O.CodCampanie,
         O.VenitEst, O.VenitProb, O.CodSubunitate, OFE.CodOferta, COM.CodComanda, CONTR.CodContract, O.An, O.Luna, O.ProbVanz, O.DataSemnare,
         coalesce(CF.CodFiscal, P.CodFiscal), P.Den_Localit, P.CifraAfaceri, P.NrAngajati, P.DenDomeniuAct, O.SeriaDoc, O.CodLead,
         CASE WHEN  TaskFirma = 2 THEN TSK_F.CodTask ELSE TSK.CodTask END  CODTASK,
         O.UserID, O.CodProiectCRM, O.Codclaseopt, O.CodLocatie, O.Obs, O.Curs, coalesce(O.CodFiscal, p.COD_CODFISCAL)
  FROM Oportunitati O
       INNER JOIN V_NPART           P     ON  P.CodPart         = O.CodPartener
       LEFT  JOIN OFERTA            OFE   ON  OFE.CodOferta     = O.CodOferta   AND  COALESCE( OFE.Anulat  , 0) = 0
       LEFT  JOIN CONTRACT          CONTR ON  CONTR.CodContract = O.CodContract AND  COALESCE( CONTR.Anulat, 0) = 0
       LEFT  JOIN COMANDA           COM   ON  COM.CodComanda    = O.CodComanda  AND  COALESCE( COM.Anulat  , 0) = 0
       LEFT  JOIN WINMADMIN.SETTASK TSK   ON  TSK.CodTask       = O.CodTask     AND  COALESCE( TSK.Sters   , 0) = 0
       LEFT  JOIN SETTASK           TSK_F ON  TSK_F.CodTask     = O.CodTask     AND  COALESCE( TSK_F.Sters , 0) = 0
       LEFT  JOIN NPARTCODFISC      CF    ON CF.COD_CODFISCAL   = O.CODFISCAL
  WHERE
     O.CodOportunitate = RecId;

  IF  TaskFirma = 2 THEN
    INSERT INTO Tmp_Oportunitati1(CodOportunitate1, CodOportunitate, IndexLocal, Stadiu, CodAgent, Info, DataC, CodMotiv, FollowUp, CodTask, Task, CodPers)
    SELECT CodOportunitate1, CodOportunitate, IndexLocal, Stadiu, CodAgent, Info, DataC, CodMotiv, FollowUp, o1.CodTask, T.Executant || '-' || T.DataTask, o1.CodPers
    FROM Oportunitati1 o1
         LEFT JOIN SetTask T ON  T.CodTask = O1.Codtask
    WHERE CodOportunitate = RecId;
  ELSE
    INSERT INTO Tmp_Oportunitati1(CodOportunitate1, CodOportunitate, IndexLocal, Stadiu, CodAgent, Info, DataC, CodMotiv, FollowUp, CodTask, Task, CodPers)
    SELECT CodOportunitate1, CodOportunitate, IndexLocal, Stadiu, CodAgent, Info, DataC, CodMotiv, FollowUp, o1.CodTask, T.Executant || '-' || T.DataTask, o1.CodPers
    FROM Oportunitati1 o1
         LEFT JOIN WinMAdmin.SetTask T ON  T.CodTask = O1.Codtask
    WHERE CodOportunitate = RecId;
  END IF;
  PERFORM PKG_CFGTABLES_EXT_GOTORECORD(82);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oportunitati_sp_insertrecord</obj_name>
  <obj_hashval>076622a6c9798ae4000b37a75cc8068a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oportunitati_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 19.11.2024 - sinc. Oracle
  INSERT INTO Tmp_Oportunitati(CodOportunitate) VALUES(0);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(82);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oportunitati_sp_lockrecord</obj_name>
  <obj_hashval>8792d37af52cc69465c77ebae2d05525</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oportunitati_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodOportunitate INTO Tmp FROM Oportunitati WHERE CodOportunitate = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oportunitati_stergecoddoc</obj_name>
  <obj_hashval>a91e87bd367daba41231d4db7c032f17</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oportunitati_stergecoddoc(acodoportunitate numeric, acoddoc numeric, atipdoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vVenitEstimat numeric;
begin
  --Adina 03.02.2021 - dupa Oracle
  vVenitEstimat := 0;
  SELECT COALESCE( Sum( D1.CANTACCEPTAT * D1.PU), 0) INTO vVenitEstimat
  FROM Oportunitati O
       INNER JOIN Comanda  D  ON  D.CodComanda  = O.CodComanda
       INNER JOIN Comanda1 D1 ON  D1.CodComanda = D.CodComanda
  WHERE
     O.CodOportunitate = aCodOportunitate AND  D.TipDoc &lt;&gt; aTipDoc;

  IF  vVenitEstimat = 0 THEN
    SELECT COALESCE( Sum( D1.CANT * D1.PRET), 0) INTO vVenitEstimat
    FROM Oportunitati O
         INNER JOIN CONTRACT  D  ON  D.CodContract  = O.CodContract
         INNER JOIN CONTRACT1 D1 ON  D1.CodContract = D.CodContract
    WHERE
       O.CodOportunitate = aCodOportunitate AND  D.TipDoc &lt;&gt; aTipDoc;
  END IF;

  IF  vVenitEstimat = 0 THEN
    SELECT COALESCE( Sum( D1.CANTMIN * D1.PRET), 0) INTO vVenitEstimat
    FROM Oportunitati O
         INNER JOIN OFERTA  D  ON  D.CodOferta  = O.CodOferta
         INNER JOIN OFERTA1 D1 ON  D1.CodOferta = D.CodOferta
    WHERE
       O.CodOportunitate = aCodOportunitate AND  D.TipDoc &lt;&gt; aTipDoc;
  END IF;

  CASE aTipDoc
    WHEN 18 THEN
      UPDATE Oportunitati SET CodComanda = 0 , VenitEst = vVenitEstimat WHERE CodOportunitate = aCodOportunitate;
    WHEN 34 THEN
      UPDATE Oportunitati SET CodContract = 0, VenitEst = vVenitEstimat WHERE CodOportunitate = aCodOportunitate;
    WHEN 50 THEN
      UPDATE Oportunitati SET CodOferta = 0  , VenitEst = vVenitEstimat WHERE CodOportunitate = aCodOportunitate;
    WHEN 55 THEN
      UPDATE Oportunitati SET CodTask = 0 WHERE CodOportunitate = aCodOportunitate;
  END CASE;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_opper_sp_deleterecord</obj_name>
  <obj_hashval>57af8ac57fa21e3c1833ed06f88a2b70</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_opper_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_OPPER_SP_LOCKRECORD( RecId);
  DELETE FROM OPPER1 WHERE CodOpper = RecId;
  DELETE FROM OPPER  WHERE CodOpper = RecId;
  PERFORM NotifyModif( 2, RECID, 'OPPER');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_opper_sp_gotorecord</obj_name>
  <obj_hashval>f738e0d395d7753db228466e57499fc4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_opper_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_OPPER
  SELECT * FROM OPPER WHERE CODOPPER = RECID;

  INSERT INTO TMP_OPPER1(CODOPPER1, CODOPPER, SAPTAMANA, TIPOPER, VALOARE, TERMEN, OBS, CODELEMBUGET, ELEMENT)
  SELECT O1.CODOPPER1, O1.CODOPPER, O1.SAPTAMANA, O1.TIPOPER, O1.VALOARE, O1.TERMEN, O1.OBS, O1.CODELEMBUGET, E.ELEMENT
  FROM OPPER1 O1 LEFT JOIN ELEMBUGET E ON  O1.CODELEMBUGET = E.CODELEMBUGET
  WHERE O1.CODOPPER = RECID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_opper_sp_lockrecord</obj_name>
  <obj_hashval>ec2de98119f0eac235346b036a720b4e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_opper_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMP numeric := 0;
begin
  SELECT CodOpper INTO Tmp FROM OPPER WHERE CodOpper = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_opper_sp_postrecords</obj_name>
  <obj_hashval>45e024c3c78c053f71cdbd27ec3805b2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_opper_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  vCod  numeric;
begin
  IF  Operation = 0 THEN
    SELECT CodOpper INTO RecId FROM TMP_OPPER;

    UPDATE OPPER
    SET
    (CODOPPER, OBS, VALOARE, AN, SUBUNITATEA) = (SELECT CODOPPER, OBS, VALOARE, AN, SUBUNITATEA FROM TMP_OPPER)
    WHERE
     CodOpper = RecId;

    DELETE FROM OPPER1 WHERE CodOpper = RecID AND CodOpper1 NOT IN (SELECT CodOpper1 FROM TMP_Opper1);

    FOR v_rec IN (SELECT * FROM TMP_OPPER1 ORDER BY SAPTAMANA) LOOP
      IF  COALESCE( v_rec.CODOPPER1, 0) &gt; 0 THEN
        UPDATE OPPER1
        SET
        SAPTAMANA    = v_rec.SAPTAMANA,
        TERMEN       = v_rec.TERMEN,
        TIPOPER      = v_rec.TIPOPER,
        VALOARE      = V_REC.VALOARE,
        OBS          = V_REC.OBS,
        CODELEMBUGET = V_REC.CODELEMBUGET
        WHERE
         CodOpper1 = v_rec.CodOpper1;
      ELSE
        INSERT INTO OPPER1(CodOpper1, CODOPPER, SAPTAMANA, TIPOPER, TERMEN, VALOARE, OBS, CODELEMBUGET)
        VALUES(NEXTVAL('SEQ_OPPER1_CODOPPER1'), RecId, V_REC.SAPTAMANA, V_REC.TIPOPER, V_REC.TERMEN, V_REC.VALOARE, V_REC.OBS, V_REC.CODELEMBUGET);
      END IF;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_OPPER_CODOPPER') INTO RecID;

    INSERT INTO OPPER(CODOPPER, OBS, VALOARE, AN, SUBUNITATEA)
    (SELECT RecId, OBS, VALOARE, AN, SUBUNITATEA FROM TMP_OPPER);

    INSERT INTO OPPER1(CODOPPER1, CODOPPER, SAPTAMANA, TIPOPER, VALOARE, TERMEN, OBS, CODELEMBUGET)
    SELECT NEXTVAL('SEQ_OPPER1_CODOPPER1'), RECID, SAPTAMANA, TIPOPER, VALOARE, TERMEN, OBS, CODELEMBUGET
    FROM TMP_OPPER1;
  END IF;

  PERFORM NotifyModif( OPERATION, RECID, 'OPPER');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_opreg_sp_deleterecord</obj_name>
  <obj_hashval>6d90d2c5a953a2d5ad7283667a0efe01</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_opreg_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_OPREG_SP_LOCKRECORD( RecId);
  DELETE FROM OPREG1 WHERE CodOp = RecId;
  DELETE FROM OPREG  WHERE CodOp = RecId;
  PERFORM NotifyModif( 2, RECID, 'OPREG');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_opreg_sp_gotorecord</obj_name>
  <obj_hashval>d2843eb7ffc31bd109b782e48ba09f3d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_opreg_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_OPREG(CODOP, CODPART, CODBanca, OBS, TIPTRANZ, TIPDECONT, ZIDECONT, CODMONEDA, VALOARE, AN_Start, LUNA_Start, AN_MAX, LUNA_MAX, SUBUNITATEA)
  (SELECT CODOP, CODPART, CODBanca, OBS, TIPTRANZ, TIPDECONT, ZIDECONT, CODMONEDA, VALOARE, AN_Start, LUNA_Start, AN_MAX, LUNA_MAX, SUBUNITATEA
   FROM OPREG WHERE CodOp = RecId
  );

  INSERT INTO TMP_OPREG1(CODOP1, CODOP, TERMEN, Stins, Obs)
  (SELECT CODOP1, CODOP, TERMEN, Stins, Obs FROM OPREG1 WHERE CodOp = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_opreg_sp_lockrecord</obj_name>
  <obj_hashval>76e50a75d3428f8b4725cc2ef4b15162</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_opreg_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMP numeric := 0;
begin
  SELECT CodOp INTO Tmp FROM OPREG WHERE CodOp = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_create_view_4_last_job</obj_name>
  <obj_hashval>bff2aed5326d904e6421b284b3ef08a2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_create_view_4_last_job(acodjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  MascaviewName varchar;
  viewName      varchar;
  tblName       varchar;
  nr            numeric;
  aDataINI      date;
  aDataFIN      date;
  aDataGen      date;
  aSubunitate   numeric;
  isExp         numeric;
  NumeExp       varchar;
  SkemaF        varchar;
BEGIN
  --Florin 09.06.2023 - corectie view extrascont
  BEGIN
    SELECT tabla, COALESCE( Export, 0), COALESCE( FISIER_EXPORT, '?')
    INTO MascaViewName, isExp, NumeExp
    FROM jobliste1
    WHERE codjob1 = aCodjob1;
  EXCEPTION WHEN OTHERS THEN
    MascaViewName := '?';
  END;

  SELECT Count( *) INTO nr FROM joblistefin WHERE codjob1 = acodjob1;

  IF  Nr &gt; 0 THEN
    SELECT tabla, DataIni, DataFin, DataGen, SUBUNITATEA, SKEMAFIRMA
    INTO tblName, aDataINI, aDataFIN, aDataGen, aSubunitate, SkemaF
    FROM joblistefin
    WHERE codjoblistefin = (SELECT max( codjoblistefin) FROM joblistefin jf WHERE jf.codjob1 = acodjob1);
   IF  COALESCE( TblName, '?') &lt;&gt; '?' THEN

      IF  COALESCE( MascaViewName, '?') &lt;&gt; '?' THEN
        IF aDataIni IS NULL  THEN
          aDataIni := aDataGen;
        END IF;

        IF aDataFin IS NULL  THEN
          aDataFin := aDataGen;
        END IF;

        IF  aDataIni &gt; aDataFin THEN
          aDataIni := aDataFin;
        END IF;

        ViewName := (SELECT PKG_ORA_LISTS_GetNumeView.WME_RESULT FROM PKG_ORA_LISTS_GetNumeView(NULL, MascaViewName, aDataIni, aDataFin, aSubunitate));
        EXECUTE 'create or replace view ' || COALESCE(SkemaF, '') || '.' || coalesce(viewName,'') || ' as select * from ' || coalesce(tblName,'');
      END IF;
    END IF;
  ELSE
    IF  COALESCE( ViewName, '?') &lt;&gt; '?' THEN
      BEGIN
        EXECUTE 'drop view ' || coalesce(viewName,'');
      EXCEPTION WHEN OTHERS THEN
        ViewName := '?';
      END;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_creaza_tabla</obj_name>
  <obj_hashval>98772c45340f298cfd638f68f087f641</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_creaza_tabla(INOUT numetmp character varying, INOUT alistid numeric, INOUT alistver numeric, INOUT acodjob1 numeric DEFAULT NULL::numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  --&lt;sstplsql_recordtypedef&gt;
  --TYPE  IS TABLE OF t_rec;
  --t_drop t_tab;

  sCOL         varchar;
  --sCreateTab   varchar;
  IS_COLOR     numeric;
  aDINAMICName varchar;
  sInsert      varchar;
  vNewDepo     numeric;
  vNumeTmp     varchar;
begin
  --Florin 14.01.2022 - sinc. Oracle
  --Adina 19.08.2021 - sinc.Oracle din 18.08.2021
  --Adina 14.07.2021 - sinc.Oracle din 13.07.2021
  IF aCodJob1 IS NOT NULL THEN
    vNumeTmp := NULL;
    SELECT COALESCE(J.NewDepo, 0) INTO vNewDepo
    FROM JobListe1 J1 INNER JOIN JobListe J ON  J.CodJob = J1.CodJob
    WHERE J1.CodJob1 = aCodJob1;

    IF  vNewDepo = 0 THEN
      SELECT  DISTINCT LAST_VALUE(Tabla) OVER (  ORDER BY CodJobListeFin ) INTO vNumeTmp
      FROM JobListeFin WHERE CodJob1 = aCodJob1;

      FOR v_rec IN
      (SELECT CodJobListeFin, 'DROP TABLE ' || coalesce(SkemaFirma,'') || '.' || coalesce(Tabla,'') sqlDrop
      FROM JobListeFin WHERE CodJob1 = aCodJob1
      )
      LOOP
        BEGIN
          EXECUTE v_rec.sqlDrop;
        EXCEPTION
          WHEN OTHERS THEN NULL;
        END;
      END LOOP;
    END IF;

    NumeTmp := COALESCE(vNumeTmp, NumeTmp);
    IF NumeTmp IS NULL THEN
      NumeTmp := 'J_' || coalesce(Trim( (aListID)::varchar),'') || '_' || coalesce(Trim( (aListVer)::varchar),'') || '_' || coalesce(NEXTVAL('SEQ_JOBUNIC'),'');
    END IF;
  END IF;

  aDINAMICName := 'JCL' || coalesce(current_setting('PKG_ORA_LISTS.JOB_CodJob1', true)::numeric::varchar ,'');
  IF  COALESCE(current_setting('PKG_ORA_LISTS.JOB_CodJob1', true)::numeric, 0) &gt; 0 THEN
    INSERT INTO job_dinamic_cols(TABLENAME, FIELDNAME, DISPLAY, INDEXLOCAL)
    SELECT aDINAMICName, FIELDNAME, DISPLAY, INDEXLOCAL FROM tmp_dinamic_cols;
  END IF;

  IS_COLOR := 0;
  FOR V_REC IN
  (
  SELECT FIELDNAME, Min(FIELDTYPE) FIELDTYPE, CASE Min(FIELDTYPE) WHEN 0 THEN Max(FIELDSIZE) ELSE 0 END  FIELDSIZE
  FROM (SELECT  DISTINCT upper(FIELDNAME), FIELDTYPE, FIELDSIZE
        FROM LISTCOLS
        WHERE LISTID = ALISTID AND  LISTVER = 0 AND FIELDNAME LIKE 'NRCRT%' AND FIELDNAME LIKE 'NRG%' AND  NOT REGEXP_LIKE(FIELDNAME, 'EXP_\d')
        union ALL
        SELECT  DISTINCT upper(FIELDNAME), FIELDTYPE, FIELDSIZE
        FROM WINMADMIN.LISTCOLS
        WHERE LISTID = ALISTID AND  LISTVER = ALISTVER AND  USERCOLUMN = 1
        union ALL
        SELECT  DISTINCT upper(FIELDNAME), 1 FIELDTYPE, 0 FIELDSIZE
        FROM WINMADMIN.LISTCALC
        WHERE LISTID = ALISTID AND  LISTVER = ALISTVER AND  TIP = 0
        union ALL
        SELECT  DISTINCT upper(FIELDNAME), 0 FIELDTYPE, 1000 FIELDSIZE
        FROM WINMADMIN.LISTCALC
        WHERE LISTID = ALISTID AND  LISTVER = ALISTVER AND  Tip = 1
        union ALL
        SELECT  DISTINCT upper(FIELDNAME), 1 FIELDTYPE, 0 FIELDSIZE
        FROM tmp_dinamic_cols
       ) A_PG
  GROUP BY FIELDNAME
  )
  LOOP
    IF  UPPER(V_REC.FIELDNAME) = 'COLOR' THEN
      IS_COLOR := 1;
    END IF;

    sCOL := coalesce(sCOL,'') || coalesce(V_REC.FIELDNAME,'') || ' '
            || coalesce(CASE V_REC.FIELDTYPE
                         WHEN 0 THEN 'VARCHAR(' || coalesce(V_REC.FIELDSIZE,'') || ')'
                         WHEN 1 THEN 'NUMERIC(30,7)'
                         WHEN 2 THEN 'DATE'
                         WHEN 4 THEN 'TEXT'
                         ELSE NULL
                         END ,'') || ',';
  END LOOP;

  sCOL := coalesce(sCOL,'') || 'UNITAR NUMERIC(20)';
  IF  IS_COLOR = 0 THEN
    SCOL := coalesce(SCOL,'') || ',COLOR NUMERIC(20)';
  END IF;

  BEGIN
    EXECUTE ' DROP TABLE ' || coalesce(NUMETMP,'');
  EXCEPTION WHEN OTHERS THEN
    NULL;
  END;

  --sCreateTab := ' CREATE TABLE '||COALESCE(NUMETMP,'')||'( '||SCOL||')';
  --PERFORM LIST_EXECUTE_IMMEDIATE(sCreateTab, 0, 0);
  EXECUTE ' CREATE TABLE ' || coalesce(NUMETMP,'') || '( ' || coalesce(SCOL,'') || ')';
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_creaza_tabla__xx</obj_name>
  <obj_hashval>466847c19a9d32dcae578179d70d6d8b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_creaza_tabla__xx(INOUT numetmp character varying, INOUT alistid numeric, INOUT alistver numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  --&lt;sstplsql_recordtypedef&gt;
  sCOL     varchar;
  IS_COLOR numeric;
  --aDINAMICName varchar;
  sInsert  varchar;
  vNewDepo numeric;
  vNumeTmp varchar;
begin

  NumeTmp := COALESCE(vNumeTmp, NumeTmp);
  IF NumeTmp IS NULL THEN
    NumeTmp := 'J_' || coalesce(Trim( (aListID)::varchar),'') || '_' || coalesce(Trim( (aListVer)::varchar),'') || '_' || coalesce(NEXTVAL('SEQ_JOBUNIC'),'');
  END IF;

  IS_COLOR := 0;
  FOR V_REC IN
  (
  SELECT distinct lower(FIELDNAME) as FieldName, Min(FIELDTYPE) FIELDTYPE,
         CASE Min(FIELDTYPE)
              WHEN 0 THEN 1000--Max(FIELDSIZE)
              ELSE 0
         END  FIELDSIZE
  FROM (SELECT  DISTINCT FIELDNAME, FIELDTYPE, FIELDSIZE
        FROM LISTCOLS
        WHERE LISTID = ALISTID AND  LISTVER = 0 AND UPPER(FIELDNAME) not LIKE 'NRCRT%' AND UPPER(FIELDNAME) NOT LIKE 'NRG%' AND  UPPER(FIELDNAME) NOT LIKE 'EXP_%'--REGEXP_LIKE(FIELDNAME, 'EXP_\d'-- )
        union ALL
        SELECT  DISTINCT FIELDNAME, FIELDTYPE, FIELDSIZE FROM WINMADMIN.LISTCOLS
        WHERE LISTID = ALISTID AND  LISTVER = ALISTVER --AND  USERCOLUMN = 1
        union ALL
        SELECT  DISTINCT FIELDNAME, 1 FIELDTYPE, 0 FIELDSIZE FROM WINMADMIN.LISTCALC
        WHERE LISTID = ALISTID AND  LISTVER = ALISTVER AND  TIP = 0
        union ALL
        SELECT  DISTINCT FIELDNAME, 0 FIELDTYPE, 1000 FIELDSIZE FROM WINMADMIN.LISTCALC
        WHERE LISTID = ALISTID AND  LISTVER = ALISTVER AND  Tip = 1
        union ALL
        SELECT  DISTINCT FIELDNAME, 1 FIELDTYPE, 0 FIELDSIZE FROM tmp_dinamic_cols
       ) A_PG
  GROUP BY FIELDNAME
  )
  LOOP
    IF  UPPER(V_REC.FIELDNAME) = 'COLOR' THEN
      IS_COLOR := 1;
    END IF;

    sCOL := coalesce(sCOL,'') || coalesce(V_REC.FIELDNAME,'') || ' ' ||
            coalesce(CASE V_REC.FIELDTYPE
                       WHEN 0 THEN  'VARCHAR(' || coalesce(V_REC.FIELDSIZE::varchar,'1') || ')'
                       WHEN 1 THEN 'NUMERIC(30,7)'
                       WHEN 2 THEN 'DATE'
                       WHEN 4 THEN 'BLOB'
                       ELSE NULL
                     END ,'') || ',';
  END LOOP;

  sCOL := coalesce(sCOL,'') || 'UNITAR NUMERIC(20)';
  IF  IS_COLOR = 0 THEN
    SCOL := coalesce(SCOL,'') || ',COLOR NUMERIC(20)';
  END IF;

  BEGIN
    EXECUTE ' DROP TABLE ' || coalesce(NUMETMP,'');
  EXCEPTION WHEN OTHERS THEN
    NULL;
  END;

  EXECUTE ' CREATE TABLE ' || coalesce(NUMETMP,'') || '( ' || coalesce(SCOL,'') || ')';
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_deljoblistefin_tablainexist</obj_name>
  <obj_hashval>347f591364b665d2d8a4c0bf9df8d5bb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_deljoblistefin_tablainexist()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR v_rec IN (SELECT codjoblistefin, Tabla FROM JOBLISTEFIN) LOOP
    BEGIN
      EXECUTE 'SELECT Count(*) FROM ' || coalesce(v_rec.tabla,'');
    EXCEPTION WHEN OTHERS THEN
      DELETE FROM JOBLISTEFIN WHERE codjoblistefin = v_rec.codjoblistefin;
    END;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_do_joblista_webservice</obj_name>
  <obj_hashval>06e80b1b2a28f635a9aa082bc18ada54</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_do_joblista_webservice(askemafirma character varying, dbhost character varying, dbport character varying, acodjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aUserID           numeric := 0;
  aLunaLucru         numeric;
  aAnLucru           numeric;
  IPWebServiceSMS   varchar;
  PortWebServiceSMS varchar;
  JobInfo           varchar;
  Res               numeric := 0;
  aStatus           varchar;
  aContent          varchar;
begin
  BEGIN
    SELECT coalesce(j.userid, 0) INTO aUserid FROM JobLISTE J, JobLISTE1 j1 WHERE CodJob1 = acodJob1 and  J.codJob = J1.CodJob;
  EXCEPTION WHEN others THEN
    aUserID := 0;
  END;

  IF  Coalesce(aUserID, 0) &lt;&gt; 0 THEN
    SELECT anmaxim, lunamaxima INTO aAnlucru, aLunalucru FROM firmaluni;

    PERFORM pkg_globals_SETUSERID(aUserID);
    PERFORM pkg_globals_SETFIRMANAME(askemafirma);
    PERFORM pkg_globals_SETLUNALUCRU_SIMPLa(aAnlucru, aLunalucru);

    IPWebServiceSMS   := fnc_getvalconstanta('IPWebServiceSMS'  , aAnLucru, aLunaLucru);
    PortWebServiceSMS := fnc_GetValConstanta('PortWebServiceSMS', aAnLucru, aLunaLucru);

    perform http_set_curlopt('CURLOPT_CONNECTTIMEOUT', '0');
    perform http_set_curlopt('CURLOPT_TIMEOUT', '0');

    JobInfo := '{"JobInfo":{
                                         "DataBaseType":"PG",
                                         "DBName":"'         || current_database()        || '",
                                         "ServerIP":"'       || DBHost                    || '",
                                         "ServerPort":"'     || DBPort                    || '",
                                         "CodJob1":"'        || aCodJob1::varchar         || '",
                                         "Skema":"'          || askemafirma               || '"
                                       }}';

    SELECT status, content into astatus, aContent
    FROM http_post('http://' || IPWebServiceSMS  || ':' || PortWebServiceSMS || '/root/wmeserver/solveJobLista',
    '{ ' ||   JobInfo  || '}',
     'application/x-www-form-urlencoded');

    if instrb(aContent, '"ok"') &gt; 0 then
      Res := 1;
     else
      Res := 0;
     end if;

  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_do_joblista_webservice_xx</obj_name>
  <obj_hashval>d8f0a2c516aeb1c5da56ab38c5dd9e51</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_do_joblista_webservice_xx(INOUT wme_result numeric, INOUT askemafirma character varying, INOUT acodjob1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aUserID           numeric := 0;
  aLunaLucru         numeric;
  aAnLucru           numeric;
  IPWebServiceSMS   varchar;
  PortWebServiceSMS varchar;
  aDBName           varchar;
  JobInfo           varchar;
  MSG_EROARE         varchar;
  URL               varchar;
  aREq               varchar;  --utl_http.req;
  RESP               varchar;  --utl_http.resp;
  value             varchar;
  Res               numeric := 0;
  aPos               numeric;
  StartPos           numeric;
  EndPos             numeric;
begin
  BEGIN
    SELECT coalesce(j.userid, 0) INTO aUserid FROM JobLISTE J, JobLISTE1 j1 WHERE CodJob1 = acodJob1 and  J.codJob = J1.CodJob;
  EXCEPTION WHEN others THEN
    aUserID := 0;
  END;

  IF  Coalesce(aUserID, 0) &lt;&gt; 0 THEN
    SELECT anmaxim, lunamaxima INTO aAnlucru, aLunalucru FROM firmaluni;

    PERFORM pkg_globals_SETUSERID(aUserID);
    PERFORM pkg_globals_SETFIRMANAME(askemafirma);
    PERFORM pkg_globals_SETLUNALUCRU_SIMPLa(aAnlucru, aLunalucru);

    IPWebServiceSMS   := fnc_getvalconstanta('IPWebServiceSMS'  , aAnLucru, aLunaLucru);
    PortWebServiceSMS := fnc_GetValConstanta('PortWebServiceSMS', aAnLucru, aLunaLucru);

    SELECT global_name INTO aDBName FROM global_name;

    JobInfo := '{"JobInfo":{
                                         "DataBaseType":"ORA",
                                         "DBName":"' || coalesce(aDBName,'') || '",
                                         "CodJob1":"' || coalesce(aCodJob1::varchar ,'') || '",
                                         "Skema":"' || coalesce(askemafirma,'') || '"
                                       }}';

    MSG_EROARE := '';
    URL := 'http://' || coalesce(IPWebServiceSMS,'') || ':' || coalesce(PortWebServiceSMS,'') || '/root/wmeserver/solveJobLista';
    areq := UTL_HTTP.BEGIN_REQUEST(LOWER(URL), 'POST');

    PERFORM utl_http.set_header(areq, 'Content-Length', length(JobInfo));
    PERFORM UTL_HTTP.WRITE_TEXT(areq, JobInfo);

    BEGIN
      resp := UTL_HTTP.GET_RESPONSE(areq);
      LOOP
        PERFORM UTL_HTTP.READ_LINE(resp, value, TRUE);
        aPos := INSTRB(VALUE, '"result"');
        IF  aPOS &gt; 0 THEN
          aPOS := aPOS + 8;
          StartPos := INSTRB(VALUE, '"', aPos, 1);
          EndPos := INSTRB(VALUE, '"', aPos, 2);

          IF  StartPos &gt; 0 AND  EndPos &gt; 0 AND  StartPos &lt; EndPos THEN
            MSG_EROARE := Substr(Value, StartPos, EndPos - StartPos + 1);
          END IF;
        END IF;
      END LOOP;

      PERFORM UTL_HTTP.END_RESPONSE(resp);
    --EXCEPTION WHEN UTL_HTTP.END_OF_BODY THEN PERFORM UTL_HTTP.END_RESPONSE(resp);
    END;

    IF  MSG_Eroare = '"ok"' THEN
      RES := 1;
    END IF;

    WME_Result :=  RES;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_dropcompletejoblistefin</obj_name>
  <obj_hashval>560b33f500c4b33005c5e17c020e241f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_dropcompletejoblistefin(acod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodJob1 numeric;
begin
  --Adina 02.02.2021 - comentat linia 17 dupa modif.de pe Oracle din 29.01.2021
  BEGIN
    SELECT CodJob1 INTO aCodJob1 FROM JOBLISTEFIN WHERE codjoblistefin = aCod;
  EXCEPTION WHEN OTHERS THEN
    aCodJob1 := 0;
  END;

  IF  aCodJob1 &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_DropJobListeFin( aCod);
    --PERFORM PKG_ORA_LISTS_CREATE_VIEW_4_LAST_JOB( aCodJob1);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_dropjoblistefin</obj_name>
  <obj_hashval>fc603f6cf97543e31e060a0188d6a9b7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_dropjoblistefin(acod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aSkema   varchar;
  aTabla   varchar;
  aCodJob1 numeric;
begin
  BEGIN
    SELECT CodJob1, SKEMAFIRMA, Tabla INTO aCodJob1, aSkema, aTabla FROM JOBLISTEFIN WHERE codjoblistefin = aCod;
  EXCEPTION WHEN OTHERS THEN
    aSkema   := '?';
    aTabla   := '?';
    aCodJob1 := 0;
  END;

  IF  aTabla &lt;&gt; '?' AND  aSkema &lt;&gt; '?' THEN
    BEGIN
      EXECUTE 'DROP TABLE ' || coalesce(aSkema,'') || '.' || coalesce(atabla,'');
    EXCEPTION WHEN OTHERS THEN
      aSkema := '?';
    END;
  END IF;

  DELETE FROM JOBLISTEFIN WHERE CODJOBLISTEFIN = aCod;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_exportoratoxlsx</obj_name>
  <obj_hashval>ad31309dfaa15a516ac5587ae32913b7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_exportoratoxlsx(asql character varying, numeexp character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM ORA_EXCEL_new_document(NULL,NULL);
  PERFORM ORA_EXCEL_add_sheet(NULL, 'WME',NULL);
  PERFORM ORA_EXCEL_query_to_sheet( aSQL,NULL,NULL,NULL);
  PERFORM ORA_EXCEL_save_to_file( 'WMETOXLS_' || coalesce((SELECT PKG_USERFIRME_GetSkemaFirma.WME_RESULT FROM PKG_USERFIRME_GetSkemaFirma(NULL, (SELECT pkg_globals_GetCodFirma.WME_RESULT FROM pkg_globals_GetCodFirma(NULL,NULL)))),''), NumeExp);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_extract_element</obj_name>
  <obj_hashval>01322319508172b9aa6c75a7e66227e4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_extract_element(INOUT pss character varying, INOUT pvalori character varying, INOUT pelement character varying, INOUT plungime numeric, INOUT pfill character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  x    NUMERIC;
  vSS  varchar := pSS;
  Buf  varchar;
  Buf1 varchar;
  bb   integer;
begin
  pValori  := '';
  pElement := '';
  pLungime := 0;
  pFill    := '0';
  X        := Instr( vSS, '[');

  IF  X &gt; 0 THEN
    Buf := SubStr( vSS, X + 1, 255);
    vSS := coalesce(SubStr( vSS, 1, X - 1),'') || coalesce(SubStr( vSS, X + 255),'');
    bb := INSTR( Buf, ']');
    IF  bb &gt; 0 THEN
      IF  bb &gt; 101 THEN
        bb := 101;
      END IF;
      Buf := SUBSTR( Buf, 1, bb - 1);
      bb := Instr( Buf, '=');
      IF  bb &gt; 0 THEN
        pValori := Substr( Buf, bb + 1, 255);
      END IF;
    END IF;
  END IF;

  X := Instr( vSS, '(');
  IF  X &gt; 0 THEN
    Buf := SubStr( vSS, X + 1, 255);
    vSS := coalesce(SubStr( vSS, 1, X - 1),'') || coalesce(SubStr( vSS, X + 255),'');
    bb := Instr( Buf, ')');
    IF  bb &gt; 0 THEN
      bb := Least( bb, 101);
      Buf := SubStr( Buf, 1, bb - 1);
      bb := Instr( Buf, ',');
      IF  bb &gt; 0 THEN
        pFill := SubStr( Buf, bb + 1, 1);
        Buf := coalesce(SubStr( Buf, 1, bb - 1),'') || coalesce(SubStr( Buf, bb + 255),'');
      END IF;
      BEGIN
        pLungime :=  Buf::numeric;
      EXCEPTION WHEN OTHERS THEN
        pLungime := 0;
      END;
    END IF;
  END IF;
  pElement := vSS;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_get_job_dataini</obj_name>
  <obj_hashval>13090711681650474301a17c66fdc821</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_get_job_dataini(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Stef 06.09.2022
  WME_Result := To_Date(current_setting('PKG_ORA_LISTS.JOB_DATAIni', true),'dd.mm.yyyy');
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_get_values_from_tmp</obj_name>
  <obj_hashval>cdc4a32aa0ed05c1c99b00ef83608992</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_get_values_from_tmp(INOUT wme_result numeric, INOUT asubunit numeric, INOUT acodjob1 numeric, INOUT datafixata numeric DEFAULT 0)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  S       varchar;
  IRES    numeric;
  ANINI   numeric;
  LUNAINI numeric;
  ANMAX   numeric;
  LUNAMAX numeric;

  IsWeb   numeric;
  aCodJob numeric;
BEGIN
  --Adina 02.02.2021 - modif.dupa Oracle din 29.01.2021
  --Florin 11.01.2021
  BEGIN
    SELECT CodJob    INTO aCodJob FROM JOBLISTE1 WHERE CODJOB1 = ACODJOB1;
    SELECT WebServer INTO IsWeb   FROM JobListe  WHERE CodJob  = aCodJob;

    INSERT INTO VARIABILE_SESIUNE(CODJOB1, SQL_EXEC, TIP_SQL, ORDINE)
    SELECT aCodJob1, 'INSERT INTO TMP_MANEVRA_LISTE(FILTRU,VALOARE,FILTRU1,VALOARE1,FILTRU2,VALOARE2) VALUES (''' || coalesce(FILTRU,'') || ''',''' || coalesce(VALOARE,'') || ''',''' || coalesce(FILTRU1,'') || ''',''' || coalesce(VALOARE1,'') || ''',''' || coalesce(FILTRU2,'') || ''',''' || coalesce(VALOARE2,'') || ''')', 1, 0
    FROM TMP_MANEVRA_LISTE;

    INSERT INTO VARIABILE_SESIUNE(CODJOB1, SQL_EXEC, TIP_SQL, ORDINE)
    SELECT aCodJob1, 'INSERT INTO TMP_MANEVRA(CODUNIC) VALUES (' || coalesce(CODUNIC,0) || ')', 1, 0
    FROM TMP_MANEVRA;

    IF IsWeb = 0 THEN
      SELECT ANINITIAL, LUNAINITIALA, ANMAXIM, LUNAMAXIMA INTO ANINI, LUNAINI, ANMAX, LUNAMAX FROM FIRMALUNI;

--      INSERT INTO VARIABILE_SESIUNE(CODJOB1,SQL_EXEC,TIP_SQL,ORDINE)
--      SELECT ACODJOB1,'PKG_GLOBALS_SETLUNALUCRU( (select wme_result from pkg_ora_lists_set_last_year(null,null)), (select wme_result from pkg_ora_lists_set_last_month(null,null)))',0,-1 ;
--
--      INSERT INTO VARIABILE_SESIUNE(CODJOB1,SQL_EXEC,TIP_SQL,ORDINE)
--      SELECT ACODJOB1,'PKG_GLOBALS_SETSUBUNITATE('||COALESCE(aSubunit,0)||')',0,-2 ;
--
--      INSERT INTO VARIABILE_SESIUNE(CODJOB1,SQL_EXEC,TIP_SQL,ORDINE)
--      SELECT ACODJOB1,'PKG_SETLUNI_SetLunaInitiala('||COALESCE(ANINI,0)||','||COALESCE(LUNAINI,0)||')',0,-3 ;
    END IF;

  /* -- astea oricum le execut din Delphi

  INSERT INTO VARIABILE_SESIUNE
  (
  CODJOB1, SQL_EXEC, TIP_SQL, ORDINE
  )
  SELECT ACODJOB1, 'PKG_GLOBALS_SETLUNALUCRU(pkg_ora_lists.set_last_year,pkg_ora_lists.set_last_month)', 0, -1;


  INSERT INTO VARIABILE_SESIUNE
  (
  CODJOB1, SQL_EXEC, TIP_SQL, ORDINE
  )
  SELECT ACODJOB1, 'PKG_GLOBALS_SETSUBUNITATE(' || coalesce(aSubunit,0) || ')', 0, -2;
  INSERT INTO VARIABILE_SESIUNE
  (
  CODJOB1, SQL_EXEC, TIP_SQL, ORDINE
  )
  SELECT ACODJOB1, 'PKG_SETLUNI_SetLunaInitiala(' || coalesce(ANINI,0) || ',' || coalesce(LUNAINI,0) || ')', 0, -3;
  */
    IRES := 1;
  EXCEPTION WHEN OTHERS THEN
    IRES := 0;
    raise;
  END;

  WME_Result :=  IRES;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_getjob_dataini</obj_name>
  <obj_hashval>a97194289ca01b7649038d153949ac1c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_getjob_dataini(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_ORA_LISTS.JOB_DATAIni', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := Null;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_getnumeview</obj_name>
  <obj_hashval>bc6d162c48d5dcb7b939e2203cecb58a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_getnumeview(INOUT wme_result character varying, INOUT viewname character varying, INOUT dataini date, INOUT datafin date, INOUT subunit numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  RES      varchar;
  SS       varchar;
  S        varchar;
  vValori  varchar;
  vElement varchar;
  vLungime numeric;
  vFill    varchar;
  b        NUMERIC;
  bb       NUMERIC;
  Pos      NUMERIC;
BEGIN
  s    := ViewName;
  IF Instr( S,'P(') = 0 THEN
     WME_Result := s; RETURN;
  END IF;

  LOOP
    Pos := Instr(S,'+');
    IF Pos &gt; 0
    THEN ss := Substr(s, 1, Pos-1); s := SubStr(s, Pos+1);
    ELSE ss := s;
    END IF;

    Select pkg_ora_lists_extract_element.pss,
       pkg_ora_lists_extract_element.pvalori,
       pkg_ora_lists_extract_element.pelement,
       pkg_ora_lists_extract_element.plungime,
       pkg_ora_lists_extract_element.pfill
    into
       SS,
       vValori ,
       vElement ,
       vLungime ,
       vFill
    from
      pkg_ora_lists_extract_element(SS, vValori, vElement, vLungime, vFill);

    Res := Res||(select pkg_ora_lists_translate_element.wme_result from pkg_ora_lists_translate_element('',vValori, vElement, vLungime, vFill) );
    EXIT WHEN pos = 0;
  END LOOP;
  WME_Result :=  Res;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_job_codjob1</obj_name>
  <obj_hashval>03bedfaf54a2049f130b3c654fba50b6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_job_codjob1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_ORA_LISTS.JOB_CodJob1', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_job_datafin</obj_name>
  <obj_hashval>9901a6a0b213bb665e3650d46d02a85c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_job_datafin(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_ORA_LISTS.JOB_DATAFin', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := Null;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_job_dataini</obj_name>
  <obj_hashval>a537c294849a36e9ddaf51c9eb734d5f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_job_dataini(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_ORA_LISTS.JOB_DATAIni', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := Null;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_keeplastresult</obj_name>
  <obj_hashval>e5cc52bbd34676cd4d0c491ff4fdf9e2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_keeplastresult()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  V_DEL   RECORD;
  aMaxCod numeric;
begin
  UPDATE joblistefin SET TABLE_TYPE = 1;

  FOR v_rec IN (SELECT  DISTINCT codjob1 FROM JOBLISTEFIN) LOOP
    SELECT max( codjoblistefin) INTO aMaxCod FROM joblistefin WHERE codjob1 = v_rec.codjob1;

    UPDATE joblistefin SET TABLE_TYPE = 0 WHERE codjoblistefin = aMaxCod;
  END LOOP;

  FOR v_del IN (SELECT codjoblistefin FROM joblistefin WHERE TABLE_TYPE = 1) LOOP
    PERFORM PKG_ORA_LISTS_DropJobListeFin( v_del.codjoblistefin);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_mesaj_job_executat</obj_name>
  <obj_hashval>b7b349f310945251f18516950aa2a487</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_mesaj_job_executat(acodjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCodMesaj  numeric;
  vCodMesaj1 numeric;
  vUserId    numeric;
  sUserName  varchar;
  sListaName varchar;
  sFirmaName varchar;
begin
  SELECT J.USERID, L.NAME
  INTO vUserId, sListaName
  FROM JOBLISTE1 J1
      INNER JOIN JOBLISTE        J ON  J.CODJOB   = J1.CODJOB
      INNER JOIN WINMADMIN.LISTS L ON  J1.LISTAID = L.LISTID AND  J1.LISTAVER = L.LISTVER
  WHERE J1.CODJOB1 = aCODJOB1;

  IF  COALESCE( (SELECT PKG_GLOBALS_GETUSERID.WME_RESULT FROM PKG_GLOBALS_GETUSERID(NULL,NULL)), 0) = 0 THEN
    PERFORM PKG_GLOBALS_SETUSERID( vUserId);
  ELSE
    vUserId := (SELECT PKG_GLOBALS_GETUSERID.WME_RESULT FROM PKG_GLOBALS_GETUSERID(NULL,NULL));
  END IF;

  sFirmaName := current_setting('PKG_GLOBALS.FIRMANAME', true);
  IF  COALESCE( (fnc_GetValConstantalucru('AutoMesajJob')), '1') = '1' THEN
    sUserName := (SELECT PKG_USERFIRME_GETUSERNAME.WME_RESULT FROM PKG_USERFIRME_GETUSERNAME(NULL, vUserId));

    IF sFirmaName IS NULL  THEN
      SELECT  DISTINCT LAST_VALUE( SkemaFirma) OVER (  ORDER BY codjoblistefin ) INTO sFirmaName FROM JobListeFin WHERE CodJob1 = aCODJOB1;
    END IF;

    IF sFirmaName IS NULL  THEN
      sFirmaName := USER;
    END IF;

    SELECT WINMADMIN.SEQ_MESAJE_CODMESAJ.NEXTVAL, WINMADMIN.SEQ_MESAJE1_CODMESAJ1.NEXTVAL INTO vCodMesaj, vCodMesaj1;

    INSERT INTO WINMADMIN.MESAJE(CODMESAJ, TEXT, FROM_USER, SKEMAFIRMA, DATA, TIP_MESAJ)
    VALUES(vCodMesaj, 'Job complet ' || coalesce(sListaName,'') || ' la data ' || coalesce(CURRENT_TIMESTAMP,''), 'JOB LISTE', sFirmaName, CURRENT_TIMESTAMP, 0);

    INSERT INTO WINMADMIN.MESAJE1(CODMESAJ1, CODMESAJ, TO_USER, STERS)
    VALUES(vCodMesaj1, vCodMesaj, sUserName, 0);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_set_data_dinamic</obj_name>
  <obj_hashval>5a2013c207ab8813fa0a0d62ec5a7bd4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_set_data_dinamic(INOUT acodjob1 numeric, INOUT adata date)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  DMax date;
BEGIN
  -- Stef - 06.09.2022
  BEGIN  -- verificare tabela TMP_INTERVAL_LISTARE -- pentru liste WEB
    SELECT To_Date(To_Char(Coalesce(ANSTART,0),'fm0000')||To_Char(Coalesce(LUNASTART,0),'fm00')||To_Char(Coalesce(ZISTART,0),'fm00'),'yyyymmdd') INTO STRICT aData
    FROM   TMP_INTERVAL_LISTARE
    WHERE  CODJOB1 = aCODJOB1 AND Coalesce( ANSTART, 0) &lt;&gt; 0;
  EXCEPTION WHEN OTHERS THEN
    aData := current_date;
  END;

  SELECT Last_Day(To_Date(To_Char(ANMAXIM,'fm0000')||To_Char(LUNAMAXIMA,'fm00'),'yyyymm')) INTO STRICT DMax FROM FIRMALUNI;

  IF  DMax &gt; aData THEN
    IF (12*EXTRACT(YEAR FROM DMax) + EXTRACT(MONTH FROM DMax)) &lt; (12*EXTRACT(YEAR FROM aData) + EXTRACT(MONTH FROM aData))
    THEN aData := DMAx;
    END IF;
  END IF;

  PERFORM PKG_ORA_LISTS_SET_INTERVAL_LISTARE(aData, aData);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_set_last_month</obj_name>
  <obj_hashval>06633465f47e5967c9df6d861adb96ea</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_set_last_month(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  iRes numeric;
begin
  SELECT (CASE
            WHEN  (anmaxim * 12 + lunamaxima)  &lt; (extract( year FROM CURRENT_TIMESTAMP) * 12 + extract( month FROM CURRENT_TIMESTAMP))  THEN lunamaxima
            ELSE extract( month FROM CURRENT_TIMESTAMP)
          END )
  INTO ires
  FROM firmaluni;
  WME_Result :=  iRes;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_set_last_year</obj_name>
  <obj_hashval>15eec6dfc3639e7eb25ba16327cbf265</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_set_last_year(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  iRes numeric;
begin
  SELECT (CASE
            WHEN  (anmaxim * 12 + lunamaxima)  &lt; (extract( year FROM CURRENT_TIMESTAMP) * 12 + extract( month FROM CURRENT_TIMESTAMP))  THEN anmaxim
            ELSE extract( year FROM CURRENT_TIMESTAMP)
          END )
  INTO ires
  FROM firmaluni;
  WME_Result :=  iRes;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_set_variabile_sesiune</obj_name>
  <obj_hashval>4dae69f44fcb090500dcef5e02c88502</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_set_variabile_sesiune(acodjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  s     varchar;
begin
  PERFORM PKG_Globals_SetUserId( 0);

  perform set_config('PKG_ORA_LISTS.JOB_CodJob1',to_char(aCodJob1,'999999999999999999'),false);
  DELETE FROM TMP_DINAMIC_COLS;
  DELETE FROM TMP_MACHETE;

  INSERT INTO TMP_MACHETE SELECT * FROM MACHETE;

  FOR V_REC IN (SELECT * FROM VARIABILE_SESIUNE WHERE CODJOB1 = ACODJOB1 ORDER BY ORDINE) LOOP
    IF  V_REC.TIP_SQL = 1 THEN
      PERFORM LIST_EXECUTE_IMMEDIATE( V_REC.SQL_EXEC, 0, ACODJOB1);
    END IF;

    IF  V_REC.TIP_SQL = 0 THEN
      s := 'do language plpgsql $$ BEGIN ' || coalesce(V_REC.SQL_EXEC,'') || ';  END; $$;';
      PERFORM LIST_EXECUTE_IMMEDIATE( s, 0, ACODJOB1);
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT  DISTINCT LISTAID FROM JOBLISTE1 WHERE CODJOB1 = ACODJOB1) LOOP
    PERFORM LIST_BAGA_DINAMIC_COLS( v_rec.LISTAID);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_setjob_datafin</obj_name>
  <obj_hashval>e62de6d70d29bba7de0c37e710591e91</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_setjob_datafin(ajob_datafin date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_ORA_LISTS.JOB_DATAFin',aJOB_DATAFin,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_setjob_dataini</obj_name>
  <obj_hashval>000b0852766479b88d360b7d00dd15ba</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_setjob_dataini(ajob_dataini date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_ORA_LISTS.JOB_DATAIni',aJOB_DATAIni,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_testjob</obj_name>
  <obj_hashval>0bf81c8f9979487b117bb885b0409a36</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_testjob()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMP_NAME varchar;
  USERN    numeric;
begin
--&lt;sstcommit&gt;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_testjobx</obj_name>
  <obj_hashval>98a658ce027e1db509813bb346806c29</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_testjobx()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMP_NAME varchar;
  USERN numeric;
begin
  PERFORM PKG_ORA_LISTS_SET_VARIABILE_SESIUNE( 130);
  PERFORM PKG_ORA_LISTS_CREAZA_TABLA( TMP_NAME, 114, 0, 130);
  PERFORM PKG_LIST_BASE_NART_PROCESSLIST( TMP_NAME, 114, 0);

  INSERT INTO JOBLISTEFIN(CODJOBLISTEFIN, CODJOB1, TABLA, SUBUNITATEA, SKEMAFIRMA, LISTANAME, DATAGEN, TABLE_TYPE, TIPDEPO, LISTID, LISTVER, DATAINI, DATAFIN)
  VALUES(NEXTVAL('SEQ_JOBLISTEFIN_CODJOBLISTEFIN'), 130, TMP_NAME, (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL)), 'Stest', 'Nomenclator articole', CURRENT_TIMESTAMP, 0, 0, 114, 0, (SELECT PKG_ORA_LISTS_GET_JOB_DATAINI.WME_RESULT FROM PKG_ORA_LISTS_GET_JOB_DATAINI(NULL,NULL)), (SELECT PKG_ORA_LISTS_GET_JOB_DATAFIN.WME_RESULT FROM PKG_ORA_LISTS_GET_JOB_DATAFIN(NULL,NULL)));

  PERFORM PKG_ORA_LISTS_MESAJ_JOB_EXECUTAT( 130);
  PERFORM PKG_ORA_LISTS_CREATE_VIEW_4_LAST_JOB( 130);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_teststoredprocname</obj_name>
  <obj_hashval>40798441823b368a6b20c289f1afb589</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_teststoredprocname(INOUT wme_result numeric, INOUT acodjob1 numeric, INOUT aid numeric, INOUT astoredproc character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  nume     varchar;
  aCodOrar numeric;
  aActiv   numeric;
begin
  BEGIN
    SELECT StoredProcName INTO nume FROM winmadmin.lists WHERE listid = aID and  listver = 0;
  EXCEPTION WHEN others THEN
    Nume := '?';
  END;

  IF  COALESCE( nume, '?') = '?' THEN
    nume := aStoredProc;
  ELSE
    WME_Result :=  1;
    RETURN;
  END IF;

  IF  COALESCE( nume, '?') = '?' THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  UPDATE winmadmin.lists SET StoredProcName = nume WHERE listid = aID and  listver = 0;

  SELECT O.CODORAR, j1.activ INTO aCodOrar, aActiv
  FROM JOBLISTE1 J1
      INNER JOIN JOBLISTE J ON  J1.CODJOB = J.CODJOB
      INNER JOIN ORAR     O ON  O.CODORAR = J.CODORAR
  WHERE j1.CODJOB1 = ACODJOB1;

  IF  COALESCE( aCODORAR, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_JOB( aCODORAR, aCODJOB1, (   aActiv = 1) );
  END IF;

  WME_Result :=  1;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_translate_element</obj_name>
  <obj_hashval>845707dd5bd8a58cabf94eba2e93989c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_translate_element(INOUT wme_result character varying, INOUT pvalori character varying, INOUT pelement character varying, INOUT plungime numeric, INOUT pfill character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  Res varchar;
begin
  IF pElement IS NOT NULL THEN
    IF  pElement = 'P' THEN
      Res := pValori;
    ELSIF  pElement = 'S' THEN
      Res := ( Subunit)::varchar;  --Subunit din pkg_ora_lists_getnumeview ??
    elsif pElement = 'AA' THEN Res := To_Char(DataIni,'yyyy');
        ELSIF pElement = 'L1' THEN Res := To_Char(DataIni,'mm');
        ELSIF pElement = 'Z1' THEN Res := To_Char(DataIni,'dd');
        ELSIF pElement = 'L2' THEN Res := To_Char(DataFin,'mm');
        ELSIF pElement = 'Z2' THEN Res := To_Char(DataFin,'dd');
    END IF;
    Res := LPad( Res, pLungime, pFill);
  END IF;
  WME_Result :=  Res;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_orar_creaza_orar</obj_name>
  <obj_hashval>2a80ba146742f7530d935e6c2a456059</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_orar_creaza_orar(recid numeric, operation numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Denumire  varchar;
  newObs    varchar;
  oldObs    varchar;
  newStartD date;
  oldStartD date;
  newEndD   date;
  oldEndD   date;
  newRep    varchar;
  oldRep    varchar;
BEGIN
  --Florin 07.05.2021 - fixat 46266
  SELECT Upper( denumire), Obs, to_date( to_char( data_start, 'dd.mm.yyyy') || ' ' || ora || ':' || min || ':00', 'dd.mm.yyyy hh24:mi:ss'),
         CASE repetare WHEN 0 THEN NULL ELSE to_date( to_char( data_fin, 'dd.mm.yyyy') || ' 23:59:59', 'dd.mm.yyyy hh24:mi:ss') END  DATA_FIN,
         CASE repetare
           WHEN 1 THEN 'FREQ=DAILY'
           WHEN 2 THEN 'FREQ=WEEKLY'
           WHEN 3 THEN 'FREQ=MONTHLY'
           WHEN 4 THEN 'FREQ=HOURLY'
           ELSE NULL
           END  || CASE WHEN  interval &gt; 1 THEN ';INTERVAL=' || INTERVAL ELSE NULL END  || coalesce( zile_sapt, ';BYDAY=' || zile_sapt, null) || coalesce( zile_luna, ';BYMONTHDAY=' || zile_luna, null)
  INTO Denumire, newObs, newStartD, newEndD, newRep
  FROM orar WHERE codorar = recid;

  IF  operation &lt;&gt; 0 THEN
    PERFORM dbms_scheduler.create_schedule( schedule_name =&gt; Denumire, start_date =&gt; newStartD, repeat_interval =&gt; newRep, end_date =&gt; newEndD, comments =&gt; newObs);
  END IF;

  IF  operation = 0 THEN
    PERFORM dbms_scheduler.get_attribute( name =&gt; Denumire, attribute =&gt; 'start_date', value =&gt; oldStartD);

    IF  COALESCE( oldStartD, (current_setting('PKG_GLOBALS.data0', true))) &lt;&gt; COALESCE( newStartD, (current_setting('PKG_GLOBALS.data0', true))) THEN
      PERFORM dbms_scheduler.set_attribute( name =&gt; Denumire, attribute =&gt; 'start_date', value =&gt; newStartD);
    END IF;

    PERFORM dbms_scheduler.get_attribute( name =&gt; Denumire, attribute =&gt; 'repeat_interval', value =&gt; oldRep);

    IF  COALESCE( oldRep, newRep || '_') &lt;&gt; COALESCE( newRep, oldRep || '_') THEN
      PERFORM dbms_scheduler.set_attribute( name =&gt; Denumire, attribute =&gt; 'repeat_interval', value =&gt; newRep);
    END IF;

    PERFORM dbms_scheduler.get_attribute( name =&gt; Denumire, attribute =&gt; 'end_date', value =&gt; oldEndD);

    IF  COALESCE( oldEndD, (current_setting('PKG_GLOBALS.data0', true))) &lt;&gt; COALESCE( newEndD, (current_setting('PKG_GLOBALS.data0', true))) THEN
      PERFORM dbms_scheduler.set_attribute( name =&gt; Denumire, attribute =&gt; 'end_date', value =&gt; newEndD);
    END IF;

    PERFORM dbms_scheduler.get_attribute( name =&gt; Denumire, attribute =&gt; 'comments', value =&gt; oldObs);

    IF  COALESCE( oldObs, newObs || '_') &lt;&gt; COALESCE( newObs, oldObs || '_') THEN
      PERFORM dbms_scheduler.set_attribute( name =&gt; Denumire, attribute =&gt; 'comments', value =&gt; newObs);
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_orar_expirat</obj_name>
  <obj_hashval>3323a7a88377c77a2aed8d427ebe1588</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_orar_expirat(acodorar numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vEXPIRAT numeric := 0;
  aDataFin TIMESTAMP;
BEGIN
  --Stef   13.04.2022
  --Florin 13.04.2022 - fixat 53882
  select coalesce(data_fin::date + INTERVAL '1' HOUR * ora + INTERVAL '1' MINUTE * min, to_timestamp('31.12.3000', 'dd.mm.yyyy hh24:mi:ss')) into aDataFin from Orar
  where codorar = aCodOrar;

  if aDataFin &lt; current_timestamp then
    vEXPIRAT := 1;
  end if;

  RETURN vEXPIRAT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_orar_getg_codjob</obj_name>
  <obj_hashval>4cb4646649e5405e7b6c47382d097d03</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_orar_getg_codjob(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_ORAR.g_CodJob', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_orar_saveglobalenviroment</obj_name>
  <obj_hashval>e3facb960903845f593bb78ad6d09ee1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_orar_saveglobalenviroment()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  NULL;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_orar_savelistaenviroment</obj_name>
  <obj_hashval>63fc772bcdf18101405caaf59a78e286</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_orar_savelistaenviroment(asql character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  x numeric;
begin
  NULL;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_orar_setcodjob</obj_name>
  <obj_hashval>c6552f6224e19caa1e3ad9a76b7b92a6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_orar_setcodjob(acodjob numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_ORAR.g_CodJob',to_char(aCodJob,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_orar_setg_codjob</obj_name>
  <obj_hashval>6cdf939f8be5b6d54fb04b17c4dea6cb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_orar_setg_codjob(ag_codjob numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_ORAR.g_CodJob',to_char(ag_CodJob,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_orar_setparams</obj_name>
  <obj_hashval>ab1e93568633e7a797cb34afa802ead0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_orar_setparams()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM pkg_globals_SetLunaLucru( An =&gt; 2008, Luna =&gt; 1,NULL);
  PERFORM pkg_globals_SETSUBUNITATE( 100);
  INSERT INTO tmp_manevra_liste(filtru, valoare) VALUES('test orar', '999');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_orar_sp_deleterecord</obj_name>
  <obj_hashval>b3772adba3891bff26a7c921142305c0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_orar_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sDen varchar;
begin
  PERFORM PKG_ORAR_SP_LOCKRECORD( RECID);

  SELECT upper( denumire) INTO sDen FROM orar WHERE codorar = recid;

  BEGIN
    DELETE FROM ORAR WHERE CODORAR = RECID;
  --PERFORM dbms_scheduler.drop_schedule( schedule_name =&gt; sDen);
  --EXCEPTION WHEN others THEN
  --&lt;sstunknown&gt;
  --&lt;sstl_raisestmt&gt;
  END;

  PERFORM NotifyModif( 2, RECID, 'ORAR');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_orar_sp_gotorecord</obj_name>
  <obj_hashval>e284da3c55754dbab2adcbf62a687698</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_orar_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  S varchar;
BEGIN
   --stef 13.04.2022
  BEGIN
    SELECT coalesce(ZILE_SAPT, '') INTO S FROM ORAR WHERE CODORAR = RECID;
    S := REPLACE(S, 'MON', 'L');
    S := REPLACE(S, 'TUE', 'Ma');
    S := REPLACE(S, 'WED', 'Mi');
    S := REPLACE(S, 'THU', 'J');
    S := REPLACE(S, 'FRI', 'V');
    S := REPLACE(S, 'SAT', 'S');
    S := REPLACE(S, 'SUN', 'D');
  EXCEPTION WHEN OTHERS THEN
    S := NULL;
  END;

  INSERT INTO TMP_ORAR(CODORAR, DENUMIRE, OBS, REPETARE, INTERVAL, ORA, MIN, ZILE_SAPT, ZILE_LUNA, DATA_START, DATA_FIN, EXPLICATII, EXPIRAT)
  SELECT
    CODORAR, DENUMIRE, OBS, REPETARE, INTERVAL, ORA, MIN, ZILE_SAPT, ZILE_LUNA, DATA_START, DATA_FIN,
     coalesce(CASE WHEN  REPETARE=0 THEN 'Fara repetare; '
                   WHEN  REPETARE=1 THEN 'Repetare zilnica; '
                   WHEN  REPETARE=2 THEN 'Repetare saptamanala; '
                   WHEN  REPETARE=3 THEN 'Repetare lunara; '
                   WHEN  REPETARE=4 THEN 'Repetare orara; '
              END ,'') || coalesce((CASE WHEN  repetare &gt; 0 THEN 'Odata la ' || coalesce(CASE WHEN  repetare=1 THEN 'zile'
                                                                                              WHEN  repetare=2 THEN 'saptamani'
                                                                                              WHEN  repetare=3 THEN 'luni, '
                                                                                              WHEN  repetare=4 THEN 'ore'
                                                                                         END ::varchar ,'') || ' = ' || coalesce(CASE WHEN  interval=0 THEN 1 ELSE  interval END ,0)
                                         ELSE ' '
                                    END ,'dd.mm.yyyy')::varchar,'')
                       || coalesce( CASE WHEN  length(trim( zile_sapt)) &gt; 0 THEN 'In zilele ' || coalesce(S,'') || '(ora ' || coalesce(ORA::varchar,'') || ':' || coalesce(MIN::varchar,'') || ') ; '
                                         WHEN  length(trim( zile_luna)) &gt; 0 THEN CASE WHEN  zile_luna = '-1' THEN ' '
                                                                                      ELSE 'In zilele de ' || coalesce(Replace(ZILE_LUNA, '-1,', ' ')::varchar ,'')
                                                                                            || coalesce(CASE WHEN  instr(zile_luna, '-1') &gt; 0 THEN ' si ' ELSE '; ' END ::varchar ,'')
                                                                                 END
                                                                                    || coalesce(CASE WHEN  instr(zile_luna, '-1') &gt; 0 THEN 'in ultima zi a lunii (ora ' || coalesce(ORA::varchar,'') || ':' || coalesce(MIN::varchar,'') || '); '
                                                                                                     ELSE '; '
                                                                                                END ::varchar ,'')
                                    END ::varchar ,'')
                       || coalesce(Chr(13),'') || coalesce(Chr(10),'')
                       || coalesce((CASE WHEN  repetare &gt; 0 THEN 'Activ in perioada ' || coalesce(To_Char(DATA_START,'dd.mm.yyyy'),'') || ' - ' || coalesce(To_Char(DATA_FIN,'dd.mm.yyyy'),'')
                                         ELSE 'Ruleaza la ' || coalesce(To_Char(DATA_START,'dd.mm.yyyy'),'') || ' ora ' || coalesce(ORA::varchar,'') || ':' || coalesce(MIN::varchar,'')
                                    END ,'dd.mm.yyyy')::varchar,''),
    PKG_ORAR_Expirat(CODORAR)
  FROM ORAR
  WHERE CODORAR = RECID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_orar_sp_insertrecord</obj_name>
  <obj_hashval>ff97b337876e67ca2b79fa558832cd1b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_orar_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_ORAR(CodORAR) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_orar_unjob</obj_name>
  <obj_hashval>a25253b94f8368447cf6d417c0b00f24</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_orar_unjob()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
PERFORM dbms_scheduler.create_job( job_name =&gt; 'TEST_VARIABILE', job_type =&gt; 'plsql_block', job_action =&gt; ' begin

                      pkg_orar.setParams;

                      insert into t_orar(variabila,valoare) values(''ANLUCRU'',' || (SELECT pkg_globals_GetANLUCRU.WME_RESULT FROM pkg_globals_GetANLUCRU(NULL,NULL)) || ');

                      insert into t_orar(variabila,valoare) values(''SUBUNITATEA'',' || (SELECT pkg_globals_GETSUBUNITATE.WME_RESULT FROM pkg_globals_GETSUBUNITATE(NULL,NULL)) || ');

                      insert into t_orar(variabila,valoare)

                      select filtru,valoare from tmp_manevra_liste;

                      insert into t_orar(variabila,valoare) select ''NR'', count(*) from tmp_manevra_liste;

                      commit;

                    end;', start_date =&gt; (  CURRENT_TIMESTAMP + (  1 / (  24 * 60) ) ) , comments =&gt; 'job test', auto_drop =&gt; true);
PERFORM dbms_scheduler.enable( 'TEST_VARIABILE');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pachete_ct_monitor</obj_name>
  <obj_hashval>1c5224e15a7b0900e9477eb8b6ad1bb0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pachete_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_PACHETE.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_61';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pachete_deletelinie</obj_name>
  <obj_hashval>8cd50e2154132d04abc63849423cd076</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pachete_deletelinie(acodpachete numeric, acodlinie numeric, adenlinie character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCount numeric;
begin
  IF  aDenLinie = 'CODLIVR1' THEN
    SELECT count( *) INTO aCount FROM pacheteobjl WHERE codpachete = aCodPachete;

    IF  aCount = 1 THEN
      SELECT count( *) INTO aCount FROM pacheteobjl WHERE codpachete = aCodPachete and  CodLivr1 = aCodLinie;

      IF  aCount = 1 THEN
        PERFORM pkg_pachete_SP_DELETERECORD( aCodPachete);
      END IF;
    ELSE
      DELETE FROM pacheteobjl WHERE codpachete = aCodPachete and  CodLivr1 = aCodLinie;
    END IF;
  ELSE
    SELECT count( *) INTO aCount FROM pacheteobj WHERE codpachete = aCodPachete;

    IF  aCount = 1 THEN
      SELECT count( *) INTO aCount FROM pacheteobj WHERE codpachete = aCodPachete and  CodNirStoc = aCodLinie;

      IF  aCount = 1 THEN
        PERFORM pkg_pachete_SP_DELETERECORD( aCodPachete);
      END IF;
    ELSE
      DELETE FROM pacheteobj WHERE codpachete = aCodPachete and  CodNirStoc = aCodLinie;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pachete_getcarnetdoc_i</obj_name>
  <obj_hashval>f71c9e1904ca72599e997bfa23945f49</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pachete_getcarnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PACHETE.CARNETDOC_I', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pachete_getcodpartener</obj_name>
  <obj_hashval>7c42d73e18cd0db3f272e59ca95e088f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pachete_getcodpartener(INOUT wme_result numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
aCodPart numeric;
begin
SELECT CASE
 WHEN p1.tipdoc IN (12, 13) THEN COALESCE( ng.codgest, 0)
 WHEN  p1.tipdoc = 23 THEN COALESCE( ns.codsubunit, 0)
 ELSE COALESCE( np.codpart, 0)
 END
INTO aCodPart
FROM pachete p
INNER JOIN pachete1 p1 ON  p.codpachete = p1.codpachete
LEFT JOIN transf t ON  p1.coddoc = t.codtransf
LEFT JOIN ngest ng ON  t.codgestcmd = ng.codgest
LEFT JOIN iesiri i ON  p1.coddoc = i.codies
LEFT JOIN npart np ON  i.partener = np.codpart
LEFT JOIN nsubunit ns ON  i.codsubunit = ns.codsubunit
WHERE
   p.codpachete = recid and  rownum &lt;= 1;
WME_Result :=  aCodPart;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pachete_getct_monitor</obj_name>
  <obj_hashval>728af73b8fff1ac14a5b290e1167f6ec</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pachete_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_PACHETE.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_61';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pachete_getmasa</obj_name>
  <obj_hashval>3cc96f3d6f69ab31efd64544d3aa3141</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pachete_getmasa(INOUT wme_result numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
aMasa double precision;
aTip numeric;
begin
BEGIN
SELECT COALESCE( tippachet, 0)
INTO aTip
FROM pachete
WHERE
   codpachete = RecId;
EXCEPTION WHEN others THEN
aTip := 0;
END;
IF  aTip = 0
THEN
SELECT sum( PKOBJL.Cant * COALESCE( OBJ.Masa, 0))
INTO aMasa
FROM PACHETEOBJL PKOBJL
INNER JOIN LIVR1 L1 ON  L1.CODLIVR1 = PKOBJL.CODLIVR1
INNER JOIN NIRSTOC NS ON  L1.CodNIRStoc = NS.CodNIRStoc
INNER JOIN NARTOBJ OBJ ON  NS.CodObiect = OBJ.CodObiect
WHERE
   PKOBJL.Codpachete = RecId;
ELSE
SELECT sum( PKOBJ.Cant * COALESCE( OBJ.Masa, 0))
INTO aMasa
FROM PACHETEOBJ PKOBJ
INNER JOIN NIRSTOC NS ON  PKOBJ.CodNIRStoc = NS.CodNIRStoc
INNER JOIN NARTOBJ OBJ ON  NS.CodObiect = OBJ.CodObiect
WHERE
   PKOBJ.Codpachete = RecId;
END IF;
WME_Result :=  aMasa;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pachete_getmasa1</obj_name>
  <obj_hashval>148e8753e7c0750a9e6670412070e866</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pachete_getmasa1(recid numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
declare
  aMasa NUMERIC(20, 7);
  aTip NUMERIC(1);
  V_rec record;
begin
  aMasa := 0;
  begin
    select coalesce(tippachet,0) into aTip from pachete where codpachete = RecId;
  exception when others then aTip := 0;
  end;

  if aTip = 0 then
    FOR V_REC IN (
      select sum
      (
        COALESCE(PKOBJL.Cant,0) * coalesce(OBJ.Masa, 0)
      )  masa
      FROM TMP_PACHETE1 P1
           INNER JOIN TMP_PACHETEOBJL PKOBJL ON PKOBJL.CODDOC = P1.CODDOC AND PKOBJL.TIPDOC = P1.TIPDOC
           INNER JOIN LIVR1 L1 ON L1.CODLIVR1 = PKOBJL.CODLIVR1
           INNER JOIN NIRSTOC NS ON L1.CodNIRStoc = NS.CodNIRStoc
           INNER JOIN NARTOBJ OBJ ON NS.CodObiect = OBJ.CodObiect
      WHERE P1.Codpachete1 = RecId
      UNION ALL
      select sum
      (
        COALESCE(PKOBJL.Cant,0) * coalesce(OBJ.Masa, 0)
      ) masa
      FROM TMP_PACHETE1 P1
           INNER JOIN TMP_PACHETEOBJL PKOBJL ON PKOBJL.CODDOC = P1.CODDOC AND PKOBJL.TIPDOC = P1.TIPDOC
           INNER JOIN REZERVATS R ON R.CODREZERVATS = PKOBJL.CODREZERVATS
           INNER JOIN NIRSTOC NS ON R.CodNIRStoc = NS.CodNIRStoc
           INNER JOIN NARTOBJ OBJ ON NS.CodObiect = OBJ.CodObiect
      WHERE P1.Codpachete1 = RecId
    ) LOOP
      aMasa := aMasa + v_rec.masa;
    END LOOP;
  end if;

  Return aMasa;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pachete_getvaloare1</obj_name>
  <obj_hashval>9a5f411eb04cab3b7e73f312426bd67a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pachete_getvaloare1(recid numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
declare
  aValoare NUMERIC(20, 7);
  aTip NUMERIC(1);
  v_rec record;
begin
  aVALOARE := 0;
  begin
    select COALESCE(tippachet,0) into aTip from pachete where codpachete = RecId;
  exception when others then aTip := 0;
  end;

  if aTip = 0 then
    FOR V_REC IN (
      select sum
      (
        COALESCE(PKOBJL.Cant,0) * COALESCE(PKOBJL.PRET, 0)
      ) valoare
      FROM TMP_PACHETE1 P1
           INNER JOIN TMP_PACHETEOBJL PKOBJL ON PKOBJL.CODDOC = P1.CODDOC AND PKOBJL.TIPDOC = P1.TIPDOC
      WHERE P1.Codpachete1 = RecId
    ) LOOP
      aValoare := aValoare + v_rec.valoare;
    END LOOP;
  end if;

  Return aValoare;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pachete_getvolum</obj_name>
  <obj_hashval>44de3753684f0456c1f4b84ac3e7e23f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pachete_getvolum(INOUT wme_result numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
aVolum double precision;
aTip numeric;
begin
BEGIN
SELECT COALESCE( tippachet, 0)
INTO aTip
FROM pachete
WHERE
   codpachete = RecId;
EXCEPTION WHEN others THEN
aTip := 0;
END;
IF  aTip = 0
THEN
SELECT sum( PKOBJL.Cant * COALESCE( OBJ.Volum, 0))
INTO aVolum
FROM PACHETEOBJL PKOBJL
INNER JOIN LIVR1 L1 ON  L1.CODLIVR1 = PKOBJL.CODLIVR1
INNER JOIN NIRSTOC NS ON  L1.CodNIRStoc = NS.CodNIRStoc
INNER JOIN NARTOBJ OBJ ON  NS.CodObiect = OBJ.CodObiect
WHERE
   PKOBJL.Codpachete = RecId;
ELSE
SELECT sum( PKOBJ.Cant * COALESCE( OBJ.Volum, 0))
INTO aVolum
FROM PACHETEOBJ PKOBJ
INNER JOIN NIRSTOC NS ON  PKOBJ.CodNIRStoc = NS.CodNIRStoc
INNER JOIN NARTOBJ OBJ ON  NS.CodObiect = OBJ.CodObiect
WHERE
   PKOBJ.Codpachete = RecId;
END IF;
WME_Result :=  aVolum;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pachete_getvolum1</obj_name>
  <obj_hashval>c58bfdf10e8f4e10e03893bdbb09a935</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pachete_getvolum1(recid numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
declare
  aVolum NUMERIC(20, 7);
  aTip NUMERIC(1);
  v_rec record;
begin
  aVolum := 0;
  begin
    select coalesce(tippachet,0) into aTip from pachete where codpachete = RecId;
  exception when others then aTip := 0;
  end;

  if aTip = 0 then
    FOR V_REC IN (
      select sum
      (
        COALESCE(PKOBJL.Cant,0) * coalesce(OBJ.Volum, 0)
      ) volum
      FROM TMP_PACHETE1 P1
           INNER JOIN TMP_PACHETEOBJL PKOBJL ON PKOBJL.CODDOC = P1.CODDOC AND PKOBJL.TIPDOC = P1.TIPDOC
           INNER JOIN LIVR1 L1 ON L1.CODLIVR1 = PKOBJL.CODLIVR1
           INNER JOIN NIRSTOC NS ON L1.CodNIRStoc = NS.CodNIRStoc
           INNER JOIN NARTOBJ OBJ ON NS.CodObiect = OBJ.CodObiect
      WHERE P1.Codpachete1 = RecId
      UNION ALL
      select sum
      (
        COALESCE(PKOBJL.Cant,0) * coalesce(OBJ.Volum, 0)
      ) volum
      FROM TMP_PACHETE1 P1
           INNER JOIN TMP_PACHETEOBJL PKOBJL ON PKOBJL.CODDOC = P1.CODDOC AND PKOBJL.TIPDOC = P1.TIPDOC
           INNER JOIN REZERVATS R ON R.CODREZERVATS = PKOBJL.CODREZERVATS
           INNER JOIN NIRSTOC NS ON R.CodNIRStoc = NS.CodNIRStoc
           INNER JOIN NARTOBJ OBJ ON NS.CodObiect = OBJ.CodObiect
      WHERE P1.Codpachete1 = RecId
    ) LOOP
      aVolum := aVolum + v_rec.volum;
    END LOOP;
  end if;

  Return aVolum;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pachete_insertdoc</obj_name>
  <obj_hashval>b93f605af96ead2c2d8ca2337c6ca787</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pachete_insertdoc(INOUT wme_result numeric, INOUT recid numeric, INOUT coddoc numeric, INOUT tipdoc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCod numeric := 1;
  tmp  numeric;
begin
  BEGIN
    SELECT codpachete INTO Tmp FROM PACHETE WHERE codpachete = RecId;

    INSERT INTO PACHETE1(CodPachete1, CodPachete, CodDoc, TipDoc)
    VALUES(NEXTVAL('SEQ_PACHETE1_CODPACHETE1'), RecId, CodDoc, TipDoc);
  EXCEPTION WHEN OTHERS THEN
    aCod := 0;
  END;

  WME_Result :=  aCod;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pachete_insertobj</obj_name>
  <obj_hashval>3fb95244bb37e283f92ead25f44b74f1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pachete_insertobj(recid numeric, acodnirstoc numeric, acant numeric, acantum1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  aCount numeric;
  vCant  double precision;
begin
  IF  RecId &gt; 0 THEN
    SELECT count( *) INTO aCount FROM pacheteobj WHERE codnirstoc = aCodNirStoc and  CodPachete = RecId;

    IF  aCount = 1 THEN
      UPDATE pacheteobj
      SET
      Cant    = Cant + aCant,
      Rest    = rest + aCant,
      CantUM1 = CantUM1 + aCantUM1
      WHERE
       codpachete = RecId and  CodNirStoc = aCodNirStoc;
    ELSE
      IF  aCant &gt; 0 THEN
        INSERT INTO pacheteobj(codpacheteobj, codpachete, codnirstoc, cant, rest, cantum1)
        VALUES(NEXTVAL('SEQ_PACHETEOBJ_CODPACHETEOBJ'), RecId, aCodNirStoc, aCant, aCant, aCantUM1);
      END IF;
    END IF;
  ELSE
    IF  aCant &lt; 0 THEN
      vCant := -aCant;
      FOR v_rec IN (SELECT pobj.codpacheteobj, pobj.rest CANT
                    FROM pacheteobj pobj INNER JOIN pachete p ON  pobj.codpachete = p.codpachete
                    WHERE pobj.codnirstoc = aCodNirStoc
                    ORDER BY p.datacreare desc
                   )
      LOOP
        IF  vCant &lt;= 0 THEN
          EXIT ;
        END IF;

        IF  vCant &gt; v_rec.cant THEN
          vCant := vCant - v_rec.cant;

          UPDATE pacheteobj
          SET
          cant = cant - vCant,
          rest = rest - vCant
          WHERE
           codpacheteobj = v_rec.codpacheteobj;

          DELETE FROM pacheteobj WHERE cant = 0 and  codpacheteobj = v_rec.codpacheteobj;
        ELSE
          UPDATE pacheteobj
          SET
          cant = cant - vCant,
          rest = rest - vCant
          WHERE
           codpacheteobj = v_rec.codpacheteobj;

          vCant := 0;
        END IF;
      END LOOP;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pachete_insertobjl</obj_name>
  <obj_hashval>2f097d673270c899f613faeb1fee17ea</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pachete_insertobjl(recid numeric, acodlivr1 numeric, acant numeric, acantum1 numeric, apachet numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  aCount numeric;
  vCant  double precision;
begin
  --Florin 29.12.2021 - sinc Oracle 28.12.2021
  if aPachet &gt; 0 then
      if RecId &gt; 0 then
      select count(*) into aCount from pacheteobjl where codlivr1 = aCodLivr1 and CodPachete = RecId and Pachet = aPachet;
      if aCount = 1 then
        update pacheteobjl set
          Cant = Cant + aCant,
          Rest = rest + aCant,
          CantUM1 = CantUM1 + aCantUM1
        where codpachete = RecId and CodLivr1 = aCodLivr1 and Pachet = aPachet;
      else
        if aCant &gt; 0 then
          insert into pacheteobjl (codpacheteobjl, codpachete, codlivr1, cant, rest, cantum1, Pachet)
          values (nextval('seq_pacheteobjl_codpacheteobjl'), RecId, aCodLivr1, aCant, aCant, aCantUM1, aPachet);
        end if;
      end if;
    else
      if aCant &lt; 0 then
        vCant := - aCant;
        for v_rec in (select pobj.codpacheteobjl, pobj.rest cant
                      from pacheteobjl pobj
                           inner join pachete p on pobj.codpachete = p.codpachete
                      where pobj.codlivr1 = aCodLivr1
                      order by p.datacreare desc
                     ) loop
          if vCant &lt;= 0 then Exit;
        end if;
          if vCant &gt; v_rec.cant then
            vCant := vCant - v_rec.cant;
            update pacheteobjl
              set cant = cant - vCant, rest = rest - vCant where codpacheteobjl = v_rec.codpacheteobjl;
            delete from pacheteobjl
              where cant = 0 and codpacheteobjl = v_rec.codpacheteobjl;
          else
            update pacheteobjl
              set cant = cant - vCant, rest = rest - vCant where codpacheteobjl = v_rec.codpacheteobjl;
            vCant := 0;
          end if;
        end loop;
      end if;
    end if;
  else
  IF  RecId &gt; 0 THEN
    SELECT count( *) INTO aCount FROM pacheteobjl WHERE codlivr1 = aCodLivr1 and  CodPachete = RecId;

    IF  aCount = 1 THEN
      UPDATE pacheteobjl
      SET
      Cant    = Cant + aCant,
      Rest    = rest + aCant,
      CantUM1 = CantUM1 + aCantUM1
      WHERE
       codpachete = RecId and  CodLivr1 = aCodLivr1;
    ELSE
      IF  aCant &gt; 0 THEN
        INSERT INTO pacheteobjl(codpacheteobjl, codpachete, codlivr1, cant, rest, cantum1)
        VALUES(NEXTVAL('SEQ_PACHETEOBJL_CODPACHETEOBJL'), RecId, aCodLivr1, aCant, aCant, aCantUM1);
      END IF;
    END IF;
  ELSE
    IF  aCant &lt; 0 THEN
      vCant := -aCant;
      FOR v_rec IN (SELECT pobj.codpacheteobjl, pobj.rest CANT
                    FROM pacheteobjl pobj INNER JOIN pachete p ON  pobj.codpachete = p.codpachete
                    WHERE pobj.codlivr1 = aCodLivr1
                    ORDER BY p.datacreare desc
                    )
      LOOP
        IF  vCant &lt;= 0 THEN
          EXIT ;
        END IF;
        IF  vCant &gt; v_rec.cant THEN
          vCant := vCant - v_rec.cant;
          UPDATE pacheteobjl
          SET
          cant = cant - vCant,
          rest = rest - vCant
          WHERE
           codpacheteobjl = v_rec.codpacheteobjl;

          DELETE FROM pacheteobjl WHERE cant = 0 and  codpacheteobjl = v_rec.codpacheteobjl;
        ELSE
          UPDATE pacheteobjl
          SET
          cant = cant - vCant,
          rest = rest - vCant
          WHERE
           codpacheteobjl = v_rec.codpacheteobjl;
          vCant := 0;
        END IF;
      END LOOP;
    END IF;
  END IF;
  end if;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pachete_setlistare</obj_name>
  <obj_hashval>272b2bf4f95f16d2a80fbcbc690fa294</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pachete_setlistare(recid numeric, alistat numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
UPDATE PACHETE
SET
Listat = aListat
WHERE
 CodPachete = RecId
;
UPDATE TMP_PACHETE
SET
Listat = aListat
WHERE
 CodPachete = RecId
;
--&lt;sstunknown&gt;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pachete_sp_deleterecord</obj_name>
  <obj_hashval>91badcbe3b7694a9ad7774c6c52dc244</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pachete_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCarnetDoc numeric;
  aNrDoc     numeric;
  aDataDoc   date;
  aDoc       varchar;
  aSubunit   numeric;
BEGIN
  --Florin 01.06.2023 - monitor
  --Florin 12.04.2023 - sinc. Oracle (10.04.2023)
  perform pkg_pachete_setct_monitor('MON_61');
  PERFORM PKG_PACHETE_SP_LOCKRECORD (RecId);
  PERFORM PKG_CFGTABLES_EXT_DELETERECORD (recId, 77);

  SELECT P.CARNETDOC, P.NRDOC, P.DATAP, DC.SERIE || P.NRDOC || '/' || P.DATAP, P.SUBUNITATE
  INTO aCarnetDoc, aNrDoc, aDataDoc, aDoc, aSubunit
  FROM PACHETE P LEFT JOIN DOCCARNETE DC ON P.CARNETDOC = DC.CODCARNET
  WHERE P.CODPACHETE = RECID;

  IF (SELECT WME_RESULT
      FROM WINMADMIN.PKG_USERFIRME_ValidPostLog (NULL, TO_NUMBER((current_setting ('PKG_GLOBALS.USERID', true)) ,'999999999999999999') , (current_setting ('PKG_PACHETE.CT_MONITOR', true)))
     )
  THEN
    PERFORM WINMADMIN.pkg_userfirme_postlogcucommit ('PACHETE', (current_setting ('PKG_GLOBALS.USERNAME', true)) , 'S', RECID,
                                                     (current_setting ('PKG_GLOBALS.FIRMANAME', true)) , aSubunit, aDataDoc, aDoc, null,
                                                     (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION (NULL,NULL)));
  END IF;

  DELETE FROM PACHETELINK   WHERE CODPACHETEOBJ IN (SELECT CODPACHETEOBJ FROM PACHETEOBJ WHERE CODPACHETE = RecId);
  DELETE FROM PACHETEDLLINK WHERE CODPACHETEOBJ IN (SELECT CODPACHETEOBJ FROM PACHETEOBJ WHERE CODPACHETE = RecId);
  DELETE FROM PACHETEOBJ    WHERE codpachete = RecId;
  DELETE FROM PACHETEOBJL   WHERE codpachete = RecId;
  DELETE FROM PACHETE1      WHERE codpachete = RecId;
  DELETE FROM PACHETE       WHERE codpachete = RecId;

  PERFORM PKG_CARNETEDOC_RELEASENUMARDOC (ACARNETDOC, ANRDOC);
  PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE (ACARNETDOC);
  PERFORM NotifyModif (2, RecId, 'PACHETE');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pachete_sp_lockrecord</obj_name>
  <obj_hashval>21d722ce2c55336c19301543859c4f90</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pachete_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT codpachete INTO Tmp FROM PACHETE WHERE codpachete = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pachete_updatepacheteobjl</obj_name>
  <obj_hashval>d878f27dbf56dcef53ae8e09c7f49f63</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pachete_updatepacheteobjl()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR v_rec IN
  (
  SELECT pk.codpachete, l1.codlivr1, l1.cant, l1.cantum1
  FROM pachete1 pk1
      INNER JOIN pachete     pk  ON  pk.codpachete  = pk1.codpachete
      INNER JOIN iesiri      i   ON  i.codies       = pk1.coddoc and  i.tipdoc = pk1.tipdoc
      INNER JOIN iesiri1     i1  ON  i1.codies      = i.codies
      INNER JOIN livr1       l1  ON  i1.codies1     = l1.codies1
      LEFT  JOIN pacheteobjl pkl ON  pkl.codpachete = pk.codpachete and  pkl.codlivr1 = l1.codlivr1
  WHERE
     pk.tiplivrare = i1.tiplivrare and  COALESCE( pkl.codpacheteobjl, 0) = 0
  )
  LOOP
    INSERT INTO pacheteobjl(codpacheteobjl, codpachete, codlivr1, cant, rest, cantum1)
    VALUES(NEXTVAL('SEQ_PACHETEOBJL_CODPACHETEOBJL'), v_rec.codpachete, v_rec.codlivr1, v_rec.cant, v_rec.cant, v_rec.cantum1);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pachete_updateveriffactdl</obj_name>
  <obj_hashval>4ab3ef5daf12ab0b244848e4eacd6afa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pachete_updateveriffactdl(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_rec record;
BEGIN
  --Florin 05.05.2022
  for v_rec in (select distinct dl1.codcomanda
                from pacheteobjl po
                     inner join rezervats r on po.codrezervats = r.codrezervats
                     inner join comanda1 dl1 on dl1.codcomanda1 = r.codcomanda1
                where po.codpachete = recid
               ) loop
    update comanda set verificat = 1, facturabil = 1 where codcomanda = v_rec.codcomanda;
  end loop;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_packing_set_dirty</obj_name>
  <obj_hashval>e12bbf521214b48e6d557ad795541077</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_packing_set_dirty(acoddoc numeric, atipdoc numeric, aflag numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCodPacking NUMERIC(20,0);
BEGIN
  --Florin 10.07.2024
   BEGIN
     SELECT CODPACKING into vCodPacking
     FROM PACKING
     WHERE
        CODDOC = aCODDOC
        AND TIPDOC = aTIPDOC;
     EXCEPTION WHEN OTHERS THEN
        vCodPacking := 0;
   END;
   IF vCodPacking &lt;&gt; 0 THEN
    UPDATE PACKING SET DIRTY = aFlag WHERE CODPACKING = vCodPacking;
    COMMIT;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_packing_set_variabile</obj_name>
  <obj_hashval>ec56e4c8ae06510aa6e15fe08cbe35b1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_packing_set_variabile(INOUT acoddoc numeric, INOUT atipdoc numeric, INOUT acoddetaliu numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCodPacking NUMERIC(20,0);
BEGIN
  --Bogdan 23.09.2025 - 66750 - Packing nu se deschide daca nu exista contract pentru acel prtener + obiect
  --Florin 02.08.2024 - fixat 62900
  --Florin 25.07.2024 - fixat 62823
  --Florin 10.07.2024
  perform set_config('pkg_packing.gCodDoc', aCodDoc::varchar, FALSE);
  perform set_config('pkg_packing.gTipDoc', aTipDoc::varchar, FALSE);
  BEGIN
    SELECT CODPACKING into strict aCODDETALIU FROM PACKING
    WHERE
      CODDOC = aCODDOC
      AND TIPDOC = aTIPDOC;
    EXCEPTION WHEN OTHERS THEN
      aCODDETALIU := 0;
  END;

  IF aCodDetaliu = 0 THEN
    aCODDETALIU := NEXTVAL('SEQ_PACKING_CODPACKING');
    INSERT INTO PACKING (CODPACKING, CODDOC, TIPDOC )
    VALUES(aCODDETALIU, aCodDoc, aTipDoc);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_packing_sp_deleterecord</obj_name>
  <obj_hashval>48608b74413b4c7ed6df0575b82a3b0b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_packing_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 10.07.2024
  DELETE FROM PACKING3 P3 WHERE P3.CODPACKING2 IN
         (SELECT P2.CODPACKING2  FROM PACKING2 P2 WHERE P2.CODPACKING1 IN (SELECT P1.CODPACKING1
                                                                                             FROM PACKING P JOIN PACKING1 P1 ON P1.CODPACKING = P.CODPACKING
                                                                                             WHERE P.CODPACKING = RECID));

  DELETE FROM PACKING2 P2 WHERE P2.CODPACKING1 IN (SELECT P1.CODPACKING1
                                                                                             FROM PACKING P JOIN PACKING1 P1 ON P1.CODPACKING = P.CODPACKING
                                                                                             WHERE  P.CODPACKING = RECID);
  DELETE FROM PACKING1 P1 WHERE P1.CODPACKING IN (SELECT P.CODPACKING FROM PACKING P WHERE  P.CODPACKING = RECID);
  DELETE FROM PACKING P WHERE P.CODPACKING = RECID;


  PERFORM NotifyModif(2, RecId, 'PACKING');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_packing_sp_lockrecord</obj_name>
  <obj_hashval>136fec33f6e90e0c423432f07b8a58ae</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_packing_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 10.07.2024
  --todo
  PERFORM NotifyModif(2, RecId, 'PACKING');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_packing_sp_postrecords</obj_name>
  <obj_hashval>c522c62c4c54269aaa93a2875fa6cf78</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_packing_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCodPack1 NUMERIC(20);
  vCodPack2 NUMERIC(20);
  v_recp record;
  v_recp2 record;
BEGIN
  --Florin 10.07.2024
  SELECT CODPACKING INTO RecId FROM TMP_PACKING;
  -- golesc randurile fara date
  DELETE FROM TMP_PACKING3 pkg3 WHERE pkg3.CODPACKING2 in
         (SELECT pkg2.CODPACKING2 FROM TMP_PACKING2 pkg2 WHERE (pkg2.SSCC IS NULL or LENGTH(pkg2.SSCC) &lt; 1)
         AND  (pkg2.OBS IS NULL OR LENGTH(pkg2.OBS) &lt; 1))
         OR COALESCE(pkg3.CODREZERVATS,0) = 0 ;

  DELETE FROM TMP_PACKING2 pkg2 WHERE (pkg2.SSCC is null or LENGTH(pkg2.SSCC) &lt; 1) AND  (pkg2.OBS IS NULL OR LENGTH(pkg2.OBS) &lt; 1);

   --clean
   DELETE FROM PACKING3 PK3 WHERE PK3.CODPACKING2 IN
                (SELECT PK2.CODPACKING2 FROM PACKING2 PK2
                       JOIN PACKING1 PK1 ON PK1.CODPACKING1 = PK2.CODPACKING1
                WHERE PK1.CODPACKING = RecId);

    DELETE FROM PACKING2 PK2 WHERE pk2.codpacking1 in
                                        (SELECT pk1.codpacking1
                                         FROM PACKING1 pk1
                                         where pk1.CODPACKING = RecId);

       DELETE FROM PACKING1 pk1
              WHERE pk1.CODPACKING1 NOT IN (SELECT tpk1.CODPACKING1 FROM TMP_PACKING1 tpk1)
                          AND pk1.CODPACKING = RecId;
       --PACKING
       UPDATE PACKING pk
            set (CODPACKING, CODDOC, TIPDOC, OBS, DIRTY) =
                (select CODPACKING, CODDOC, TIPDOC, OBS, 0 from TMP_PACKING)
         WHERE pk.CODPACKING = RecId ;
       --PACKING1  - UPDATE
       UPDATE PACKING1 PK1
                SET  (CODOBIECT, CODAMB_PRIMAR, CODAMB_SECUNDAR, CODAMB_TERTIAR,
                                                CANTAMB, CANTAMBXPRIMAR, CANTAMBXSECUNDAR, CANTAMBXTERTIAR, CANTOBJ ) =
                                 (SELECT CODOBIECT,
                                                CASE WHEN CODAMB_PRIMAR &lt;&gt; 0 THEN CODAMB_PRIMAR ELSE NULL END,
                                                CASE WHEN CODAMB_SECUNDAR &lt;&gt; 0 THEN CODAMB_SECUNDAR ELSE NULL END,
                                                CASE WHEN CODAMB_TERTIAR &lt;&gt; 0 THEN CODAMB_TERTIAR ELSE NULL END,
                                                 CANTAMB, CANTAMBXPRIMAR, CANTAMBXSECUNDAR, CANTAMBXTERTIAR, CANTOBJ
                                 FROM TMP_PACKING1 tpk1
                                 WHERE tpk1.CODPACKING1 &gt; 0 and tpk1.CODPACKING1 = pk1.CODPACKING1)
         WHERE pk1.codpacking = RecId;

         FOR V_RECP IN (SELECT * FROM TMP_PACKING1 tpk1 WHERE tpk1.CODPACKING1 &lt; 0) LOOP
             vCodPack1 := NEXTVAL('SEQ_PACKING1_CODPACKING1');
             UPDATE TMP_PACKING2 tpk2 SET CODPACKING1 = vCodPack1 WHERE tpk2.CODPACKING1 = V_RECP.CODPACKING1;
             INSERT INTO PACKING1 (CODPACKING1, CODPACKING, CODDOC1, CODOBIECT, CODAMB_PRIMAR,
                                                   CODAMB_SECUNDAR, CODAMB_TERTIAR, CANTAMB,
                                                   CANTAMBXPRIMAR, CANTAMBXSECUNDAR, CANTAMBXTERTIAR, CANTOBJ)
             VALUES (vCodPack1,
                          RecId,
                          V_RECP.CODDOC1,
                          V_RECP.CODOBIECT,
                          CASE WHEN V_RECP.CODAMB_PRIMAR &lt;&gt; 0 THEN V_RECP.CODAMB_PRIMAR ELSE NULL END,
                          CASE WHEN V_RECP.CODAMB_SECUNDAR &lt;&gt; 0 THEN V_RECP.CODAMB_SECUNDAR ELSE NULL END,
                          CASE WHEN V_RECP.CODAMB_TERTIAR &lt;&gt; 0 THEN V_RECP.CODAMB_TERTIAR ELSE NULL END,
                          V_RECP.CANTAMB,
                          V_RECP.CANTAMBXPRIMAR, V_RECP.CANTAMBXSECUNDAR, V_RECP.CANTAMBXTERTIAR, V_RECP.CANTOBJ) ;
         END LOOP;

         FOR V_RECP2 IN (SELECT * FROM TMP_PACKING2 tpk2 WHERE tpk2.CODPACKING2 &lt; 0) LOOP
            vCodPack2 := NEXTVAL('SEQ_PACKING2_CODPACKING2');
            UPDATE TMP_PACKING3 tpk3 SET CODPACKING2 = vCodPack2 WHERE tpk3.CODPACKING2 = V_RECP2.CODPACKING2;
            UPDATE TMP_PACKING2 tpk2 SET CODPACKING2 = vCodPack2 WHERE tpk2.CODPACKING2 =  V_RECP2.CODPACKING2;
         END LOOP;
         --PACKING2  - INSERT (initial au fost toate sterse)
         INSERT INTO PACKING2 (CODPACKING2, CODPACKING1, SSCC, OBS, CODAMB_FINAL, CANTOBJ)
                SELECT  tpk2.codpacking2,
                        tpk2.codpacking1 ,
                        tpk2.sscc,
                        tpk2.obs,
                        tpk2.codamb_final,
                        tpk2.CANTOBJ
               FROM TMP_PACKING2 tpk2;

          --PACKING3  - INSERT (initial au fost toate sterse)
          UPDATE TMP_PACKING3 TPK3 SET CODPACKING3 = NEXTVAL('SEQ_PACKING3_CODPACKING3') WHERE TPK3.CODPACKING3 &lt; 0;
          INSERT INTO PACKING3 (
               CODPACKING3 ,
               CODPACKING2,
               CODREZERVATS,
               CANT,
               UMSEC)
           SELECT tpk3.CODPACKING3,
                    tpk3.CODPACKING2,
                    tpk3.CODREZERVATS,
                    tpk3.CANT,
                    tpk3.UMSEC
            FROM TMP_PACKING3 tpk3;
 END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_particip_sp_gotorecord</obj_name>
  <obj_hashval>27631732d3456e3bfb3b7dc52735be77</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_particip_sp_gotorecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM TMP_PARTICIP;
  INSERT INTO TMP_PARTICIP SELECT * FROM PARTICIP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_particip_sp_postrecords</obj_name>
  <obj_hashval>a2fe22ac367c7b352a9cdc1be3320053</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_particip_sp_postrecords()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  DELETE FROM PARTICIP WHERE COD NOT IN (SELECT COD FROM TMP_PARTICIP WHERE COD &gt; 0);

  FOR V_REC IN (SELECT * FROM TMP_PARTICIP) LOOP
    IF  V_REC.COD &gt; 0 THEN
      UPDATE PARTICIP
      SET
      DENUMIRE = V_REC.DENUMIRE,
      PROCENT  = V_REC.PROCENT
      WHERE
       COD = V_REC.COD;
    ELSE
      INSERT INTO PARTICIP(COD, DENUMIRE, PROCENT)
      VALUES(NEXTVAL('SEQ_PARTICIP_COD'), V_REC.DENUMIRE, V_REC.PROCENT);
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_perisabil_sp_insertrecord</obj_name>
  <obj_hashval>b9e8d0c1a00b529c4ca8b0ce928ace89</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_perisabil_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_PERISABIL(CODPERISABIL) VALUES(0);
  INSERT INTO TMP_PERISABIL1(CODPERISABIL1, Luna_Ini) VALUES(0, 1);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_perisabil_sp_lockrecord</obj_name>
  <obj_hashval>0532ffaadfb8cca3c15690785fa110a4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_perisabil_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMP numeric;
begin
  SELECT CODPERISABIL INTO TMP FROM PERISABIL WHERE CODPERISABIL = RECID FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_perisabil_sp_postrecords</obj_name>
  <obj_hashval>d9ccfa8319e253c5cf02e23170d97909</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_perisabil_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  V_REC RECORD;

begin
  if OPERATION = 0 then
    SELECT CODPERISABIL INTO RECID FROM TMP_PERISABIL;

    UPDATE PERISABIL
    SET
    (DENUMIRE, OBS) = (SELECT DENUMIRE, OBS FROM TMP_PERISABIL )
    WHERE CODPERISABIL = RECID ;

    DELETE FROM PERISABIL1 P1 WHERE P1.CODPERISABIL = RECID and not exists (SELECT TMP.CODPERISABIL1 FROM TMP_PERISABIL1 TMP WHERE TMP.CODPERISABIL1 = P1.CODPERISABIL1 );
    DELETE FROM PERISABIL2 P2 WHERE P2.CODPERISABIL = RECID and not exists (SELECT TMP.CODPERISABIL2 FROM TMP_PERISABIL2 TMP WHERE TMP.CODPERISABIL2 = P2.CODPERISABIL2 );

    for V_REC in (SELECT * FROM TMP_PERISABIL1 ) loop
      UPDATE PERISABIL1
      set
        LUNA_INI  = V_REC.LUNA_INI,
        LUNA_FIN  = V_REC.LUNA_FIN,
        NrZile    = V_REC.NrZile,
        NrZileDir = V_REC.NrZileDir,
        OBS1      = V_REC.OBS1
      where
        CODPERISABIL1 = V_REC.CODPERISABIL1 ;
    end loop;

    INSERT INTO PERISABIL1 ( CODPERISABIL1, CODPERISABIL, LUNA_INI, LUNA_FIN, NrZile, NrZileDir, OBS1 )
    SELECT nextval('SEQ_PERISABIL1_CODPERISABIL1'), RECID, LUNA_INI, LUNA_FIN, NrZile, NrZileDir, OBS1
    FROM TMP_PERISABIL1 WHERE CODPERISABIL1 &lt; 0;

    for V_REC in (SELECT * FROM TMP_PERISABIL2 ) loop
      UPDATE PERISABIL2
      set
        LUNA_INI  = V_REC.LUNA_INI,
        LUNA_FIN  = V_REC.LUNA_FIN,
        ZI_INI    = V_REC.ZI_INI,
        ZI_FIN    = V_REC.ZI_FIN,
        StocMediu = V_REC.StocMediu,
        TIPSEZON  = V_REC.TIPSEZON,
        OBS1      = V_REC.OBS1
      where
        CODPERISABIL2 = V_REC.CODPERISABIL2 ;
    end loop;

    INSERT INTO PERISABIL2 ( CODPERISABIL2, CODPERISABIL, LUNA_INI, ZI_INI, LUNA_FIN, ZI_FIN, StocMediu, TIPSEZON, OBS1 )
    SELECT nextval('SEQ_PERISABIL2_CODPERISABIL2'), RECID, LUNA_INI, ZI_INI, LUNA_FIN, ZI_FIN, StocMediu, TIPSEZON, OBS1
    FROM TMP_PERISABIL2 WHERE CODPERISABIL2 &lt; 0;
  else
    SELECT nextval('SEQ_PERISABIL_CODPERISABIL') INTO RECID;

    INSERT INTO PERISABIL ( CODPERISABIL, DENUMIRE, OBS )
    SELECT RECID, DENUMIRE, OBS FROM TMP_PERISABIL;

    INSERT INTO PERISABIL1 ( CODPERISABIL1, CODPERISABIL, LUNA_INI, LUNA_FIN, NrZile, NrZileDir, OBS1 )
    SELECT nextval('SEQ_PERISABIL1_CODPERISABIL1'), RECID, LUNA_INI, LUNA_FIN, NrZile, NrZileDir, OBS1 FROM TMP_PERISABIL1;

    INSERT INTO PERISABIL2 ( CODPERISABIL2, CODPERISABIL, LUNA_INI, ZI_INI, LUNA_FIN, ZI_FIN, StocMediu, TIPSEZON, OBS1 )
    SELECT nextval('SEQ_PERISABIL2_CODPERISABIL2'), RECID, LUNA_INI, ZI_INI, LUNA_FIN, ZI_FIN, StocMediu, TIPSEZON, OBS1 FROM TMP_PERISABIL2;
  end if;

  perform NotifyModif( Operation, RecId, 'PERISABIL');
 end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_perscontact_ct_monitor</obj_name>
  <obj_hashval>e0d93db75918d0059c1fdfab04f3f7e0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_perscontact_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_PERSCONTACT.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_52';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_perscontact_getct_monitor</obj_name>
  <obj_hashval>21f38840e859016bb49bcabdbb4fdcf7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_perscontact_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_PERSCONTACT.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_52';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_perscontact_setct_monitor</obj_name>
  <obj_hashval>f2b27797f418e5c1726e396aae7e91db</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_perscontact_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PERSCONTACT.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_perscontact_sp_deleterecord</obj_name>
  <obj_hashval>6088e1b51da3086370c7c0000daf5b22</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_perscontact_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDoc varchar;
BEGIN
  --Florin 01.06.2023 - monitor
  --Florin 01.10.2020 - fixat #40194
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_perscontact_setct_monitor('MON_52');
  PERFORM PKG_PERSCONTACT_SP_LOCKRECORD( RecId);

  IF (SELECT WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, current_setting('PKG_GLOBALS.USERID', true)::numeric, 'MON_52')) THEN
    SELECT 'Pers.contact. "' || nume || ' ' || prenume || '"'
    INTO aDoc
    FROM NPERSCONTACT
    WHERE codpersc = recid;

    PERFORM pkg_userfirme_postlogcucommit('NPERSCONTACT', current_setting('PKG_GLOBALS.USERNAME', TRUE), 'S', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), current_setting('PKG_GLOBALS.SUBUNITATE', true)::NUMERIC, null, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  DELETE FROM NPERSCONTACT WHERE CODPERSC = RecId;

  PERFORM NotifyModif( 2, RecId, 'NPERSCONTACT');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_perscontact_sp_gotorecord</obj_name>
  <obj_hashval>37727aac77d24fbc756f06f4438fbe06</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_perscontact_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Florin 16.11.2021 - fixat 52001
  perform pkg_perscontact_setct_monitor('MON_52');
  INSERT INTO TMP_NPERSCONTACT(CODPERSC, NUME, PRENUME, TELEFON, EMAIL, FUNCTIE, DATANASTERE, RZONA, ID, TIP, CODBANKCONT, CODPART, IMPLICIT, Obs)
  SELECT CODPERSC, NUME, PRENUME, TELEFON, EMAIL, FUNCTIE, DATANASTERE, RZONA, ID, TIP, CODBANKCONT, CODPART, COALESCE( IMPLICIT, 0), Obs
  FROM NPERSCONTACT WHERE CODPERSC = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_perscontact_sp_insertrecord</obj_name>
  <obj_hashval>e58d708b2a2e925f64e841e3db1d7e90</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_perscontact_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NPERSCONTACT(CODPERSC) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_perscontact_sp_lockrecord</obj_name>
  <obj_hashval>439e111f07a2cff64528b42a55bce958</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_perscontact_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CODPERSC INTO Tmp FROM NPERSCONTACT WHERE CODPERSC = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_perscontact_sp_postrecords</obj_name>
  <obj_hashval>e55e8e21599e3e520f6ff84f151e3e80</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_perscontact_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDoc varchar;
BEGIN
  --Florin 01.06.2023 - monitor
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_perscontact_setct_monitor('MON_52');
  IF  Operation = 0 THEN
    SELECT CODPERSC INTO RecId FROM TMP_NPERSCONTACT;

    UPDATE NPERSCONTACT
    SET
    (CODPERSC, NUME, PRENUME, TELEFON, EMAIL, FUNCTIE, DATANASTERE, RZONA, ID, TIP, CODBANKCONT, CODPART, IMPLICIT, Obs)
    =
    (SELECT CODPERSC, NUME, PRENUME, TELEFON, EMAIL, FUNCTIE, DATANASTERE, RZONA, ID, TIP, CODBANKCONT, CODPART, IMPLICIT, Obs FROM TMP_NPERSCONTACT)
    WHERE
     CODPERSC = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_NPERSCONTACT_CODPERSC') INTO RecId;

    INSERT INTO NPERSCONTACT(CODPERSC, NUME, PRENUME, TELEFON, EMAIL, FUNCTIE, DATANASTERE, RZONA, ID, TIP, CODBANKCONT, CODPART, IMPLICIT, Obs)
    SELECT RecId, NUME, PRENUME, TELEFON, EMAIL, FUNCTIE, DATANASTERE, RZONA, ID, TIP, CODBANKCONT, CODPART, IMPLICIT, Obs
    FROM TMP_NPERSCONTACT;
  END IF;

  SELECT 'Pers.contact. "' || nume || ' ' || prenume || '"'
  INTO aDoc
  FROM NPERSCONTACT
  WHERE codpersc = recid;

  PERFORM ValidPostLog( 'MON_52',
                        Case when Operation = 0 then 'M' else 'A' end,
                        recid,
                        TO_NUMBER((current_setting('PKG_GLOBALS.SUBUNITATE', true)),'999999999999999999'),
                        null,
                        aDoc);

  PERFORM NotifyModif( Operation, RecId, 'NPERSCONTACT');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pgs_sp_deleterecord</obj_name>
  <obj_hashval>3578fac598f7f700131cdcdb85f3f325</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pgs_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_PGS_SP_LOCKRECORD( RecId);
  DELETE FROM PGS1 WHERE codPGS = RecId;
  DELETE FROM PGS  WHERE codPGS = RecId;
  PERFORM NotifyModif( 2, RecId, 'PGS');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pgs_sp_gotorecord</obj_name>
  <obj_hashval>86458a4872661d9935542cd8aaa66417</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pgs_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_PGS(codPGS, Denumire)
  (SELECT codPGS, Denumire FROM PGS WHERE codPGS = RecId);

  INSERT INTO TMP_PGS1(codPGS1, codPGS, IndexLocal, CodCurs, CodTema)
  (SELECT codPGS1, codPGS, IndexLocal, CodCurs, CodTema FROM PGS1 WHERE codPGS = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pgs_sp_insertrecord</obj_name>
  <obj_hashval>5970535549ee14cec712028ea1da880b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pgs_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_PGS(codPGS) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pgs_sp_lockrecord</obj_name>
  <obj_hashval>46135ed3437c6bac3bfd11f80849061e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pgs_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT codPGS INTO Tmp FROM PGS WHERE codPGS = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pgs_sp_postrecords</obj_name>
  <obj_hashval>2c837834ac1f152af04e7731f1e01b28</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pgs_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  vRecNo NUMERIC := 0;
  vAn NUMERIC := 0;
  vLuna NUMERIC := 0;
  vCod numeric;
begin
  IF  Operation = 0 THEN
    SELECT codPGS INTO RecId FROM TMP_PGS;

    UPDATE PGS SET (Denumire)  = (SELECT Denumire FROM TMP_PGS) WHERE codPGS = RecId;

    DELETE FROM PGS1 WHERE codPGS = RecId and codPGS1 NOT IN (SELECT codPGS1 FROM TMP_PGS1);

    FOR v_rec IN (SELECT * FROM TMP_PGS1 WHERE codPGS1 &gt; 0) LOOP
      UPDATE PGS1
      SET
      INDEXLOCAL = V_REC.INDEXLOCAL,
      CODCURS    = V_REC.CODCURS
      WHERE
       codPGS1 = v_rec.codPGS1;
    END LOOP;

    INSERT INTO PGS1(codPGS1, codPGS, IndexLocal, CodCurs, CodTema)
    SELECT NEXTVAL('SEQ_PGS1_CODPGS1'), RecId, IndexLocal, CodCurs, CodTema FROM TMP_PGS1 WHERE codPGS1 &lt; 0;
  ELSE
    SELECT NEXTVAL('SEQ_PGS_CODPGS') INTO RecId;

    INSERT INTO PGS(codPGS, Denumire)
    (SELECT RecId, Denumire FROM Tmp_PGS);

    INSERT INTO PGS1(codPGS1, codPGS, IndexLocal, CodCurs, CodTema)
    SELECT NEXTVAL('SEQ_PGS1_CODPGS1'), RecId, IndexLocal, CodCurs, CodTema FROM TMP_PGS1;
  END IF;

  PERFORM NotifyModif( Operation, RecId, 'PGS');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plancontsec_g_codcontruls</obj_name>
  <obj_hashval>5a8796b3dd8af2c552004c15d1274c6e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plancontsec_g_codcontruls(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_PLANCONTSEC.g_CodcontrulS', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plancontsec_g_codconts1</obj_name>
  <obj_hashval>90458b33aca07a1d1ee9eaa163115de4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plancontsec_g_codconts1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_PLANCONTSEC.g_CodContS1', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plancontsec_g_codcontsolds</obj_name>
  <obj_hashval>261cbb9292097b03fee9ad18a7384db1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plancontsec_g_codcontsolds(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_PLANCONTSEC.g_CodContSoldS', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plancontsec_get_cont_cod_caract_luna</obj_name>
  <obj_hashval>5c662d40640ab8bdee3331e3e9ccb139</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plancontsec_get_cont_cod_caract_luna(INOUT wme_result numeric, INOUT acodconts numeric, INOUT aan numeric, INOUT aluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODCONTS1 numeric := -1;
begin
  BEGIN
    SELECT  DISTINCT COALESCE( LAST_VALUE( CODCONTS1) OVER (  ORDER BY AnStart , LunaStart ) , 0)
    INTO aCODCONTS1
    FROM NCONTS1
    WHERE
       CODCONTS = aCODCONTS AND  ANSTART * 12 + LUNASTART &lt;= aAN * 12 + aLUNA;
  EXCEPTION WHEN OTHERS THEN
    WME_Result :=  -1;
    RETURN;
  END;

  WME_Result :=  aCODCONTS1;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plancontsec_getg_codcontruls</obj_name>
  <obj_hashval>f1f12aded9beae26b409725d4c5abbf0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plancontsec_getg_codcontruls(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_PLANCONTSEC.g_CodcontrulS', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plancontsec_getg_codconts1</obj_name>
  <obj_hashval>41927f58514ea69ed1a017a0ce099b97</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plancontsec_getg_codconts1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_PLANCONTSEC.g_CodContS1', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plancontsec_getg_codcontsolds</obj_name>
  <obj_hashval>bd8db5f755e4d932404fe7cc6fd65177</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plancontsec_getg_codcontsolds(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_PLANCONTSEC.g_CodContSoldS', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plancontsec_getinitializari</obj_name>
  <obj_hashval>aaa679b1fd94966e7184a2ac804138ab</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plancontsec_getinitializari(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_PLANCONTSEC.INITIALIZARI', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plancontsec_initializari</obj_name>
  <obj_hashval>129243a72e087a8d6f397591f8ce92a4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plancontsec_initializari(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_PLANCONTSEC.INITIALIZARI', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plancontsec_set_flag_initializari</obj_name>
  <obj_hashval>7285d2fc33a48aa5e95f16adfa9fb2fb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plancontsec_set_flag_initializari(flag numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANCONTSEC.INITIALIZARI',to_char(FLAG,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plancontsec_setg_codcontruls</obj_name>
  <obj_hashval>dc42ecd4c9b4d456f94ec78eaf794944</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plancontsec_setg_codcontruls(ag_codcontruls numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANCONTSEC.g_CodcontrulS',to_char(ag_CodcontrulS,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plancontsec_setg_codconts1</obj_name>
  <obj_hashval>894ea954f04252f80d506cfdf43d57bf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plancontsec_setg_codconts1(ag_codconts1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANCONTSEC.g_CodContS1',to_char(ag_CodContS1,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plancontsec_setg_codcontsolds</obj_name>
  <obj_hashval>b003c728436fff240887129e575c95c1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plancontsec_setg_codcontsolds(ag_codcontsolds numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANCONTSEC.g_CodContSoldS',to_char(ag_CodContSoldS,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plancontsec_setinitializari</obj_name>
  <obj_hashval>4fb33150fb9195df76bfd0c28e14b919</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plancontsec_setinitializari(ainitializari numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANCONTSEC.INITIALIZARI',aINITIALIZARI::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plancontsec_sp_deleterecord</obj_name>
  <obj_hashval>d6d65cbdfcbb7d7bd8f116ab36ef44c1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plancontsec_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 20.04.2023 - sinc. oracle
  PERFORM PKG_PLANCONTSEC_SP_LOCKRECORD( RecId);
  PERFORM PKG_CFGTABLES_EXT_DELETERECORD (recId, 525);
  delete from ncontS1 where codcontS = recid;
  DELETE FROM NCONTS  WHERE CodContS = RecId;
  PERFORM NotifyModif( 2, RecId, 'NCONTS');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plancontsec_sp_gotorecord</obj_name>
  <obj_hashval>82cb56e485e0fbf8c283b5c348fdc5f1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plancontsec_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  glb_g_CodContSoldS numeric;
  glb_g_CodContRulS  numeric;
  V_REC              RECORD;
  aANSFARSIT         numeric;
  aLUNASFARSIT       numeric;
BEGIN
  --Florin 21.11.2024 - sinc. Oracle
  --Bogdan 07.01.2021
  INSERT INTO TMP_NCONTS (CodContS, Simbol, Clasa, Den_cont, Name, TipCont, VizibilBalanta, BalantaSintetica, Nivel, CodParinte)
  SELECT CodContS, Simbol, Clasa, Den_cont, Name, TipCont, VizibilBalanta, BalantaSintetica, Nivel, CodParinte
  FROM NCONTS WHERE CodContS = RecId;

  INSERT INTO TMP_NCONTS1 (CodContS1, CodContS, CodCont, NrAnalitice, ContTransfD, ContTransfC, ContInkidSold, Participatiune, Sincronizare, anstart, lunastart)
  SELECT CodContS1, CodContS, CodCont, NrAnalitice, ContTransfD, ContTransfC, ContInkidSold, Participatiune, Sincronizare, anstart, lunastart
  FROM NCONTS1 WHERE CodContS = RecId;

  aANSFARSIT   := 0;
  aLUNASFARSIT := 0;

  FOR V_REC IN (SELECT CODCONTS1, ANSTART, LUNASTART FROM TMP_NCONTS1 ORDER BY ANSTART * 12 + LUNASTART desc) LOOP
    IF (aANSFARSIT &lt;&gt; 0) AND (aLUNASFARSIT &lt;&gt; 0) THEN
      UPDATE TMP_NCONTS1
      SET ANSFARSIT = aANSFARSIT, LUNASFARSIT = aLUNASFARSIT
      WHERE
        CODCONTS1 = V_REC.CODCONTS1;
    END IF;

    select newan, newluna
    from PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA (V_REC.ANSTART, V_REC.LUNASTART, aANSFARSIT, aLUNASFARSIT)
    into
      aANSFARSIT, aLUNASFARSIT;
  END LOOP;

  INSERT INTO TMP_NCONTSOLDS (CodContSoldS, CodContS, SoldID, SoldIC, SoldVID, SoldVIC, An, Luna)
  SELECT CodContSoldS, CodContS, SoldID, SoldIC, SoldVID, SoldVIC, An, Luna
  FROM NCONTSOLDS
  WHERE
    CodContS = RecId
    AND AN = GetANLUCRU()
    AND LUNA = 1;

  SELECT MAX (COALESCE (CodContSoldS, 0)) INTO glb_g_CodContSoldS FROM NCONTSOLDS WHERE CodContS = RecId;

  INSERT INTO TMP_NCONTRULS (CodcontrulS, CodContS, RulajPD, RulajPC, RulajCD, RulajCC, RulajVPD, RulajVPC, RulajVCD, RulajVCC, An, Luna)
  SELECT CodcontrulS, CodContS, RulajPD, RulajPC, RulajCD, RulajCC, RulajVPD, RulajVPC, RulajVCD, RulajVCC, An, Luna
  FROM NCONTRULS
  WHERE
    CodContS = RecId
    AND AN = TO_NUMBER (current_setting ('PKG_GLOBALS.ANLUCRU', true) ,'999999999999999999')
    AND LUNA = 1;

  SELECT MAX (COALESCE (CodcontrulS, 0)) INTO glb_g_CodContRulS FROM NCONTRULS WHERE CodContS = RecId;

  perform pkg_plancontsec_setg_codcontsolds (glb_g_CodContSoldS);
  perform pkg_plancontsec_setg_codcontruls (glb_g_CodContRulS);
  PERFORM PKG_CFGTABLES_EXT_GOTORECORD(525);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plancontsec_sp_insertrecord</obj_name>
  <obj_hashval>9f1a0a63a6fd7a43af1e5f49fb4c0093</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plancontsec_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 20.04.2023 - sinc. Oracle
  INSERT INTO TMP_NCONTS(CodContS) VALUES(0);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(525);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plancontsec_sp_lockrecord</obj_name>
  <obj_hashval>ddf573e8dd183d0719639a1744f3d496</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plancontsec_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodContS INTO Tmp FROM NCONTS WHERE CodContS = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plancontsec_sp_postrecords</obj_name>
  <obj_hashval>b9b978f620fae99f04404f85fbd1ce61</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plancontsec_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  vRecNo NUMERIC := 0;
  vAn    NUMERIC := 0;
  vLuna  NUMERIC := 0;
  vCod   numeric;
BEGIN
  --Florin 20.04.2023 - sinc. Oracle
  --Adina 15.03.2021 - prc_al_refresh
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT (525);
  IF  Operation = 0 THEN
    SELECT CodContS INTO RecId FROM TMP_NCONTS;

    UPDATE NCONTS
    SET
    (Simbol, Clasa, Den_cont, Name, TipCont, VizibilBalanta, BalantaSintetica, Nivel, CodParinte)
    =
    (SELECT Simbol, Clasa, Den_cont, Name, TipCont, VizibilBalanta, BalantaSintetica, Nivel, CodParinte FROM TMP_NCONTS)
    WHERE
     CodContS = RecId;

    DELETE FROM NCONTS1 WHERE CodContS = RecId and CodContS1 NOT IN (SELECT CodContS1 FROM TMP_NCONTS1);

    INSERT INTO NCONTS1(CodContS1, CodContS, CodCont, NrAnalitice, ContTransfD, ContTransfC, ContInkidSold, Participatiune, Sincronizare, anstart, lunastart)
    SELECT NEXTVAL('SEQ_NCONTS1_CODCONTS1'), RecId, CodCont, NrAnalitice, ContTransfD, ContTransfC, ContInkidSold, Participatiune, Sincronizare, anstart, lunastart
    FROM TMP_NCONTS1 WHERE CodContS1 &lt; 0;

    FOR V_REC IN (SELECT * FROM TMP_NCONTS1 WHERE COALESCE( CodContS1, -1) &gt; 0 ORDER BY CodContS1 ) LOOP
      UPDATE NCONTS1
      SET
      NRANALITICE    = v_rec.NrAnalitice,
      ContTransfD    = v_rec.ContTransfD,
      ContTransfC    = v_rec.ContTransfC,
      ContInkidSold  = v_rec.ContInkidSold,
      Participatiune = v_rec.Participatiune,
      Sincronizare   = v_rec.Sincronizare,
      CodCont        = v_rec.CodCont
      WHERE
       CodContS1 = v_rec.CodContS1;
    END LOOP;

    IF  current_setting('PKG_PLANCONTSEC.INITIALIZARI', true)::numeric = 1 THEN
      FOR V_REC IN (SELECT * FROM TMP_NCONTSOLDS) LOOP
        IF  V_REC.CODCONTSOLDS &lt; 0 THEN
          INSERT INTO NCONTSOLDS(CodContSoldS, SoldID, SoldIC, SoldVID, SoldVIC, CodContS, An, Luna)
          VALUES(NEXTVAL('SEQ_NCONTSOLDS_CODCONTSOLDS'), V_REC.SoldID, V_REC.SoldIC, V_REC.SoldVID, V_REC.SoldVIC, RecId, V_REC.An, V_REC.Luna);
        ELSE
          UPDATE NCONTSOLDS
          SET
          SoldID  = V_REC.SOLDID,
          SoldIC  = V_REC.SOLDIC,
          SoldVID = V_REC.SOLDVID,
          SoldVIC = V_REC.SOLDVIC
          WHERE
           CODCONTSOLDS = V_REC.CODCONTSOLDS;
        END IF;
      END LOOP;

      FOR V_REC IN (SELECT * FROM TMP_NCONTRULS) LOOP
        IF  V_REC.CODCONTRULS &lt; 0 THEN
          INSERT INTO NCONTRULS(CodContRulS, RulajPD, RulajPC, CodContS, RulajCD, RulajCC, RulajVPD, RulajVPC, RulajVCD, RulajVCC, An, Luna)
          VALUES(NEXTVAL('SEQ_NCONTRULS_CODCONTRULS'), V_REC.RulajPD, V_REC.RulajPC, RecId, V_REC.RulajCD, V_REC.RulajCC, V_REC.RulajVPD, V_REC.RulajVPC, V_REC.RulajVCD, V_REC.RulajVCC, V_REC.An, V_REC.Luna);
        ELSE
          UPDATE NCONTRULS
          SET
          RulajPD = V_REC.RULAJPD,
          RulajPC = V_REC.RULAJPC,
          RulajVPD = V_REC.RULAJVPD,
          RulajVPC = V_REC.RULAJVPC
          WHERE
           CODCONTRULS = V_REC.CODCONTRULS;
        END IF;
      END LOOP;
    END IF;
  ELSE
    SELECT NEXTVAL('SEQ_NCONTS_CODCONTS') INTO RecId;
    PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('NCONTS', RecId);

    INSERT INTO NCONTS(CodContS, Simbol, Clasa, Den_cont, Name, TipCont, VizibilBalanta, BalantaSintetica, Nivel, CodParinte)
    SELECT RecId, Simbol, Clasa, Den_cont, Name, TipCont, VizibilBalanta, BalantaSintetica, Nivel, CodParinte
    FROM TMP_NCONTS;

    INSERT INTO NCONTS1(CodContS1, CodContS, CodCont, NrAnalitice, Participatiune, Sincronizare, Conttransfd, Conttransfc, Continkidsold, anstart, lunastart)
    SELECT NEXTVAL('SEQ_NCONTS1_CODCONTS1'), RecId, CodCont, NrAnalitice, Participatiune, Sincronizare, Conttransfd, Conttransfc, Continkidsold, anstart, lunastart
    FROM TMP_NCONTS1;

    INSERT INTO NCONTSOLDS(CodContSoldS, CodContS, SoldID, SoldIC, SoldVID, SoldVIC, An, Luna)
    SELECT NEXTVAL('SEQ_NCONTSOLDS_CODCONTSOLDS'), RecId, SoldID, SoldIC, SoldVID, SoldVIC, An, Luna
    FROM TMP_NCONTSOLDS;

    INSERT INTO NCONTRULS(CodContrulS, CodContS, RulajPD, RulajPC, RulajCD, RulajCC, RulajVPD, RulajVPC, RulajVCD, RulajVCC, An, Luna)
    SELECT NEXTVAL('SEQ_NCONTRULS_CODCONTRULS'), RecId, RulajPD, RulajPC, RulajCD, RulajCC, RulajVPD, RulajVPC, RulajVCD, RulajVCC, An, Luna
    FROM TMP_NCONTRULS;
  END IF;

  CALL PRC_AL_REFRESH('nconts1',  RecId);
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS(525);
  PERFORM NotifyModif( Operation, RecId, 'NCONTS');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconttert_g_codcontrult</obj_name>
  <obj_hashval>f39c94c85c3ff436ba599a7c67a9b565</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconttert_g_codcontrult(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANCONTTERT.g_CodContRulT', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconttert_g_codcontsoldt</obj_name>
  <obj_hashval>2761098d1d89ac9cfa742b27ae58a292</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconttert_g_codcontsoldt(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANCONTTERT.g_CodContSoldT', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconttert_g_codcontt1</obj_name>
  <obj_hashval>fec53c9971f0e9cd771fc259be88b26b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconttert_g_codcontt1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANCONTTERT.g_CodContT1', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconttert_get_cont_cod_caract_luna</obj_name>
  <obj_hashval>89ae445a5fa7504cc8607f1e45eead21</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconttert_get_cont_cod_caract_luna(INOUT wme_result numeric, INOUT acodcontt numeric, INOUT aan numeric, INOUT aluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodContT1 numeric := -1;
begin
  BEGIN
    SELECT DISTINCT ON (CODCONTt) INTO aCODCONTT1 LAST_VALUE(CODCONTt1)  OVER ANLUNA CODCODCONT1
    FROM NCONTT1
    WHERE
      CODCONTt = aCODCONTT
      AND ANSTART * 12  + LUNASTART &lt;= aAN * 12 + aLUNA
    WINDOW ANLUNA AS (PARTITION BY CODCONTt ORDER BY ANSTART * 12 + LUNASTART RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING);


  /*
  SELECT COALESCE( Max( CodContT1) KEEP (Dense_Rank  LAST  ORDER BY AnStart , LunaStart ) , 0)
  FROM NCONTT1
  WHERE
     CodContT = aCodContT AND  ANSTART * 12 + LUNASTART &lt;= aAN * 12 + aLUNA;
  */
  EXCEPTION WHEN OTHERS THEN
    WME_Result :=  -1;
    RETURN;
  END;

  WME_Result :=  aCodContT1;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconttert_getg_codcontt1</obj_name>
  <obj_hashval>595bd58c17815dde80b76803b05787e3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconttert_getg_codcontt1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANCONTTERT.g_CodContT1', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconttert_getinitializari</obj_name>
  <obj_hashval>1346eb151083ab62a169e92d7f661930</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconttert_getinitializari(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANCONTTERT.INITIALIZARI', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconttert_initializari</obj_name>
  <obj_hashval>4d722da18eaaa442d3f9c08669e31c6c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconttert_initializari(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANCONTTERT.INITIALIZARI', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconttert_set_flag_initializari</obj_name>
  <obj_hashval>1c596fc4bc4ece81e0926411aece0be4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconttert_set_flag_initializari(flag numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANCONTTERT.INITIALIZARI',to_char(FLAG,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconttert_setg_codcontrult</obj_name>
  <obj_hashval>d58e7ef6c73982ecbebc322b2071eebf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconttert_setg_codcontrult(ag_codcontrult numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANCONTTERT.g_CodContRulT',to_char(ag_CodContRulT,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconttert_setg_codcontsoldt</obj_name>
  <obj_hashval>238a91e4984ae6c2a781e555cef03f91</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconttert_setg_codcontsoldt(ag_codcontsoldt numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANCONTTERT.g_CodContSoldT',to_char(ag_CodContSoldT,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconttert_setg_codcontt1</obj_name>
  <obj_hashval>c590c07b80e51608c4ec6180e6b02e10</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconttert_setg_codcontt1(ag_codcontt1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANCONTTERT.g_CodContT1',to_char(ag_CodContT1,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconttert_setinitializari</obj_name>
  <obj_hashval>fffc0593e50c6923ab260b3d258fb12a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconttert_setinitializari(ainitializari numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANCONTTERT.INITIALIZARI',to_char(aINITIALIZARI,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconttert_sp_deleterecord</obj_name>
  <obj_hashval>dddaac0c4c86029f15c31a2a5cd504b4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconttert_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_PLANCONTTERT_SP_LOCKRECORD( RecId);
  DELETE FROM ncontt1 WHERE codcontt = recid;
  DELETE FROM NCONTT  WHERE CodContT = RecId;
  PERFORM NotifyModif( 2, RecId, 'NCONTT');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconttert_sp_gotorecord</obj_name>
  <obj_hashval>fd2db99872fc7c4698c4798bdc60cc0d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconttert_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  glb_g_CodContSoldT numeric;
  glb_g_CodContRulT  numeric;
  V_REC              RECORD;
  aANSFARSIT         numeric;
  aLUNASFARSIT       numeric;
begin
  --Bogdan 23.09.2020
  INSERT INTO TMP_NCONTT (CodContT, Simbol, Clasa, Den_cont, Name, TipCont, VizibilBalanta, BalantaSintetica, Nivel, CodParinte)
  SELECT CodContT, Simbol, Clasa, Den_cont, Name, TipCont, VizibilBalanta, BalantaSintetica, Nivel, CodParinte
  FROM NCONTT
  WHERE CodContT = RecId;

  INSERT INTO TMP_NCONTT1 (CodContT1, CodContT, NrAnalitice, ContTransfD, ContTransfC, ContInkidSold, Participatiune, Sincronizare, anstart, lunastart)
  SELECT CodContT1, CodContT, NrAnalitice, ContTransfD, ContTransfC, ContInkidSold, Participatiune, Sincronizare, anstart, lunastart
  FROM NCONTT1
  WHERE CodContT = RecId;

  aANSFARSIT   := 0;
  aLUNASFARSIT := 0;

  FOR V_REC IN (SELECT CodContT1, ANSTART, LUNASTART FROM TMP_NCONTT1 ORDER BY ANSTART * 12 + LUNASTART desc) LOOP
    IF (aANSFARSIT &lt;&gt; 0) AND (aLUNASFARSIT &lt;&gt; 0) THEN
      UPDATE TMP_NCONTT1 SET ANSFARSIT = aANSFARSIT, LUNASFARSIT = aLUNASFARSIT WHERE CodContT1 = V_REC.CodContT1;
    END IF;

    select PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA.newAn ,PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA.newLuna
    from  PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA (V_REC.ANSTART, V_REC.LUNASTART, aANSFARSIT, aLUNASFARSIT) into aANSFARSIT, aLUNASFARSIT ;
  END LOOP;

  perform set_config ('PKG_PLANCONTTERT.g_CodContT1', (COALESCE (current_setting ('PKG_PLANCONTTERT.g_CodContT1', true)::numeric , 0))::varchar ,false);

  INSERT INTO TMP_NCONTSOLDT (CodContSoldT, CodContT, SoldID, SoldIC, SoldVID, SoldVIC, An, Luna)
  SELECT CodContSoldT, CodContT, SoldID, SoldIC, SoldVID, SoldVIC, An, Luna
  FROM NCONTSOLDT
  WHERE CodContT = RecId AND AN = getAnLucru() AND LUNA = 1;

  SELECT MAX (COALESCE (CodContSoldT, 0)) INTO glb_g_CodContSoldT FROM NCONTSOLDT WHERE CodContT = RecId;

  perform set_config ('PKG_PLANCONTTERT.g_CodContSoldT',coalesce(glb_g_CodContSoldT,0)::varchar ,false);

  INSERT INTO TMP_NCONTRULT (CodContRulT, CodContT, RulajPD, RulajPC, RulajCD, RulajCC, RulajVPD, RulajVPC, RulajVCD, RulajVCC, An, Luna)
  SELECT CodContRulT, CodContT, RulajPD, RulajPC, RulajCD, RulajCC, RulajVPD, RulajVPC, RulajVCD, RulajVCC, An, Luna
  FROM NCONTRULT
  WHERE CodContT = RecId AND AN = getAnLucru() AND LUNA = 1;

  SELECT MAX (COALESCE (CodContRulT, 0)) INTO glb_g_CodContRulT FROM NCONTRULT WHERE CodContT = RecId;

  perform set_config ('PKG_PLANCONTTERT.g_CodContRulT',coalesce(glb_g_CodContRulT , 0)::varchar ,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconttert_sp_insertrecord</obj_name>
  <obj_hashval>97d3e89d71a307c08a4c93a1a3dc4e61</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconttert_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NCONTT(CodContT) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconttert_sp_postrecords</obj_name>
  <obj_hashval>3f7ee52ea5de45004fd4c7854f6978a5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconttert_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  vRecNo NUMERIC := 0;
  vAn    NUMERIC := 0;
  vLuna  NUMERIC := 0;
  vCod   numeric;
BEGIN
  --Adina 15.03.2021 - prc_al_refresh
  IF  Operation = 0 THEN
    SELECT CodContT INTO RecId FROM TMP_NCONTT;

    UPDATE NCONTT
    SET
    (Simbol, Clasa, Den_cont, Name, TipCont, VizibilBalanta, BalantaSintetica, Nivel, CodParinte)
    =
    (SELECT Simbol, Clasa, Den_cont, Name, TipCont, VizibilBalanta, BalantaSintetica, Nivel, CodParinte FROM TMP_NCONTT)
    WHERE
     CodContT = RecId;

    DELETE FROM NCONTT1 WHERE CodContT = RecId and CodContT1 NOT IN (SELECT CodContT1 FROM TMP_NCONTT1);

    INSERT INTO NCONTT1(CodContT1, CodContT, NrAnalitice, ContTransfD, ContTransfC, ContInkidSold, Participatiune, Sincronizare, anstart, lunastart)
    SELECT NEXTVAL('SEQ_NCONTT1_CODCONTT1'), RecId, NrAnalitice, ContTransfD, ContTransfC, ContInkidSold, Participatiune, Sincronizare, anstart, lunastart
    FROM TMP_NCONTT1 WHERE CodContT1 &lt; 0;

    FOR V_REC IN (SELECT * FROM TMP_NCONTT1 WHERE COALESCE( CodContT1, -1) &gt; 0  ORDER BY CodContT1 ) LOOP
      UPDATE NCONTT1
      SET
      NRANALITICE    = v_rec.NrAnalitice,
      ContTransfD    = v_rec.ContTransfD,
      ContTransfC    = v_rec.ContTransfC,
      ContInkidSold  = v_rec.ContInkidSold,
      Participatiune = v_rec.Participatiune,
      Sincronizare   = v_rec.Sincronizare
      WHERE
       CodContT1 = v_rec.CodContT1;
    END LOOP;

    IF  TO_NUMBER((current_setting('PKG_PLANCONTTERT.INITIALIZARI', true)),'999999999999999999') = 1 THEN
      FOR V_REC IN (SELECT * FROM TMP_NCONTSOLDT) LOOP
        IF  V_REC.CodContSoldT &lt; 0 THEN
          INSERT INTO NCONTSOLDT(CodContSoldT, SoldID, SoldIC, SoldVID, SoldVIC, CodContT, An, Luna)
          VALUES(NEXTVAL('SEQ_NCONTSOLDT_CODCONTSOLDT'), V_REC.SoldID, V_REC.SoldIC, V_REC.SoldVID, V_REC.SoldVIC, RecId, V_REC.An, V_REC.Luna);
        ELSE
          UPDATE NCONTSOLDT
          SET
          SoldID  = V_REC.SOLDID,
          SoldIC  = V_REC.SOLDIC,
          SoldVID = V_REC.SOLDVID,
          SoldVIC = V_REC.SOLDVIC
          WHERE
           CodContSoldT = V_REC.CodContSoldT;
        END IF;
      END LOOP;

      FOR V_REC IN (SELECT * FROM TMP_NCONTRULT) LOOP
        IF  V_REC.CodContRulT &lt; 0  THEN
          INSERT INTO NCONTRULT(CodContRulT, RulajPD, RulajPC, CodContT, RulajCD, RulajCC, RulajVPD, RulajVPC, RulajVCD, RulajVCC, An, Luna)
          VALUES(NEXTVAL('SEQ_NCONTRULT_CODCONTRULT'), V_REC.RulajPD, V_REC.RulajPC, RecId, V_REC.RulajCD, V_REC.RulajCC, V_REC.RulajVPD, V_REC.RulajVPC, V_REC.RulajVCD, V_REC.RulajVCC, V_REC.An, V_REC.Luna);
        ELSE
          UPDATE NCONTRULT
          SET
          RulajPD  = V_REC.RULAJPD,
          RulajPC  = V_REC.RULAJPC,
          RulajVPD = V_REC.RULAJVPD,
          RulajVPC = V_REC.RULAJVPC
          WHERE
           CodContRulT = V_REC.CodContRulT;
        END IF;
      END LOOP;
    END IF;
  ELSE
    SELECT NEXTVAL('SEQ_NCONTT_CODCONTT') INTO RecId;

    INSERT INTO NCONTT(CodContT, Simbol, Clasa, Den_cont, Name, TipCont, VizibilBalanta, BalantaSintetica, Nivel, CodParinte)
    SELECT RecId, Simbol, Clasa, Den_cont, Name, TipCont, VizibilBalanta, BalantaSintetica, Nivel, CodParinte
    FROM TMP_NCONTT;

    INSERT INTO NCONTT1(CodContT1, CodContT, NrAnalitice, Participatiune, Sincronizare, Conttransfd, Conttransfc, Continkidsold, anstart, lunastart)
    SELECT NEXTVAL('SEQ_NCONTT1_CODCONTT1'), RecId, NrAnalitice, Participatiune, Sincronizare, Conttransfd, Conttransfc, Continkidsold, anstart, lunastart
    FROM TMP_NCONTT1;

    INSERT INTO NCONTSOLDT(CodContSoldT, CodContT, SoldID, SoldIC, SoldVID, SoldVIC, An, Luna)
    SELECT NEXTVAL('SEQ_NCONTSOLDT_CODCONTSOLDT'), RecId, SoldID, SoldIC, SoldVID, SoldVIC, An, Luna
    FROM TMP_NCONTSOLDT;

    INSERT INTO NCONTRULT(CodContRulT, CodContT, RulajPD, RulajPC, RulajCD, RulajCC, RulajVPD, RulajVPC, RulajVCD, RulajVCC, An, Luna)
    SELECT NEXTVAL('SEQ_NCONTRULT_CODCONTRULT'), RecId, RulajPD, RulajPC, RulajCD, RulajCC, RulajVPD, RulajVPC, RulajVCD, RulajVCC, An, Luna
    FROM TMP_NCONTRULT;
  END IF;

  CALL PRC_AL_REFRESH('ncontt1',  RecId);
  PERFORM NotifyModif( Operation, RecId, 'NCONTT');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_echiv_constante</obj_name>
  <obj_hashval>ff6cd8fb2066ceaf0bece8640d673e00</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_echiv_constante()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  V_REC_V RECORD;
  NEEDECHIV     numeric := 0;
  aCODCONSTLUNA numeric;
begin
  --Bogdan 09.02.2021
  FOR V_REC IN (SELECT CL.*
                FROM CONSTLUNA CL, CONST1 C1
                WHERE CL.CODCONST1 = C1.CODCONST1
                  AND C1.TIP    IN (1, 2, 20)
                  AND CL.ANSTART * 12 + CL.LUNASTART = (SELECT MAX (CL2.ANSTART * 12 + CL2.LUNASTART)
                                                        FROM CONSTLUNA CL2
                                                        WHERE CODCONST1 = CL.CODCONST1 AND CL2.ANSTART * 12 + CL2.LUNASTART &lt;= GETANLUCRU () * 12 + GETLUNALUCRU ()
                                                       )
                ORDER BY CL.CODCONSTLUNA
               )
  LOOP
    NeedEchiv := 0;
    FOR V_REC_V IN (SELECT * FROM CONSTVAL CV WHERE CV.CODCONSTLUNA = V_REC.CODCONSTLUNA) LOOP
      NeedEchiv := NeedEchiv + (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT
                                FROM   PKG_PLANCONTURI_ContEchivalat (NULL, case when V_REC_V.VALOARE = '' then 0 else V_REC_V.VALOARE::numeric end));
    END LOOP;

    IF NeedEchiv &gt; 0 THEN
      IF V_REC.ANSTART * 12 + V_REC.LUNASTART &lt; GETANLUCRU () * 12 + GETLUNALUCRU () THEN
        aCODCONSTLUNA := NEXTVAL ('SEQ_CONSTLUNA_CODCONSTLUNA');
        INSERT INTO CONSTLUNA (CODCONSTLUNA, CODCONST1, ANSTART, LUNASTART, USERID)
        VALUES (aCODCONSTLUNA, V_REC.CODCONST1, GETANLUCRU () , GETLUNALUCRU () , V_REC.USERID);

        FOR V_REC_V IN (SELECT * FROM CONSTVAL CV WHERE CV.CODCONSTLUNA = V_REC.CODCONSTLUNA) LOOP
          INSERT INTO CONSTVAL (VALOARE, CODCONSTLUNA)
          VALUES ( (SELECT PKG_PLANCONTURI_CONTECHIVALENT.WME_RESULT FROM PKG_PLANCONTURI_CONTECHIVALENT (NULL, V_REC_V.VALOARE)) , aCODCONSTLUNA);
        END LOOP;
      ELSE
        FOR V_REC_V IN (SELECT * FROM CONSTVAL CV WHERE CV.CODCONSTLUNA = V_REC.CODCONSTLUNA) LOOP
          UPDATE CONSTVAL
          SET VALOARE = (SELECT PKG_PLANCONTURI_CONTECHIVALENT.WME_RESULT FROM PKG_PLANCONTURI_CONTECHIVALENT (NULL, V_REC_V.VALOARE))
          WHERE
            VALOARE = V_REC_V.VALOARE AND CODCONSTLUNA = V_REC_V.CODCONSTLUNA;
        END LOOP;
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_echiv_contserv_iesiri1</obj_name>
  <obj_hashval>87262c2e5d600802dc6b430bb60e3142</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_echiv_contserv_iesiri1()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN (SELECT E.CONTVECHI, I1.CODIES1, I.CODIES, I.TIPDOC, MIN( E.CONTNOU) AS CONTNOU
                FROM NCONTECHIV E, IESIRI1 I1, IESIRI I
                WHERE E.AN = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') AND  I1.CODIES = I.CODIES AND  I.AN = E.AN AND  I1.CONTSERV = E.CONTVECHI
                GROUP BY E.CONTVECHI, I1.CODIES1, I.CODIES, I.TIPDOC
               )
  LOOP
    UPDATE IESIRI1 SET CONTSERV = V_REC.CONTNOU WHERE CODIES1 = V_REC.CODIES1;
    UPDATE JURNAL1 SET DIRTY = 1 WHERE TIPDOC = V_REC.TIPDOC AND  CODDOC = V_REC.CODIES AND  AN = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999');
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_echiv_corelatii</obj_name>
  <obj_hashval>1bf400df641a5e8a9c8374092a17951f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_echiv_corelatii()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN (SELECT CV.SIMBOL AS SIMBOLVECHI, CN.SIMBOL AS SIMBOLNOU
                FROM ncontechiv E, NCONT CV, NCONT CN
                WHERE an = (SELECT PKG_GLOBALS_GetANLUCRU.WME_RESULT FROM PKG_GLOBALS_GetANLUCRU(NULL,NULL)) AND  CV.CODCONT = E.CONTVECHI AND  CN.CODCONT = E.CONTNOU
               )
  LOOP
    UPDATE SITFINLIN SET CORELATIE = REPLACE( CORELATIE, '&lt;' || V_REC.SIMBOLVECHI || '&gt;', '&lt;' || V_REC.SIMBOLNOU || '&gt;') WHERE CORELATIE LIKE '%&lt;' || V_REC.SIMBOLVECHI || '&gt;%';
    UPDATE SITFINLIN SET OBS = REPLACE( OBS, '&lt;' || V_REC.SIMBOLVECHI || '&gt;', '&lt;' || V_REC.SIMBOLNOU || '&gt;') WHERE OBS LIKE '%&lt;' || V_REC.SIMBOLVECHI || '&gt;%';
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_echiv_ioart</obj_name>
  <obj_hashval>693760f3ee10618815f9ae8a33a39b2c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_echiv_ioart()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  NEEDECHIV numeric := 0;
BEGIN
  --Adina 10.03.2021 - add prc_al_refresh
  FOR V_REC IN (SELECT * FROM IOART1 I1
                WHERE I1.ANSTART * 12 + I1.LUNASTART = (SELECT MAX( I2.ANSTART * 12 + I2.LUNASTART)
                                                        FROM IOART1 I2
                                                        WHERE CODIOART = I1.CODIOART AND
                                                              I2.ANSTART * 12 + I2.LUNASTART &lt;= GETANLUCRU() * 12 + GETLUNALUCRU()
                                                       )
               )
  LOOP
    NeedEchiv := (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONT))             +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.DIFERENTE))        +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CHELTUIELI))       +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.VENITURI))         +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.PLUSINVENTAR))     +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CHELTTVACOLECTAT)) +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTROTUNJIRI))    +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.DIVERSE))          +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CUSTODIE))         +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.PROVIZION))        +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CHELTPROVIZION))   +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.VENITPROVIZION));
    IF  NeedEchiv &gt; 0 THEN
      IF  V_REC.ANSTART * 12 + V_REC.LUNASTART &lt; GETANLUCRU() * 12 + GETLUNALUCRU() THEN
        INSERT INTO IOART1(CODIOART1, CODIOART, CONT, DIFERENTE, CHELTUIELI, VENITURI, PLUSINVENTAR, MINUSINVENTAR, CHELTTVACOLECTAT, CONTROTUNJIRI, DIVERSE, CUSTODIE, ACCIZELATRANSFER, DESCARCAREG, CONTABGEST, BAZA, DIFPRET, ARETVANEEX, TVANEEX, MG, ANSTART, LUNASTART, PUSTANDARD, PROVIZION, CHELTPROVIZION, VENITPROVIZION)
        VALUES(NEXTVAL('SEQ_IOART1_CODIOART1'), V_REC.CODIOART,
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONT)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.DIFERENTE)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CHELTUIELI)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.VENITURI)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.PLUSINVENTAR)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.MINUSINVENTAR)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CHELTTVACOLECTAT)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTROTUNJIRI)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.DIVERSE)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CUSTODIE)),
               V_REC.ACCIZELATRANSFER, V_REC.DESCARCAREG, V_REC.CONTABGEST, V_REC.BAZA, V_REC.DIFPRET, V_REC.ARETVANEEX, V_REC.TVANEEX, V_REC.MG,
               TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU'  , true)),'999999999999999999'),
               TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999'),
               V_REC.PUSTANDARD,
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.PROVIZION)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CHELTPROVIZION)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.VENITPROVIZION)));
        CALL prc_al_refresh('ioart1', V_REC.CODIOART);
      ELSE
        UPDATE IOART1
        SET
          CONT             = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONT)),
          DIFERENTE        = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.DIFERENTE)),
          CHELTUIELI       = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CHELTUIELI)),
          VENITURI         = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.VENITURI)),
          PLUSINVENTAR     = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.PLUSINVENTAR)),
          MINUSINVENTAR    = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.MINUSINVENTAR)),
          CHELTTVACOLECTAT = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CHELTTVACOLECTAT)),
          CONTROTUNJIRI    = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTROTUNJIRI)),
          DIVERSE          = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.DIVERSE)),
          CUSTODIE         = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CUSTODIE)),
          PROVIZION        = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.PROVIZION)),
          CHELTPROVIZION   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CHELTPROVIZION)),
          VENITPROVIZION   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.VENITPROVIZION))
        WHERE
         CODIOART1 = V_REC.CODIOART1;
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_echiv_iobank</obj_name>
  <obj_hashval>110866ed46a53e53b32e4f457f095a31</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_echiv_iobank()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  NEEDECHIV numeric := 0;
BEGIN
  --Adina 11.03.2021 - add prc_al_refresh
  FOR V_REC IN (SELECT * FROM IOBANK1 I1
                WHERE
                  I1.ANSTART * 12 + I1.LUNASTART = (SELECT MAX( I2.ANSTART * 12 + I2.LUNASTART)
                                                    FROM IOBANK1 I2
                                                    WHERE
                                                      CODIOBANK = I1.CODIOBANK AND
                                                      I2.ANSTART * 12 + I2.LUNASTART &lt;= GETANLUCRU() * 12 + GETLUNALUCRU()
                                                   )
               )
  LOOP
    NeedEchiv := (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONT))         +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.DOBANDA))      +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.COMISION))     +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CHELTUIELICV)) +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.VENITURICV))   +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.PCEC))         +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.PEFECTE))      +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.PEFECTEREM))   +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.ICEC))         +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.IEFECTE))      +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.IEFECTEREM));
    IF  NeedEchiv &gt; 0 THEN
      IF  V_REC.ANSTART * 12 + V_REC.LUNASTART &lt; GETANLUCRU() * 12 + GETLUNALUCRU() THEN
        INSERT INTO IOBANK1(CODIOBANK1, CODIOBANK, CONT, DOBANDA, COMISION, CHELTUIELICV, VENITURICV, PCEC, PEFECTE, PEFECTEREM, ICEC, IEFECTE, IEFECTEREM, ANSTART, LUNASTART)
        VALUES(NEXTVAL('SEQ_IOBANK1_CODIOBANK1'), V_REC.CODIOBANK,
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONT)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.DOBANDA)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.COMISION)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CHELTUIELICV)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.VENITURICV)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.PCEC)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.PEFECTE)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.PEFECTEREM)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.ICEC)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.IEFECTE)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.IEFECTEREM)),
               GETANLUCRU(),
               GETLUNALUCRU()
              );
        CALL PRC_AL_REFRESH('iobank1', V_REC.CODIOBANK);
      ELSE
        UPDATE IOBANK1
        SET
        CONT         = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONT)),
        DOBANDA      = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.DOBANDA)),
        COMISION     = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.COMISION)),
        CHELTUIELICV = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CHELTUIELICV)),
        VENITURICV   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.VENITURICV)),
        PCEC         = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.PCEC)),
        PEFECTE      = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.PEFECTE)),
        PEFECTEREM   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.PEFECTEREM)),
        ICEC         = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.ICEC)),
        IEFECTE      = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.IEFECTE)),
        IEFECTEREM   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.IEFECTEREM))
        WHERE
         CODIOBANK1 = V_REC.CODIOBANK1;
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_echiv_iofilial</obj_name>
  <obj_hashval>544929f2d934ea0685ac8b98d2e0daa6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_echiv_iofilial()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  NEEDECHIV numeric := 0;
BEGIN
  --Adina 11.03.2021 -add prc_al_refresh
  FOR V_REC IN (SELECT * FROM IOFILIAL1 I1
                WHERE
                  I1.ANSTART * 12 + I1.LUNASTART = (SELECT MAX( I2.ANSTART * 12 + I2.LUNASTART)
                                                    FROM IOFILIAL1 I2
                                                    WHERE
                                                      CODIOFILIAL = I1.CODIOFILIAL AND
                                                      I2.ANSTART * 12 + I2.LUNASTART &lt;= GETANLUCRU() * 12 + GETLUNALUCRU()
                                                   )
               )
  LOOP
    NeedEchiv := (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTDECONTARE))  +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTDECONTSERV)) +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTDECONTCB))   +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTDECONTCMP))  +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTDECONTAREF));
    IF  NeedEchiv &gt; 0 THEN
      IF  V_REC.ANSTART * 12 + V_REC.LUNASTART &lt; GETANLUCRU() * 12 + GETLUNALUCRU() THEN
        INSERT INTO IOFILIAL1(CODIOFILIAL1, CODIOFILIAL, CONTDECONTARE, CONTDECONTSERV, CONTDECONTCB, CONTDECONTCMP, CONTDECONTAREF, ISFIRMA, ANSTART, LUNASTART)
        VALUES(NEXTVAL('SEQ_IOFILIAL1_CODIOFILIAL1'), V_REC.CODIOFILIAL,
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTDECONTARE)) ,
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTDECONTSERV)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTDECONTCB))  ,
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTDECONTCMP)) ,
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTDECONTAREF)),
               V_REC.ISFIRMA,
               GETANLUCRU(),
               GETLUNALUCRU()
              );
        CALL PRC_AL_REFRESH('iofilial1', V_REC.CODIOFILIAL);
      ELSE
        UPDATE IOFILIAL1
        SET
        CONTDECONTARE  = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, CONTDECONTARE)) ,
        CONTDECONTSERV = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, CONTDECONTSERV)),
        CONTDECONTCB   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, CONTDECONTCB))  ,
        CONTDECONTCMP  = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, CONTDECONTCMP)) ,
        CONTDECONTAREF = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, CONTDECONTAREF))
        WHERE
         CODIOFILIAL1 = V_REC.CODIOFILIAL1;
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_echiv_iopers</obj_name>
  <obj_hashval>2ba7544970ec50e1f0839b366394aa50</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_echiv_iopers()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  NEEDECHIV numeric := 0;
BEGIN
  --Adina 11.03.2021 - add prc_al_refresh
  FOR V_REC IN (SELECT * FROM IOPERS1 I1
                WHERE
                  I1.ANSTART * 12 + I1.LUNASTART = (SELECT MAX( I2.ANSTART * 12 + I2.LUNASTART)
                                                    FROM IOPERS1 I2
                                                    WHERE
                                                      CODIOPERS = I1.CODIOPERS AND
                                                      I2.ANSTART * 12 + I2.LUNASTART &lt;= GETANLUCRU() * 12 + GETLUNALUCRU()
                                                   )
               )
  LOOP
    NeedEchiv := (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTAVANSDECONT))  +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTIMPUTATII))    +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTGARANTII))     +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTALTERETINERI)) +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTAVANS))        +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTLIKI))         +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTNERIDICATE))   +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTBOALA))        +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTPARTSAL))      +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTNATURA))       +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTECHIPAMENT))   +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTIMPOZIT));
    IF  NeedEchiv &gt; 0 THEN
      IF  V_REC.ANSTART * 12 + V_REC.LUNASTART &lt; GETANLUCRU() * 12 + GETLUNALUCRU() THEN
        INSERT INTO IOPERS1(CODIOPERS1, CODIOPERS, CONTAVANSDECONT, CONTIMPUTATII, CONTGARANTII, CONTALTERETINERI, CONTAVANS, CONTLIKI, CONTNERIDICATE, CONTBOALA, CONTPARTSAL, CONTNATURA, CONTECHIPAMENT, CONTIMPOZIT, ANSTART, LUNASTART)
        VALUES(NEXTVAL('SEQ_IOPERS1_CODIOPERS1'), V_REC.CODIOPERS,
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTAVANSDECONT)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTIMPUTATII)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTGARANTII)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTALTERETINERI)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTAVANS)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTLIKI)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTNERIDICATE)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTBOALA)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTPARTSAL)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTNATURA)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTECHIPAMENT)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTIMPOZIT)),
               GETANLUCRU(),
               GETLUNALUCRU()
              );
        CALL PRC_AL_REFRESH('iopers1', V_REC.CODIOPERS);
      ELSE
        UPDATE IOPERS1
        SET
        CONTAVANSDECONT  = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, CONTAVANSDECONT)),
        CONTIMPUTATII    = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, CONTIMPUTATII)),
        CONTGARANTII     = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, CONTGARANTII)),
        CONTALTERETINERI = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, CONTALTERETINERI)),
        CONTAVANS        = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, CONTAVANS)),
        CONTLIKI         = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, CONTLIKI)),
        CONTNERIDICATE   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, CONTNERIDICATE)),
        CONTBOALA        = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, CONTBOALA)),
        CONTPARTSAL      = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, CONTPARTSAL)),
        CONTNATURA       = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, CONTNATURA)),
        CONTECHIPAMENT   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, CONTECHIPAMENT)),
        CONTIMPOZIT      = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, CONTIMPOZIT))
        WHERE
         CODIOPERS1 = V_REC.CODIOPERS1;
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_echiv_notecredit</obj_name>
  <obj_hashval>771a1c1cf488e7d37088770c68195054</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_echiv_notecredit()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  NEEDECHIV numeric := 0;
begin
  FOR V_REC IN (SELECT * FROM NOTECREDIT WHERE AN * 12 + LUNA &gt;= GETANLUCRU() * 12 + GetLUNALUCRU()) LOOP
    NeedEchiv := (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CODCONTV)) +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CODCONTT)) +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CODCONTC)) +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CODCONTP)) +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CODCONTZ));

    IF  NeedEchiv &gt; 0 THEN
      UPDATE NOTECREDIT
      SET
      CODCONTV = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CODCONTV)),
      CODCONTT = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CODCONTT)),
      CODCONTC = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CODCONTC)),
      CODCONTP = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CODCONTP)),
      CODCONTZ = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CODCONTZ))
      WHERE
       CODNCREDIT = V_REC.CODNCREDIT;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_get_an_soldini</obj_name>
  <obj_hashval>65797d1ff726ecb2f653027799c73638</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_get_an_soldini(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999') &gt;= 1 THEN
    WME_Result :=  TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999');
    RETURN;
  ELSE
    WME_Result :=  TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') - 1;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_get_cont_cod_caract_anluna</obj_name>
  <obj_hashval>3656562f88916b52377a5d4a632ad02e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_get_cont_cod_caract_anluna(INOUT wme_result numeric, INOUT acodcont numeric, INOUT aanluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODCONT1 numeric := -1;
begin
  --Florin 08.01.2022 - sinc. Oracle (29.01.2021)
  BEGIN
    SELECT Coalesce(CODCONT1, 0) INTO aCODCONT1
    FROM NCONT1
    WHERE CODCONT = aCODCONT AND aANLUNA BETWEEN ALSTART AND ALSTOP;
  EXCEPTION WHEN OTHERS THEN
    WME_Result :=  -1;
    RETURN;
  END;

  WME_Result :=  aCODCONT1;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_get_cont_cod_caract_luna</obj_name>
  <obj_hashval>ab4136d6f2b77c624b93f376728c38ee</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_get_cont_cod_caract_luna(INOUT wme_result numeric, INOUT acodcont numeric, INOUT aan numeric, INOUT aluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODCONT1 numeric := -1;
begin
  WME_Result :=  (SELECT PKG_PLANCONTURI_GET_CONT_COD_CARACT_ANLUNA.WME_RESULT FROM PKG_PLANCONTURI_GET_CONT_COD_CARACT_ANLUNA(NULL, aCODCONT, aAN * 12 + aLUNA));
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_get_cont_cod_caract_luna_ext</obj_name>
  <obj_hashval>bedf3f4cf071794fc4d921d381833121</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_get_cont_cod_caract_luna_ext(INOUT wme_result numeric, INOUT acodcont numeric, INOUT aanluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODCONT1 numeric := -1;
begin
  BEGIN

    SELECT DISTINCT ON (CODCONT) LAST_VALUE(CODCONT1)  OVER ANLUNA CODCONT1
    INTO aCODCONT1
    FROM NCONT1
    WHERE CODCONT = aCODCONT AND  ANSTART * 12 + LUNASTART &lt;= aANLUNA
     WINDOW ANLUNA AS (PARTITION BY CODCONT ORDER BY ANSTART * 12 + LUNASTART RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING);

  /*
  SELECT Max( COALESCE( CODCONT1, 0)) KEEP (Dense_Rank  LAST  ORDER BY ANSTART * 12 + LUNASTART )
  INTO aCODCONT1
  FROM NCONT1
  WHERE
     CODCONT = aCODCONT AND  ANSTART * 12 + LUNASTART &lt;= aANLUNA;
  */
  EXCEPTION WHEN OTHERS THEN
    WME_Result :=  -1;
    RETURN;
  END;

  WME_Result :=  aCODCONT1;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_getcodcont_by_simbol</obj_name>
  <obj_hashval>c9b09791f49608b90d1a1c637fb0b791</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_getcodcont_by_simbol(INOUT wme_result numeric, INOUT asimbol character varying, INOUT principal numeric DEFAULT 0)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCOD numeric := 0;
begin
  BEGIN
    --BogdanL 28.07.2020
    IF  COALESCE( Principal, 0) = 0 THEN
      SELECT CODCONT INTO ACOD FROM NCONT WHERE upper( SIMBOL) = upper( aSIMBOL);
    ELSE
      SELECT CODCONTS INTO ACOD FROM NCONTS WHERE upper( SIMBOL) = upper( aSIMBOL);
    END IF;
  EXCEPTION WHEN OTHERS THEN
    WME_Result :=  aCOD;
    RETURN;
  END;

  WME_Result :=  aCOD;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_getcodcontrep</obj_name>
  <obj_hashval>5e0544af8b4a87d32cf5f010370b1f11</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_getcodcontrep(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER((current_setting('PKG_PLANCONTURI.CODCONTREP', true)),'999999999999999999');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_getdencont</obj_name>
  <obj_hashval>c4a0b9ea7d115dd53d3b5df6af3fe58b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_getdencont(INOUT wme_result character varying, INOUT cont numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDEN varchar := '';
BEGIN
  --Florin 10.02.2021 - fixat 42815
  BEGIN
    SELECT DEN_CONT INTO STRICT aDEN FROM NCONT WHERE CODCONT = CONT;
  EXCEPTION WHEN OTHERS THEN
    WME_Result :=  aDEN;
    RETURN;
  END;

  WME_Result :=  aDEN;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_getinitializari</obj_name>
  <obj_hashval>beed8d1eeebd728bdc6bd4bfdb3168a5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_getinitializari(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANCONTURI.INITIALIZARI', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_getnumaranalitice</obj_name>
  <obj_hashval>a698c4eb232c6c36c4730fd363bdefd7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_getnumaranalitice(INOUT wme_result numeric, INOUT cont numeric, INOUT unanstart numeric, INOUT olunastart numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  RECNO NUMERIC := 0;
begin
  SELECT COUNT( *) INTO RECNO FROM NCONT N
  WHERE
     CODPARINTE = CONT AND  (SELECT COUNT( *) FROM NCONT1 N1
                             WHERE N.CODCONT = N1.CODCONT AND  (SELECT GETDATA.WME_RESULT FROM GETDATA(NULL, UNANSTART, OLUNASTART)) &gt;= (SELECT GETDATA.WME_RESULT FROM GETDATA(NULL, ANSTART, LUNASTART))
                            ) &gt; 0;

  WME_Result :=  RECNO;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_getsimbolcont</obj_name>
  <obj_hashval>7dc220ac92f2257968b1dce34c972d5a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_getsimbolcont(cont numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  aSimbol varchar := '???';
BEGIN
  --Adina 25 august 2020
  BEGIN
    SELECT SIMBOL INTO aSimbol FROM NCONT WHERE CODCONT = CONT;
  EXCEPTION WHEN OTHERS THEN
    RETURN  aSimbol;
  END;

  RETURN  aSimbol;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_ncont_addnewentries</obj_name>
  <obj_hashval>51d660bd31ed6aed50ee62f4d6593234</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_ncont_addnewentries()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  RECID numeric;
begin
  FOR v_rec IN (SELECT * FROM NCONT_NEWENTRY WHERE Done &lt;&gt; 1) LOOP
    PERFORM PKG_PLANCONTURI_NCONT_NewEntry( V_REC.SIMBOL, V_REC.DEN_CONT, V_REC.NAME, V_REC.ANSTART, V_REC.LUNASTART, RECID);

    IF  RECID &gt; 0 THEN
      UPDATE NCONT_NEWENTRY SET DONE = 1 WHERE CodCont = V_REC.CodCont;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_ncont_newentry</obj_name>
  <obj_hashval>ebaf4a65e767ae5c3db7ec8b7ebe7057</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_ncont_newentry(INOUT asimbol character varying, INOUT anume character varying, INOUT aname character varying, INOUT aan numeric, INOUT aluna numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR      numeric;
  ANINI   numeric := 0;
  LUNAINI numeric := 0;
  AN      numeric := 0;
  LUNA    numeric := 0;
  aClasa  numeric := 0;
begin
  RECID := 0;
  SELECT Count( *) INTO NR FROM NCONT WHERE SubSTR( SIMBOL, 1, LENGTH( aSIMBOL)) = aSIMBOL;
  IF  NR = 0 THEN
    BEGIN
      SELECT ANINITIAL, LUNAINITIALA INTO ANINI, LUNAINI FROM FIRMALUNI;
    EXCEPTION WHEN OTHERS THEN
      ANINI := 0;
    END;

    IF  ANINI &gt; 0 AND  LUNAINI &gt; 0 THEN
      AN   := aAN;
      LUNA := aLUNA;
      IF  aAn &lt; ANINI     THEN AN   := ANINI;   END IF;
      IF  aLUNA &lt; LUNAINI THEN LUNA := LUNAINI; END IF;
      aClasa := To_Number( Substr( aSimbol, 1, 1),'999999999999999999');

      INSERT INTO TMP_NCONT(CodCont, Simbol, Den_Cont, Name, TipCont, VizibilBalanta, BalantaSintetica, Nivel, Clasa, Inactiv)
      VALUES(0, aSIMBOL, aNUME, aNAME, 0, 1, 0, 1, aClasa, 1);

      INSERT INTO TMP_NCONT1(CodCont1, AnStart, LunaStart)
      VALUES(-1, AN, LUNA);

      PERFORM PKG_PLANCONTURI_SP_POSTRECORDS( 1, RecID);
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_repartizare_sold_in_luna</obj_name>
  <obj_hashval>ecbd5c9d5154835c150bdb77dac4ca4e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_repartizare_sold_in_luna(INOUT wme_result numeric, INOUT acodcont numeric, INOUT aan numeric, INOUT aluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  SELECT COUNT( *) into Nr FROM NCONTREP WHERE CODCONT = aCODCONT AND  AN = aAN AND  LUNA = aLUNA;

  WME_Result :=  NR;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_set_echivalari_automate</obj_name>
  <obj_hashval>1a5462eca316c1c12a5e95bb281f0135</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_set_echivalari_automate()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_PLANCONTURI_ECHIV_CONTSERV_INTRARI1();
  PERFORM PKG_PLANCONTURI_ECHIV_CONTSERV_IESIRI1();
  PERFORM PKG_PLANCONTURI_ECHIV_CONTSERV_NART();
  PERFORM PKG_PLANCONTURI_ECHIV_IOART();
  PERFORM PKG_PLANCONTURI_ECHIV_IOPART();
  PERFORM PKG_PLANCONTURI_ECHIV_IOPERS();
  PERFORM PKG_PLANCONTURI_ECHIV_CONSTANTE();
  PERFORM PKG_PLANCONTURI_ECHIV_IOBANK();
  PERFORM PKG_PLANCONTURI_ECHIV_IOFILIAL();
  PERFORM PKG_PLANCONTURI_ECHIV_CORELATII();
  PERFORM PKG_PLANCONTURI_ECHIV_NOTECREDIT();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_setinitializari</obj_name>
  <obj_hashval>d2dac275b793158decafbf0f1a9566c0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_setinitializari(ainitializari numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANCONTURI.INITIALIZARI',to_char(aINITIALIZARI,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_setsimbolsitfin</obj_name>
  <obj_hashval>b41b8112a4aa699dc81950b6b0eea19b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_setsimbolsitfin()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
UPDATE ncont
SET
simbolsitfin = simbol
WHERE
 COALESCE( simbolsitfin, '@') = '@'
;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_sp_deleterecord</obj_name>
  <obj_hashval>2a5d62cb3f54fd0275dd942203425332</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  aCODPARINTE numeric := 0;
  NR          numeric := 0;
BEGIN
  --Florin 20.04.2023 - sinc. Oracle
  --Adina  15.03.2021 - prc_al_refresh
  PERFORM pkg_planconturi_SP_LOCKRECORD( RecId);
  PERFORM PKG_CFGTABLES_EXT_DELETERECORD (recId, 521);

  SELECT COALESCE( CODPARINTE, 0) INTO aCODPARINTE FROM NCONT WHERE CODCONT = RECID;

  FOR V_REC IN (SELECT * FROM NCONT1 WHERE CODCONT = RECID) LOOP
    DELETE FROM ncont1sub WHERE CODCONT1 = V_REC.CODCONT1;
    DELETE FROM ncont1     WHERE CODCONT1 = V_REC.CODCONT1;
  END LOOP;

  FOR V_REC IN (SELECT * FROM NCONTSOLD WHERE CODCONT = RECID) LOOP
    DELETE FROM ncontsold    WHERE CODCONTSOLD = V_REC.CODCONTSOLD;
    DELETE FROM ncontsoldsub WHERE CODCONTSOLD = V_REC.CODCONTSOLD;
  END LOOP;

  FOR V_REC IN (SELECT * FROM NCONTRUL WHERE CODCONT = RECID) LOOP
    DELETE FROM ncontrul    WHERE CODCONTRUL = V_REC.CODCONTRUL;
    DELETE FROM ncontrulsub WHERE CODCONTRUL = V_REC.CODCONTRUL;
  END LOOP;

  DELETE FROM ncontrep WHERE CODCONT = recid;

  FOR V_REC IN (SELECT * FROM NCONTREPSOLD WHERE CODCONT = RECID) LOOP
    DELETE FROM ncontrepsoldsub WHERE CODCONTREPSOLD = V_REC.CODCONTREPSOLD;
    DELETE FROM ncontrepsold     WHERE CODCONTREPSOLD = V_REC.CODCONTREPSOLD;
  END LOOP;

  FOR V_REC IN (SELECT * FROM NCONTREPRUL WHERE CODCONT = RECID) LOOP
    DELETE FROM ncontreprulsub WHERE CODCONTREPRUL = V_REC.CODCONTREPRUL;
    DELETE FROM ncontreprul    WHERE CODCONTREPRUL = V_REC.CODCONTREPRUL;
  END LOOP;

  DELETE FROM ncont    WHERE CODCONT = recid;
  DELETE FROM ncontrep WHERE CODCONT NOT IN (SELECT CODPARINTE FROM ncontrepsold
                                             UNION
                                             SELECT CODPARINTE FROM ncontreprul);
 /*  17.11.2021 am renuntat la update-urile de mai jos deoarece strica solurile initiale
  IF  ACODPARINTE &gt; 0 THEN
    SELECT COUNT( *) INTO NR FROM NCONT WHERE CODPARINTE = aCODPARINTE;

    IF  NR &gt; 0 THEN
      PERFORM pkg_planconturi_UPDATE_SOLD_PARINTE( aCODPARINTE);
      PERFORM pkg_planconturi_UPDATE_SOLD_SUB_PARINTE( aCODPARINTE);
      PERFORM pkg_planconturi_UPDATE_RULAJP_PARINTE( aCODPARINTE);
      PERFORM pkg_planconturi_UPDATE_RULAJP_SUB_PARINTE( aCODPARINTE);
    END IF;
  END IF;
*/



  CALL PRC_AL_REFRESH('ncont1',  RecId);
  PERFORM NotifyModif( 2, RecId, 'NCONT');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_sp_insertrecord</obj_name>
  <obj_hashval>4c6aab6666d742d50666ae77f43b9c86</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 20.04.2023 - sinc. Oracle
  INSERT INTO TMP_NCONT(CodCont) VALUES(0);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(521);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_sp_lockrecord</obj_name>
  <obj_hashval>58bddc76ec82323146b40a9cf64aff70</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMP numeric := 0;
begin
  SELECT CodCont into Tmp FROM NCONT WHERE CodCont = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_update_nume_cont</obj_name>
  <obj_hashval>368fd299c5a2a6b892ff641a24998119</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_update_nume_cont(anume character varying, asimbol character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  UPDATE NCONT SET NAME = ANUME WHERE SIMBOL = ASIMBOL;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_update_rulajp_parinte</obj_name>
  <obj_hashval>62f12f9051b7860d2c938138c73964bb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_update_rulajp_parinte(acodparinte numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR    numeric := 0;
  OLDPA numeric := 0;
begin
  SELECT COUNT( *) INTO NR FROM NCONTRUL
  WHERE CODCONT = ACODPARINTE AND  AN = current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric AND  LUNA = current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric;

  IF  NR = 0 THEN
    INSERT INTO NCONTRUL(CODCONTRUL, CODCONT, AN, LUNA)
    VALUES(NEXTVAL('SEQ_NCONTRUL_CODCONTRUL'), ACODPARINTE, current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric, current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric);
  END IF;

  UPDATE NCONTRUL
  SET
  (RULAJPD, RULAJPC, RULAJVPD, RULAJVPC, RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP)
  =
  (
  SELECT SUM( COALESCE( RULAJPD, 0)), SUM( COALESCE( RULAJPC, 0)), SUM( COALESCE( RULAJVPD, 0)), SUM( COALESCE( RULAJVPC, 0)), SUM( COALESCE( RULAJP_IFRS, 0)), SUM( COALESCE( RULAJC_IFRS, 0)), SUM( COALESCE( RULAJVP_IFRS, 0)), SUM( COALESCE( RULAJVC_IFRS, 0)), SUM( COALESCE( RULAJP_GRUP, 0)), SUM( COALESCE( RULAJC_GRUP, 0)), SUM( COALESCE( RULAJVP_GRUP, 0)), SUM( COALESCE( RULAJVC_GRUP, 0))
  FROM NCONTRUL R, NCONT C
  WHERE C.CODCONT = R.CODCONT AND  C.CODPARINTE = ACODPARINTE AND  R.AN = current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric AND  R.LUNA = current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric
  )
  WHERE
   CODCONT = ACODPARINTE AND  AN = current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric AND  LUNA = current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric;

  BEGIN
    SELECT COALESCE( CODPARINTE, 0) INTO OLDPA FROM NCONT WHERE CODCONT = aCODPARINTE;
  EXCEPTION WHEN OTHERS THEN
    OLDPA := 0;
  END;

  IF  OLDPA &lt;&gt; 0 THEN
    PERFORM PKG_PLANCONTURI_UPDATE_RULAJP_PARINTE( OLDPA);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_update_rulajp_sub_parinte</obj_name>
  <obj_hashval>f929f30a6ac586af0a678184d356e4a7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_update_rulajp_sub_parinte(acodparinte numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC          RECORD;
  NR             numeric := 0;
  ACODCONTRUL    numeric := 0;
  ACODCONTRULSUB numeric := 0;
  OLDPA          numeric := 0;
begin
  BEGIN
    SELECT CODCONTRUL INTO aCODCONTRUL FROM NCONTRUL
    WHERE CODCONT = ACODPARINTE AND  AN = current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric AND  LUNA = current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric;
  EXCEPTION WHEN OTHERS THEN
    ACODCONTRUL := 0;
  END;

  IF  aCODCONTRUL &lt;&gt; 0 THEN
    UPDATE NCONTRULSUB
    SET
    RULAJPD      = 0,
    RULAJPC      = 0,
    RULAJVPD     = 0,
    RULAJVPC     = 0,
    RULAJP_IFRS  = 0,
    RULAJVP_IFRS = 0,
    RULAJP_GRUP  = 0,
    RULAJVP_GRUP = 0
    WHERE
     CODCONTRUL = aCODCONTRUL;

    FOR V_REC IN (SELECT RS.SUBUNITATEA,
                         SUM( COALESCE( RS.RULAJPD, 0))     AS RULAJPD    , SUM( COALESCE( RS.RULAJPC, 0))      AS RULAJPC,
                         SUM( COALESCE( RS.RULAJVPD, 0))    AS RULAJVPD   , SUM( COALESCE( RS.RULAJVPC, 0))     AS RULAJVPC,
                         SUM( COALESCE( RS.RULAJP_IFRS, 0)) AS RULAJP_IFRS, SUM( COALESCE( RS.RULAJVP_IFRS, 0)) AS RULAJVP_IFRS,
                         SUM( COALESCE( RS.RULAJP_GRUP, 0)) AS RULAJP_GRUP, SUM( COALESCE( RS.RULAJVP_GRUP, 0)) AS RULAJVP_GRUP
                  FROM NCONT C, NCONTRUL R, NCONTRULSUB RS
                  WHERE  C.CODPARINTE = aCODPARINTE AND  R.CODCONT = C.CODCONT
                    AND  R.AN = current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric AND  R.LUNA = current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric
                    AND  RS.CODCONTRUL = R.CODCONTRUL
                  GROUP BY SUBUNITATEA
                 )
    LOOP
      BEGIN
        SELECT CODCONTRULSUB INTO aCODCONTRULSUB FROM NCONTRULSUB WHERE CODCONTRUL = aCODCONTRUL AND  SUBUNITATEA = V_REC.SUBUNITATEA;
      EXCEPTION WHEN OTHERS THEN
        aCODCONTRULSUB := 0;
      END;

      IF  aCODCONTRULSUB = 0 THEN
        aCODCONTRULSUB := NEXTVAL('SEQ_NCONTRULSUB_CODRULSUB');
        INSERT INTO NCONTRULSUB(CODCONTRULSUB, CODCONTRUL, SUBUNITATEA, RULAJPD, RULAJPC, RULAJVPD, RULAJVPC, RULAJP_IFRS, RULAJVP_IFRS, RULAJP_GRUP, RULAJVP_GRUP)
        VALUES(aCODCONTRULSUB, aCODCONTRUL, V_REC.SUBUNITATEA, 0, 0, 0, 0, 0, 0, 0, 0);
      END IF;

      UPDATE NCONTRULSUB
      SET
      RULAJPD      = V_REC.RULAJPD,
      RULAJPC      = V_REC.RULAJPC,
      RULAJVPD     = V_REC.RULAJVPD,
      RULAJVPC     = V_REC.RULAJVPC,
      RULAJP_IFRS  = V_REC.RULAJP_IFRS,
      RULAJVP_IFRS = V_REC.RULAJVP_IFRS,
      RULAJP_GRUP  = V_REC.RULAJP_GRUP,
      RULAJVP_GRUP = V_REC. RULAJVP_GRUP
      WHERE
       CODCONTRULSUB = aCODCONTRULSUB;
    END LOOP;
  END IF;

  BEGIN
    SELECT COALESCE( CODPARINTE, 0) INTO OLDPA FROM NCONT WHERE CODCONT = aCODPARINTE;
  EXCEPTION WHEN OTHERS THEN
    OLDPA := 0;
  END;

  IF  OLDPA &lt;&gt; 0 THEN
    PERFORM PKG_PLANCONTURI_UPDATE_RULAJP_SUB_PARINTE( OLDPA);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_update_sold_parinte</obj_name>
  <obj_hashval>d79986120bc1e4a0e27822fa0b090603</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_update_sold_parinte(acodparinte numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR    numeric := 0;
  OLDPA numeric := 0;
begin
  SELECT COUNT( *) INTO NR FROM NCONTSOLD
  WHERE CODCONT = ACODPARINTE AND  AN = (SELECT PKG_PLANCONTURI_GET_AN_SOLDINI.WME_RESULT FROM PKG_PLANCONTURI_GET_AN_SOLDINI(NULL,NULL)) AND  LUNA = 1;

  IF  NR = 0 THEN
    INSERT INTO NCONTSOLD(CODCONTSOLD, CODCONT, AN, LUNA)
    VALUES(NEXTVAL('SEQ_NCONTSOLD_CODCONTSOLD'), ACODPARINTE, (SELECT PKG_PLANCONTURI_GET_AN_SOLDINI.WME_RESULT FROM PKG_PLANCONTURI_GET_AN_SOLDINI(NULL,NULL)), 1);
  END IF;

  UPDATE NCONTSOLD
  SET
  (SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP)
  =
  (
  SELECT SUM( COALESCE( SOLDID, 0)), SUM( COALESCE( SOLDIC, 0)), SUM( COALESCE( SOLDVID, 0)), SUM( COALESCE( SOLDVIC, 0)), SUM( COALESCE( SOLDI_IFRS, 0)), SUM( COALESCE( SOLDVI_IFRS, 0)), SUM( COALESCE( SOLDI_GRUP, 0)), SUM( COALESCE( SOLDVI_GRUP, 0))
  FROM NCONTSOLD S, NCONT C
  WHERE C.CODCONT = S.CODCONT AND  C.CODPARINTE = ACODPARINTE AND  S.AN = (SELECT PKG_PLANCONTURI_GET_AN_SOLDINI.WME_RESULT FROM PKG_PLANCONTURI_GET_AN_SOLDINI(NULL,NULL)) AND  S.LUNA = 1
  )
  WHERE CODCONT = ACODPARINTE AND  AN = (SELECT PKG_PLANCONTURI_GET_AN_SOLDINI.WME_RESULT FROM PKG_PLANCONTURI_GET_AN_SOLDINI(NULL,NULL)) AND  LUNA = 1;

  BEGIN
    SELECT COALESCE( CODPARINTE, 0) INTO OLDPA FROM NCONT WHERE CODCONT = aCODPARINTE;
  EXCEPTION WHEN OTHERS THEN
    OLDPA := 0;
  END;

  IF  OLDPA &lt;&gt; 0 THEN
    PERFORM PKG_PLANCONTURI_UPDATE_SOLD_PARINTE( OLDPA);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_update_sold_sub_parinte</obj_name>
  <obj_hashval>90fdc70879fcf416945ea374aa7e0de4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_update_sold_sub_parinte(acodparinte numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC           RECORD;
  NR              numeric := 0;
  ACODCONTSOLD    numeric := 0;
  ACODCONTSOLDSUB numeric := 0;
  OLDPA           numeric := 0;
begin
  BEGIN
    SELECT CODCONTSOLD INTO aCODCONTSOLD FROM NCONTSOLD
    WHERE CODCONT = ACODPARINTE AND  AN = (SELECT PKG_PLANCONTURI_GET_AN_SOLDINI.WME_RESULT FROM PKG_PLANCONTURI_GET_AN_SOLDINI(NULL,NULL)) AND  LUNA = 1;
  EXCEPTION WHEN OTHERS THEN
    ACODCONTSOLD := 0;
  END;

  IF  aCODCONTSOLD &lt;&gt; 0 THEN
    UPDATE NCONTSOLDSUB
    SET
    SOLDID      = 0,
    SOLDIC      = 0,
    SOLDVID     = 0,
    SOLDVIC     = 0,
    SOLDI_IFRS  = 0,
    SOLDVI_IFRS = 0,
    SOLDI_GRUP  = 0,
    SOLDVI_GRUP = 0
    WHERE
     CODCONTSOLD = aCODCONTSOLD;

    FOR V_REC IN (SELECT SS.SUBUNITATEA,
                         SUM( COALESCE( SS.SOLDID, 0))     AS SOLDID    , SUM( COALESCE( SS.SOLDIC, 0))      AS SOLDIC,
                         SUM( COALESCE( SS.SOLDVID, 0))    AS SOLDVID   , SUM( COALESCE( SS.SOLDVIC, 0))     AS SOLDVIC,
                         SUM( COALESCE( SS.SOLDI_IFRS, 0)) AS SOLDI_IFRS, SUM( COALESCE( SS.SOLDVI_IFRS, 0)) AS SOLDVI_IFRS,
                         SUM( COALESCE( SS.SOLDI_GRUP, 0)) AS SOLDI_GRUP, SUM( COALESCE( SS.SOLDVI_GRUP, 0)) AS SOLDVI_GRUP
                  FROM NCONT C, NCONTSOLD S, NCONTSOLDSUB SS
                  WHERE C.CODPARINTE = ACODPARINTE AND  S.CODCONT = C.CODCONT AND  S.AN = (SELECT PKG_PLANCONTURI_GET_AN_SOLDINI.WME_RESULT FROM PKG_PLANCONTURI_GET_AN_SOLDINI(NULL,NULL)) AND  S.LUNA = 1 AND  SS.CODCONTSOLD = S.CODCONTSOLD
                  GROUP BY SUBUNITATEA
                 )
    LOOP
      BEGIN
        SELECT CODCONTSOLDSUB INTO aCODCONTSOLDSUB FROM NCONTSOLDSUB WHERE CODCONTSOLD = aCODCONTSOLD AND  SUBUNITATEA = V_REC.SUBUNITATEA;
      EXCEPTION WHEN OTHERS THEN
        aCODCONTSOLDSUB := 0;
      END;

      IF  aCODCONTSOLDSUB = 0 THEN
        aCODCONTSOLDSUB := NEXTVAL('SEQ_NCONTSOLDSUB_CODSOLDSUB');
        INSERT INTO NCONTSOLDSUB(CODCONTSOLDSUB, CODCONTSOLD, SUBUNITATEA, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP)
        VALUES(aCODCONTSOLDSUB, aCODCONTSOLD, V_REC.SUBUNITATEA, 0, 0, 0, 0, 0, 0, 0, 0);
      END IF;

      UPDATE NCONTSOLDSUB
      SET
      SOLDID      = V_REC.SOLDID,
      SOLDIC      = V_REC.SOLDIC,
      SOLDVID     = V_REC.SOLDVID,
      SOLDVIC     = V_REC.SOLDVIC,
      SOLDI_IFRS  = V_REC.SOLDI_IFRS,
      SOLDVI_IFRS = V_REC.SOLDVI_IFRS,
      SOLDI_GRUP  = V_REC.SOLDI_GRUP,
      SOLDVI_GRUP = V_REC.SOLDVI_GRUP
      WHERE
       CODCONTSOLDSUB = aCODCONTSOLDSUB;
    END LOOP;
  END IF;

  BEGIN
    SELECT COALESCE( CODPARINTE, 0) INTO OLDPA FROM NCONT WHERE CODCONT = aCODPARINTE;
  EXCEPTION WHEN OTHERS THEN
    OLDPA := 0;
  END;

  IF  OLDPA &lt;&gt; 0 THEN
    PERFORM PKG_PLANCONTURI_UPDATE_SOLD_SUB_PARINTE( OLDPA);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plancurs_sp_postrecords</obj_name>
  <obj_hashval>eff6746bb407d523c3b4e808822ed0d4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plancurs_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  vRecNo NUMERIC := 0;
  vAn    NUMERIC := 0;
  vLuna  NUMERIC := 0;
  vCod   numeric;
begin
  IF  Operation = 0 THEN
    SELECT CodPlanCurs INTO RecId FROM TMP_PlanCurs;

    UPDATE PlanCurs
    SET
    (CODPERS, NR, DataCurs, TIP, AN, LUNA) = (SELECT CODPERS, NR, DataCurs, TIP, AN, LUNA FROM TMP_PlanCurs)
    WHERE
     CodPlanCurs = RecId;

    DELETE FROM PLANCURS1 WHERE CODPLANCURS = RecId and CODPLANCURS1 NOT IN (SELECT CODPLANCURS1 FROM TMP_PLANCURS1);

    INSERT INTO PLANCURS1(CodPlanCurs1, CodPlanCurs, CodTema, DataPlan, Stare)
    SELECT NEXTVAL('SEQ_PLANCURS1_CODPLANCURS1'), RecId, CodTema, DataPlan, Stare FROM TMP_PLANCURS1 WHERE CODPLANCURS1 &lt; 0;

    FOR v_rec IN (SELECT * FROM TMP_PLANCURS1 WHERE CODPLANCURS1 &gt; 0) LOOP
      UPDATE PLANCURS1
      SET
      CodTema  = V_REC.Codtema,
      DataPlan = V_REC.dataPlan,
      Stare    = V_REC.Stare
      WHERE
       CODPLANCURS1 = v_rec.CODPLANCURS1;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_PLANCURS_CODPLANCURS') INTO RecId;

    INSERT INTO PlanCurs(CodPlanCurs, CODPERS, NR, DataCurs, TIP, AN, LUNA)
    (SELECT RecId, CODPERS, NR, DataCurs, TIP, AN, LUNA FROM TMP_PlanCurs);

    INSERT INTO PLANCURS1(CodPlanCurs1, CodPlanCurs, CodTema, DataPlan, Stare)
    SELECT NEXTVAL('SEQ_PLANCURS1_CODPLANCURS1'), RecId, CodTema, DataPlan, Stare FROM TMP_PLANCURS1;
  END IF;

  PERFORM NotifyModif( Operation, RecId, 'PlanCurs');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_blocarecurefresh</obj_name>
  <obj_hashval>020de023da851705a47c235c7017948d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_blocarecurefresh(INOUT wme_result numeric, INOUT acodstare numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp        numeric;
  Rez        numeric;
  aCodStareC numeric;
  aCodStareN numeric;
begin
  Rez := 1;
  BEGIN
    SELECT SEC.CodStare
    INTO aCodStareC
    FROM STAREESTIMARI SE
         INNER JOIN STAREESTIMARI SEC ON  SEC.AN = SE.AN AND  SEC.SAPTAMANA = SE.SAPTAMANA AND  SEC.AN = SEC.ANG AND  SEC.SAPTAMANA = SEC.SAPTAMANAG
    WHERE SE.CodStare = aCodStare and  se.subunitatea = sec.subunitatea;
  EXCEPTION WHEN others THEN
    aCodStareC := 0;
  END;

  IF  aCodStareC = 0 THEN
    Rez := 0;
  END IF;

  IF  Rez = 0 THEN
   WME_Result :=  Rez;
   RETURN;
  END IF;

  BEGIN
    SELECT SEC.CodStare
    INTO aCodStareN
    FROM STAREESTIMARI SE
    INNER JOIN STAREESTIMARI SEC ON  SEC.AN = SE.AN AND  SEC.SAPTAMANA = SE.SAPTAMANA AND  SEC.ANG * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, sec.An)) + SEC.SAPTAMANAG = SEC.AN * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, sec.An)) + SEC.SAPTAMANA + 1
    WHERE SE.CodStare = aCodStare and  se.subunitatea = sec.subunitatea;
  EXCEPTION WHEN others THEN
    aCodStareC := 0;
  END;

  IF  aCodStareN = 0 THEN
    Rez := 0;
  END IF;

  IF  Rez = 0 THEN
    WME_Result :=  Rez;
    RETURN;
  END IF;

  BEGIN
    SELECT CodStare INTO Tmp FROM STAREESTIMARI WHERE CodStare = aCodStareC;
  EXCEPTION WHEN others THEN
    Rez := 0;
  END;

  IF  Rez = 0 THEN
    WME_Result :=  Rez;
    RETURN;
  END IF;

  BEGIN
    SELECT CodStare INTO Tmp FROM STAREESTIMARI WHERE CodStare = aCodStareN;
  EXCEPTION WHEN others THEN
    Rez := 0;
  END;

  IF  Rez = 0 THEN
    WME_Result :=  Rez;
    RETURN;
  END IF;

  PERFORM PKG_PLANIFCMD_REFRESHDATETS( aCodStareC, aCodStareN);

  WME_Result :=  Rez;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_ct_monitor</obj_name>
  <obj_hashval>b22e931badfcacc3afb6b81657817465</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_PLANIFCMD.CT_MONITOR', true));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_69';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_getallcls</obj_name>
  <obj_hashval>2bed35ef8ee3d0a1726432ce79c7e83d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_getallcls(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  TO_NUMBER((current_setting('PKG_PLANIFCMD.vAllCls', true)),'999999999999999999');
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_getallclss</obj_name>
  <obj_hashval>7e357a6916524119d8bd47e5f852e4a8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_getallclss(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  TO_NUMBER((current_setting('PKG_PLANIFCMD.vAllClsS', true)),'999999999999999999');
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_getallprod</obj_name>
  <obj_hashval>5cb8b3fc98fec519ae6844446ed586f6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_getallprod(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  TO_NUMBER((current_setting('PKG_PLANIFCMD.vAllProd', true)),'999999999999999999');
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_getandrefreshrest</obj_name>
  <obj_hashval>68d6c2b52e1440e39d04b1f3e25b8017</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_getandrefreshrest(INOUT wme_result numeric, INOUT acodstare2 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  Rez double precision;
begin
  BEGIN
    UPDATE stareestimari2 se2
    SET
    restacceptat = (SELECT c1.restacceptat FROM comanda1 c1 WHERE c1.codcomanda1 = se2.codcomanda1)
    WHERE
     se2.codstare2 = aCodStare2;

    SELECT restacceptat INTO rez FROM stareestimari2 WHERE codstare2 = aCodStare2;
  EXCEPTION WHEN others THEN
    Rez := 0;
  END;

  WME_Result :=  Rez;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_getct_monitor</obj_name>
  <obj_hashval>bc9cc561514b14c5c12b46036f74ce37</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_PLANIFCMD.CT_MONITOR', true));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_69';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_getvallcls</obj_name>
  <obj_hashval>5a41bd9057241545900f6b292101c6f5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_getvallcls(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_PLANIFCMD.vAllCls', true)),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_getvallclss</obj_name>
  <obj_hashval>c6dd169ff4038269edc6107697ac1a47</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_getvallclss(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_PLANIFCMD.vAllClsS', true)),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_getvallprod</obj_name>
  <obj_hashval>25eb411eb9ba8a2a81c0417745c832f8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_getvallprod(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_PLANIFCMD.vAllProd', true)),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_lockstare</obj_name>
  <obj_hashval>42cfe8b1063652603dee6f02c7655180</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_lockstare(INOUT wme_result numeric, INOUT acodstare numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  Rez numeric;
  Tmp numeric;
begin
  BEGIN
    SELECT SEC.CodStare
    INTO Tmp
    FROM STAREESTIMARI SE
         INNER JOIN stareestimari sec ON  sec.an = se.an and  sec.saptamana = se.saptamana and  sec.an = sec.ang and  sec.saptamana = sec.saptamanag
    WHERE se.CodStare = aCodStare and  sec.subunitatea = se.subunitatea;

    Rez := 0;
  EXCEPTION WHEN others THEN
    Rez := 1;
  END;

  IF  Rez = 1 THEN
    WME_Result :=  Rez;
    RETURN;
  END IF;

  BEGIN
    SELECT SEC.CodStare
    INTO Tmp
    FROM STAREESTIMARI SE
         INNER JOIN stareestimari sec ON  sec.an = se.an and  sec.saptamana = se.saptamana and  sec.ang * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, sec.An)) + sec.saptamanag = sec.an * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, sec.An)) + sec.saptamana + 1
    WHERE se.CodStare = aCodStare and  sec.subunitatea = se.subunitatea;
    Rez := 0;
  EXCEPTION WHEN others THEN
    Rez := 1;
  END;

  WME_Result :=  Rez;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_maketemporarcentralizat</obj_name>
  <obj_hashval>4aa1264ad0d16b976bab1d2d4f926948</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_maketemporarcentralizat(aset numeric, aan numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDataCreare   timestamp;
  aSetG         numeric;
  aAnG           numeric;
  aUserID       numeric;
  aSubunitatea   numeric;
  si             date;
  sf             date;
  MultipA       numeric;
BEGIN
  aUserID      := (SELECT pkg_globals_getuserid.WME_RESULT     FROM pkg_globals_getuserid(NULL,NULL));
  aSubunitatea := (SELECT pkg_globals_GETSUBUNITATE.WME_RESULT FROM pkg_globals_GETSUBUNITATE(NULL,NULL));

  BEGIN
    SELECT min( datacreare)
    INTO adatacreare
    FROM stareestimari
    WHERE an = aan and  saptamana = aset;
  EXCEPTION WHEN others THEN
    aDataCreare := CURRENT_TIMESTAMP;
  END;

  aAnG  := aAn;
  aSetG := aSet;

  DELETE FROM tmp_stareestimari1_centr WHERE userid = aUserID;

  multipa := (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, aAn));

  DELETE FROM tmp_cmd2 WHERE userid = auserid;

  DELETE FROM tmp_cmd_pluna2 WHERE userid = auserid;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_modificastarefaracommit</obj_name>
  <obj_hashval>a8df66041b632a647128cea9eab9cac0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_modificastarefaracommit(atermen date, acodcomanda1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC         RECORD;
  aNewCodStare1 numeric;
  aNewCodStare  numeric;
  aAn           numeric;
  aSet          numeric;
  aAnMin        numeric;
  aSetMin       numeric;
  aAnSetMax     numeric;
begin
  aAn  := to_number( to_char( aTermen, 'iyyy'));
  aSet := to_number( to_char( aTermen, 'iw'));

  --INSERT INTO x(test) VALUES(to_char( aTermen, 'dd.mm.yyyy'));

  FOR v_rec IN (SELECT codstare2, codstare, codobiect FROM stareestimari2 WHERE codcomanda1 = acodcomanda1 ORDER BY codstare2 desc)
  LOOP
    BEGIN
      SELECT an, saptamana
      INTO aAnMin, aSetMin
      FROM stareestimari
      WHERE
         codstare = v_rec.codstare;
    EXCEPTION WHEN others THEN
      aAnMin := 0;
    END;

    IF  aAnMin &gt; 0 THEN
      BEGIN
        SELECT max( sen.ang * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, sen.An)) + sen.saptamanag)
        INTO aAnSetMax
        FROM stareestimari se
        INNER JOIN stareestimari sen ON  sen.an = se.an and  sen.saptamana = se.saptamana and  sen.subunitatea = se.subunitatea
        WHERE
           se.codstare = v_rec.codstare;
      EXCEPTION WHEN others THEN
        aAnSetMax := 0;
      END;

      --INSERT INTO x(test) VALUES(v_rec.codstare2);

      IF  aAn * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, aAn)) + aSet &lt;= aAnSetmax
      THEN
        --INSERT INTO x(test) VALUES('update la termen');

        UPDATE stareestimari2 SET termen = aTermen WHERE codstare2 = v_rec.CodStare2;
      END IF;

      IF  aAn * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, aAn)) + aSet &lt; aAnMin * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, aAnMin)) + aSetMin
      THEN
        BEGIN
          SELECT se1.codstare1, se1.codstare
          INTO aNewCodStare1, aNewCodStare
          FROM stareestimari se
              INNER JOIN stareestimari  sen ON  se.an = sen.an and  se.saptamana = sen.saptamana and  se.subunitatea = sen.subunitatea and  sen.ang = sen.an and  sen.saptamanag = sen.saptamana
              INNER JOIN stareestimari1 se1 ON  sen.codstare = se1.codstare and  se1.codobiect = v_rec.codobiect
          WHERE
             se.codstare = v_rec.CodStare;
        EXCEPTION WHEN others THEN
          aNewCodStare1 := 0;
        END;

        IF  aNewCodStare1 &gt; 0 THEN
          UPDATE stareestimari2
          SET
          codstare1 = aNewCodStare1,
          codstare  = aNewCodStare
          WHERE
           codcomanda1 = aCodComanda1;
        END IF;
      ELSE
        IF  aAn * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, aAn)) + aSet &lt;= aAnSetmax
        THEN
          BEGIN
            SELECT se1.codstare1, se1.codstare
            INTO aNewCodStare1, aNewCodStare
            FROM stareestimari se
                INNER JOIN stareestimari  sen ON  se.an = sen.an and  se.saptamana = sen.saptamana and  se.subunitatea = sen.subunitatea and  sen.ang = aAn and  sen.saptamanag = aSet
                INNER JOIN stareestimari1 se1 ON  sen.codstare = se1.codstare and  se1.codobiect = v_rec.codobiect
            WHERE
               se.codstare = v_rec.CodStare;
          EXCEPTION WHEN others THEN
            aNewCodStare1 := 0;
          END;

          IF  aNewCodStare1 &gt; 0 THEN
            UPDATE stareestimari2
            SET
            codstare1 = aNewCodStare1,
            codstare  = aNewCodStare
            WHERE
             codcomanda1 = aCodComanda1;
          END IF;
        ELSE
          DELETE FROM stareestimari2 WHERE codstare2 = v_rec.codstare2;
        END IF;
      END IF;
    END IF;

    EXIT ;
  END LOOP;

  BEGIN
    SELECT se1n.codstare1, se1n.codstare
    INTO aNewCodStare1, aNewCodStare
    FROM planiflink l
        INNER JOIN stareestimari1 se1  ON  se1.codstare1 = l.codstare1
        INNER JOIN stareestimari  se   ON  se.codstare   = se1.codstare
        INNER JOIN stareestimari  sen  ON  se.an = sen.an and  se.saptamana = sen.saptamana and  se.subunitatea = sen.subunitatea and  sen.ang = aAn and  sen.saptamanag = aSet
        INNER JOIN stareestimari1 se1n ON  se1n.codstare = sen.codstare and  se1n.codobiect = se1.codobiect
    WHERE
       l.codcomanda1 = aCodComanda1
       and  sen.an * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, sen.An)) + sen.saptamana
            = (SELECT max( an * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, An)) + saptamana)
               FROM stareestimari
               WHERE subunitatea = (SELECT pkg_globals_getsubunitate.WME_RESULT FROM pkg_globals_getsubunitate(NULL,NULL))
              );
  EXCEPTION WHEN others THEN
    aNewCodStare1 := 0;
  END;

  IF  aNewCodStare1 &gt; 0 THEN
    UPDATE planiflink SET codstare1 = aNewCodStare1 WHERE codcomanda1 = aCodComanda1;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_propagamat</obj_name>
  <obj_hashval>7800df0bf1d7f168eab02f0151f6419f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_propagamat(acodobiect numeric, acodstare numeric, astoc numeric, astocmin numeric, apret numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC      RECORD;
  aSetG      numeric;
  aSet       numeric;
  aAn        numeric;
  aAnG       numeric;
  aCodOferta numeric;
begin
  BEGIN
    SELECT se.an, se.saptamana, se.ang, se.saptamanag, se.codoferta
    INTO aAn, aSet, aAnG, aSetG, aCodOferta
    FROM stareestimari se
    WHERE
       se.codstare = aCodStare;
  EXCEPTION WHEN others THEN
    aSet := 0;
  END;

  IF  aSet = 0 THEN
    RETURN;
  END IF;

  FOR v_rec IN
  (
  SELECT COALESCE( se1.codstare1, 0) CODSTARE1, se.codstare
  FROM stareestimari se
       LEFT JOIN stareestimari1 se1 ON  se1.codstare = se.codstare and  se1.codobiect = aCodObiect
  WHERE an = aAn and  saptamana = aSet and  ang * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, aAn)) + saptamanag &lt;&gt; aAnG * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, aAn)) + aSetG
  )
  LOOP
    IF  v_rec.codstare1 &gt; 0 THEN
      UPDATE stareestimari1 SET dirty = COALESCE( dirty, 0) + 1 WHERE codstare1 = v_rec.codstare1;
    ELSE
      IF  v_rec.codstare &gt; 0 THEN
        INSERT INTO stareestimari1(codstare, codobiect, dirty, codstare1, stocmin, stocini, pret)
        VALUES(v_rec.codstare, aCodObiect, 1, NEXTVAL('SEQ_STAREESTIMARI1_CODSTARE1'), aStocMin, aStoc, aPret);
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_refreshdatets</obj_name>
  <obj_hashval>f6a625a32aa96b0986518522878e83fa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_refreshdatets(acodstarec numeric, acodstaren numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  V            RECORD;
  aSubunitatea numeric;
  aAn          numeric;
  aSet         numeric;
  aCodOferta   numeric;
  vUser        numeric := GETUSERID();
BEGIN
  --Adina 19/04/2021 - sinc.Oracle din 19.04.2021
  BEGIN
    SELECT se.subunitatea, se.an, se.saptamana, se.codoferta
    INTO aSubunitatea, aAn, aSet, aCodOferta
    FROM stareestimari se
    WHERE se.codstare = aCodStareC;
  EXCEPTION WHEN others THEN
    RETURN;
  END;

  PERFORM PKG_PLANIFCMD_UmpleTemporarGenerator( aAn * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, aAn)) + aSet, vUser, aSubunitatea);

  FOR v_rec IN
  (
    SELECT tmp.codobiect CODOBIECT, osub.stocmin STOCMIN, stoc.cant CANT, o1.pret PRET, tmp.cantc CONSUM
    FROM TMP_CMDTL tmp
        LEFT JOIN nartobjsubunit osub ON   osub.codobiect = tmp.codobiect
                                      and ( osub.codgest is null or osub.codgest = 0)
                                      and  osub.subunitate = aSubunitatea
        LEFT JOIN (SELECT sum( ns.rest) CANT, ns.codobiect
                   FROM nirstoc ns
                        INNER JOIN nir     ON  nir.codnir = ns.codnir
                        INNER JOIN ngest g ON  g.codgest  = nir.gest
                   WHERE g.codsubunit = aSubunitatea and  ns.rest &lt;&gt; 0 and  g.tip &lt;&gt; 4
                   GROUP BY ns.codobiect
                  ) stoc ON  stoc.codobiect = tmp.codobiect
        LEFT JOIN OFERTA1 O1 ON  O1.CODOFERTA = aCodOferta and  O1.Codobiect = tmp.Codobiect
    WHERE tmp.tip IN (1, 2) and  tmp.userid = vUser
      and  NOT  EXISTS (SELECT se1.codobiect
                        FROM stareestimari1 se1 INNER JOIN stareestimari se ON  se.codstare = se1.codstare
                        WHERE se.an = aAn and  se.saptamana = aSet and  se.subunitatea = aSubunitatea and  se1.codobiect = tmp.codobiect
                       )
  )
  LOOP
    INSERT INTO stareestimari1(codstare, codobiect, stocmin, codstare1, pret, stocini, consum)
    SELECT se.codstare, v_rec.codobiect, v_rec.stocmin, NEXTVAL('SEQ_STAREESTIMARI1_CODSTARE1'), v_rec.pret, v_rec.cant, v_rec.consum
    FROM stareestimari se
    WHERE se.an = aAn and  se.saptamana = aSet and  se.subunitatea = aSubunitatea;
  END LOOP;

  FOR V IN (SELECT tmp.codobiect, tmp.resta ESTIMAT, tmp.cantc CONSUM, TMP.CANTA DETALIERI
            FROM TMP_CMDTL tmp
            WHERE tmp.tip = 2 and  tmp.userid = vUser
           )
  LOOP
    UPDATE  stareestimari1 S
     SET ESTIMAT = COALESCE( V.DETALIERI, 0) - COALESCE( S.CONSUM, 0)
    WHERE
     S.CODOBIECT = V.CODOBIECT and  S.CODSTARE = ACODSTAREN;
  END LOOP;

  FOR V IN (SELECT tmp.codobiect, tmp.resta ESTIMAT, tmp.cantc CONSUM, TMP.CANTA DETALIERI
            FROM TMP_CMDTL tmp
            WHERE tmp.tip = 1 and  tmp.userid = vUser
           )
  LOOP
    UPDATE  stareestimari1 S
     SET ESTIMAT = COALESCE( V.DETALIERI, 0) - COALESCE( S.CONSUM, 0)
    WHERE
     S.CODOBIECT = V.CODOBIECT and  S.CODSTARE = ACODSTAREC;
  END LOOP;

  UPDATE stareestimari SET dirty = 0 WHERE codstare = aCodStareC;
  UPDATE stareestimari SET dirty = 0 WHERE codstare = aCodStareN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_setdirtydints</obj_name>
  <obj_hashval>dab0d7bf7ced85d9a2a0f78610ac09ec</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_setdirtydints()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR v_rec IN
  (
    SELECT se1.codstare1
    FROM necesar n
        INNER JOIN necesarobj     nobj ON  n.codnecesar = nobj.codnecesar
        INNER JOIN stareestimari  se   ON  se.saptamana = n.saptamana  and  se.subunitatea = n.subunitatea
        INNER JOIN stareestimari1 se1  ON  se.codstare  = se1.codstare and  se1.codobiect  = nobj.codobiect
    WHERE
            EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = 'CODNECESAR' and  n.codnecesar   = valoare::numeric)
       and  EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = 'CODOBIECT'  and  nobj.codobiect = valoare::numeric)
  )
  LOOP
    UPDATE stareestimari1 SET dirty = COALESCE( dirty, 0) + 1 WHERE codstare1 = v_rec.codstare1;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_setnecesaraccpestare1</obj_name>
  <obj_hashval>f2ed8a2189533e2b766871e787f410b3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_setnecesaraccpestare1(acodstare1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  aSaptamana  numeric;
  aSaptamanaG numeric;
  aAn         numeric;
  aAnG        numeric;
  aDataStopG  date;
  aNecesarAcc double precision;
begin
  BEGIN
    SELECT se.an, se.ang, se.saptamana, se.saptamanag, (SELECT iso_week_to_date.WME_RESULT FROM iso_week_to_date(NULL, se.AnG, se.SaptamanaG)) + 6, COALESCE( se1.necesaracc, -9999999999)
    INTO aAn, aAnG, aSaptamana, aSaptamanaG, aDataStopG, aNecesarAcc
    FROM stareestimari1 se1
         INNER JOIN stareestimari se ON  se.codstare = se1.codstare
    WHERE
       se1.codstare1 = aCodStare1;
  EXCEPTION WHEN others THEN
    RETURN;
  END;

  IF  aNecesarAcc = -9999999999 THEN
    FOR v_rec IN (SELECT CASE WHEN  x.necesar + x.stocmin &gt; 0 THEN x.necesar + x.stocmin ELSE 0 END  NECESARACC
                  FROM (SELECT COALESCE( se1.stocmin, 0) STOCMIN,
                               COALESCE( se1.necesar, 0) - COALESCE( cmdf.cant, 0) + COALESCE( estint.cant, 0) - COALESCE( cmdff.cant, 0) + COALESCE( se1.estimat, 0) - COALESCE( se1.stocmin, 0) NECESAR
                        FROM stareestimari se
                            INNER JOIN stareestimari1 se1 ON  se1.codstare  = se.codstare
                            INNER JOIN nartobj        obj ON  se1.codobiect = obj.codobiect
                            LEFT  JOIN (SELECT sum( se2.restacceptat) CANT, se1.codobiect
                                        FROM stareestimari2 se2
                                            INNER JOIN stareestimari1 se1  ON  se2.codstare1 = se1.codstare1
                                            INNER JOIN stareestimari1 se11 ON  se1.codstare  = se11.codstare and  se1.codobiect = se11.codobiect
                                            INNER JOIN stareestimari  se   ON  se11.codstare = se.codstare and  se2.codstare = se.codstare
                                        WHERE se11.codstare1 = aCodStare1 and  se.an = aAn and  se.saptamana = aSaptamana and se.AnG * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, aAn)) + se.saptamanag BETWEEN aAn * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, aAn)) + aSaptamana + 1 AND aAnG * 53 + aSaptamanaG - 1
                                        GROUP BY se1.codobiect
                                       ) cmdf ON  cmdf.codobiect = se1.codobiect
                            LEFT  JOIN (SELECT sum( COALESCE( se11.estimat, 0)) CANT, se11.codobiect
                                        FROM stareestimari1 se1
                                            INNER JOIN stareestimari1 se11 ON  se1.codstare  = se11.codstare and  se11.codobiect = se1.codobiect
                                            INNER JOIN stareestimari  se   ON  se11.codstare = se.codstare
                                        WHERE se1.codstare1 = aCodStare1 and  se.an = aAn and  se.saptamana = aSaptamana and se.AnG * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, aAn)) + se.saptamanag BETWEEN aAn * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, aAn)) + aSaptamana + 1 AND aAnG * 53 + aSaptamanaG - 1
                                        GROUP BY se11.codobiect
                                       ) estint ON  estint.codobiect = se1.codobiect
                            LEFT  JOIN (SELECT sum( se2.restacceptat) CANT, se1.codobiect
                                        FROM stareestimari2 se2
                                            INNER JOIN stareestimari1 se1 ON  se2.codstare1 = se1.codstare1
                                            INNER JOIN stareestimari  se  ON  se1.codstare  = se.codstare and  se2.codstare = se.codstare
                                        WHERE se1.codstare1 = aCodStare1
                                        GROUP BY se1.codobiect
                                       ) cmdff ON  cmdff.codobiect = se1.codobiect
                            LEFT  JOIN (SELECT SUM( C1.CANTACCEPTAT) CANT, SE1.CODSTARE1
                                        FROM STAREESTIMARI1 SE1
                                            INNER JOIN stareestimari  se   ON  se1.codstare = se.codstare
                                            INNER JOIN stareestimari  ses  ON  se.An = ses.An and  se.saptamana = ses.saptamana and  se.subunitatea = ses.subunitatea
                                            INNER JOIN stareestimari1 se11 ON  ses.codstare   = se11.codstare and  se1.codobiect = se11.codobiect
                                            INNER JOIN PLANIFLINK     L    ON  SE11.CODSTARE1 = L.CODSTARE1
                                            INNER JOIN COMANDA1       C1   ON  C1.CODCOMANDA1 = L.CODCOMANDA1
                                            INNER JOIN COMANDA        C    ON  C.CODCOMANDA   = C1.CODCOMANDA
                                        WHERE se1.codstare1 = aCodStare1 and  c1.termen &lt;= aDataStopG
                                        GROUP BY SE1.CODSTARE1
                                       ) CMDFP ON  CMDFP.CODSTARE1 = SE1.CODSTARE1
                            LEFT  JOIN (SELECT SUM( PC1.REST) CANT, SE1.CODSTARE1
                                        FROM STAREESTIMARI1 SE1
                                            INNER JOIN STAREESTIMARI SE  ON  SE1.CODSTARE  = SE.CODSTARE
                                            INNER JOIN PRECOMANDA1   PC1 ON  PC1.CODSTARE1 = SE1.CODSTARE1
                                            INNER JOIN PRECOMANDA    PC  ON  PC.CODPRECOMANDA = PC1.CODPRECOMANDA
                                        WHERE se1.codstare1 = aCodStare1 AND  PC.USERID = (SELECT PKG_GLOBALS_GETUSERID.WME_RESULT FROM PKG_GLOBALS_GETUSERID(NULL,NULL))
                                        GROUP BY SE1.CODSTARE1
                                       ) RESTC ON  RESTC.CODSTARE1 = SE1.CODSTARE1
                            LEFT  JOIN (SELECT SUM( PC1.REST) CANT, SE1.CODSTARE1
                                        FROM STAREESTIMARI1 SE1
                                            INNER JOIN STAREESTIMARI SE  ON  SE1.CODSTARE  = SE.CODSTARE
                                            INNER JOIN PRECOMANDA1   PC1 ON  PC1.CODSTARE1 = SE1.CODSTARE1
                                            INNER JOIN PRECOMANDA    PC  ON  PC.CODPRECOMANDA = PC1.CODPRECOMANDA
                                        WHERE se1.codstare1 = aCodStare1 AND  PC.USERID &lt;&gt; (SELECT PKG_GLOBALS_GETUSERID.WME_RESULT FROM PKG_GLOBALS_GETUSERID(NULL,NULL))
                                        GROUP BY SE1.CODSTARE1
                                       ) RESTCA ON  RESTCA.CODSTARE1 = SE1.CODSTARE1
                        WHERE se1.codstare1 = aCodStare1
                       ) x
    )
    LOOP
      UPDATE stareestimari1 SET necesaracc = v_rec.necesaracc WHERE codstare1 = aCodStare1;
    END LOOP;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_setstare</obj_name>
  <obj_hashval>2445c37c4985034f7400bf01ef9c3668</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_setstare(asetg numeric, aang numeric, aset numeric, aan numeric, acodstare numeric, asubunitatea numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V           RECORD;
  sColEstimat varchar;
  sSQL        varchar;
  aDataS      date;
  aDataF      date;
  vUser       numeric := GETUSERID();
BEGIN
  --Adina 19.04.2021 - sinc.Oracle din 19.04.2021
  IF  aAnG = aAn
  THEN sColEstimat := 'e1m.c' || aSetG;
  ELSE sColEstimat := 'e1m.n' || aSetG;
  END IF;

  IF  aAnG * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, aAn)) + aSetG &gt; aAn * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, aAn)) + aSet + 1
  THEN
    sSQL := 'DO $$
             declare
               v record;
             begin
               For v in (
                         select e1m.codobiect, sum(' || sColEstimat || ') estimat, osub.stocmin
                         from estimariprod1m e1m
                              inner join estimariprod   e    on  e.codestimareprod = e1m.codestimareprod
                              left  join nartobjsubunit osub on  osub.codobiect = e1m.codobiect
                                                             and ( osub.codgest is null or osub.codgest = 0)
                                                             and osub.subunitate = ' || aSubunitatea || '
                         where e.an = ' || aAn || ' and e.saptamana = ' || aSet || ' and coalesce(' || sColEstimat || ',0) &gt; 0
                               and e.operat = 1 and coalesce(e.anulat,0) = 0 and e.subunitatea = ' || aSubunitatea || '
                         group by e1m.codobiect, osub.stocmin
                        )
               Loop
                 UPDATE stareestimari1 SET ESTIMAT = coalesce(ESTIMAT,0) + V.ESTIMAT
                 WHERE CODOBIECT = V.CODOBIECT and codstare = ' || aCodStare || '
               End Loop;
             END $$; ';
    EXECUTE sSQL;
  ELSE
    IF  aAnG * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, aAn)) + aSetG = aAn * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, aAn)) + aSet + 1
    THEN
      FOR V IN (SELECT tmp.codobiect, tmp.resta ESTIMAT, osub.stocmin, tmp.cantc CONSUM
                FROM TMP_CMDTL tmp
                     LEFT JOIN nartobjsubunit osub ON   osub.codobiect = tmp.codobiect
                                                   and (osub.codgest is null or osub.codgest = 0)
                                                   and  osub.subunitate = aSubunitatea
                WHERE tmp.tip = 2 and  tmp.userid = vUser
               )
      LOOP
        UPDATE  stareestimari1 S
         SET ESTIMAT = V.ESTIMAT, CONSUM = V.CONSUM
        WHERE
         S.CODOBIECT = V.CODOBIECT and  S.CODSTARE = ACODSTARE;
      END LOOP;
    ELSE
      FOR V IN (SELECT tmp.codobiect, tmp.resta ESTIMAT, osub.stocmin, tmp.cantc CONSUM
                FROM TMP_CMDTL tmp
                     LEFT JOIN nartobjsubunit osub ON   osub.codobiect = tmp.codobiect
                                                   and (osub.codgest is null or osub.codgest = 0)
                                                   and  osub.subunitate = aSubunitatea
                WHERE tmp.tip = 1 and  tmp.userid = vUser
      ) LOOP
        UPDATE  stareestimari1 S
         SET ESTIMAT = V.ESTIMAT, CONSUM = V.CONSUM
        WHERE
         S.CODOBIECT = V.CODOBIECT and  S.CODSTARE = ACODSTARE;
      END LOOP;
    END IF;
  END IF;

  aDataS := (SELECT iso_week_to_date.WME_RESULT FROM iso_week_to_date(NULL, aAnG, aSetG));
  aDataF := aDataS + 6;

  IF  aAnG * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, aAn)) + aSetG = aAn * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, aAn)) + aSet
  THEN
    INSERT INTO stareestimari2(codstare2, codstare1, codstare, codcomanda1, datadoc, nrdoc, codpart, codobiect, umsec, restacceptat, pu, codmoneda, termen, saptamana)
    SELECT NEXTVAL('SEQ_STAREESTIMARI2_CODSTARE2'), se1.codstare1, se.codstare, c1.codcomanda1, c.datadoc, c.nrdoc, c.partener, c1.codobiect, c1.umsec, c1.restacceptat, c1.pu, c.moneda, c1.termen, aSet
    FROM stareestimari1 se1, stareestimari se, comanda1 c1, comanda c
    WHERE  se.codstare = se1.codstare and  se1.codobiect = c1.codobiect and  c1.codcomanda = c.codcomanda
      and  se.an = aAn and  se.saptamana = aSet and  se.ang = aAnG and  se.saptamanag = aSetG
      and  COALESCE( c.anulat, 0) = 0 and  c.operat = 1 and  c1.termen &lt;= aDataF and  c.tipdoc = 8
      and  c1.restacceptat &lt;&gt; 0 and  se.subunitatea = aSubunitatea and  c.subunitatea = aSubunitatea
      and  COALESCE( c.inchisa, 0) = 0;
  ELSE
    INSERT INTO stareestimari2(codstare2, codstare1, codstare, codcomanda1, datadoc, nrdoc, codpart, codobiect, umsec, restacceptat, pu, codmoneda, termen, saptamana)
    SELECT NEXTVAL('SEQ_STAREESTIMARI2_CODSTARE2'), se1.codstare1, se.codstare, c1.codcomanda1, c.datadoc, c.nrdoc, c.partener, c1.codobiect, c1.umsec, c1.restacceptat, c1.pu, c.moneda, c1.termen, aSet
    FROM stareestimari1 se1, stareestimari se, comanda1 c1, comanda c
    WHERE  se.codstare = se1.codstare and  se1.codobiect = c1.codobiect and  c1.codcomanda = c.codcomanda
      and  se.an = aAn and  se.saptamana = aSet and  se.ang = aAnG and  se.saptamanag = aSetG
      and  COALESCE( c.anulat, 0) = 0 and  c.operat = 1 and c1.termen BETWEEN aDataS AND aDataF
      and  c.tipdoc = 8 and  c1.restacceptat &lt;&gt; 0 and  se.subunitatea = aSubunitatea
      and  c.subunitatea = aSubunitatea and  COALESCE( c.inchisa, 0) = 0;
  END IF;

  UPDATE stareestimari1 se1
  SET
  CmdF = (SELECT sum( se2.restacceptat) FROM stareestimari2 se2 WHERE se2.codstare = se1.codstare and  se2.codstare1 = se1.codstare1)
  WHERE
   se1.codstare = acodstare;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_stergesalvare</obj_name>
  <obj_hashval>1aa8585066ab2f328ac9751b0a63d89d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_stergesalvare(acodstare numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  V_REC1 RECORD;
  V_XXX  RECORD;
  vAn    numeric;
  vSet   numeric;
  vData  date;
BEGIN
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  BEGIN
    SELECT se.an, se.saptamana, se.datacreare
    INTO vAn, vSet, vData
    FROM stareestimari se
    WHERE
       se.codstare = aCodStare;
  EXCEPTION WHEN others THEN
    vAn  := 0;
    vSet := 0;
  END;

  IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_PLANIFCMD.CT_MONITOR', true))))
  THEN
    PERFORM pkg_userfirme_postlogcucommit( 'STAREESTIMARI', (current_setting('PKG_GLOBALS.USERNAME', true)), 'S', vAn * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, vAn)) + vSet, (current_setting('PKG_GLOBALS.FIRMANAME', true)), (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL)), vData, vSet || '/' || vAn, vSet || '/' || vAn, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  FOR v_rec IN (SELECT codstare FROM stareestimari WHERE an = vAn and  Saptamana = vSet) LOOP
    DELETE FROM stareestimari WHERE codstare = v_rec.codstare;

    FOR v_rec1 IN (SELECT codstare1 FROM stareestimari1 WHERE codstare = v_rec.codstare) LOOP
      FOR v_xxx IN (SELECT codprecomanda1 FROM precomanda1 WHERE codstare1 = v_rec1.codstare1) LOOP
        DELETE FROM precmdlink WHERE codprecomanda1 = v_xxx.codprecomanda1;
      END LOOP;

      DELETE FROM planiflink WHERE codstare1 = v_rec1.codstare1;
    END LOOP;

    DELETE FROM stareestimari1 WHERE codstare = v_rec.codstare;
    DELETE FROM stareestimari2 WHERE codstare = v_rec.codstare;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_updatecmdexttl</obj_name>
  <obj_hashval>fdfe2ebb2e98c2219902bfe181a0f0fe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_updatecmdexttl(aan numeric, aset numeric, aang numeric, asetg numeric, afield character varying, acodcomanda numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Val         varchar;
  Aux         varchar;
  aCount      numeric;
  aNextAn     numeric;
  aNextSet    numeric;
  oData       date;
  CuDetalieri boolean;
BEGIN
  --Florin 13.06.2023 - sinc. Oracle
  IF  (SELECT pkg_list_struct_TmpExists.WME_RESULT FROM pkg_list_struct_TmpExists(NULL, 'COMANDF')) = 1
  THEN
    Val         := 'Necesar : ' || aSet || '/' || aAn;
    oData       := (SELECT iso_week_to_date.WME_RESULT FROM iso_week_to_date(NULL, aan, aset));
    oData       := oData + 7;
    aNextSet    := to_char( odata, 'IW')::numeric;
    aNextAn     := to_char( odata, 'IYYY')::numeric;
    CuDetalieri := (   aAnG = aNextAn and  aSetG = aNextSet)  or (   aAn = aAnG and  aSet = aSetG) ;

    IF CuDetalieri THEN
      BEGIN
      aux := '';
      SELECT string_agg( doc,',') INTO Aux
      FROM (SELECT p.nrdoc || '/' || to_char( p.datadoc, 'dd.mm.yyyy') DOC
            FROM planifprod p
            WHERE p.an = aAn and  p.saptamana = aSet and  p.insaptamana = 1
            union ALL
            SELECT p.nrdoc || '/' || to_char( p.datadoc, 'dd.mm.yyyy') DOC
            FROM planifprod p
            WHERE p.an = aNextAn and  p.saptamana = aNextSet and  p.insaptamana = 0
           ) A_PG;
      EXCEPTION WHEN others THEN
        Aux := '';
      END;

      IF  Length( Aux) &gt; 0 THEN
        Val := Val || ' Detalieri : ' || aux;
      END IF;
    END IF;

    BEGIN
      EXECUTE 'select count(*) from comandf where codcomanda = ' || acodcomanda;
    EXCEPTION WHEN others THEN
      aCount := 0;
    END;

    IF  aCount &gt; 0 THEN
      BEGIN
        Aux := 'update comandf set ' || aField || ' = ''' || Val || ''' where codcomanda = ' || aCodComanda;
        EXECUTE Aux;
      EXCEPTION WHEN others THEN
        Aux := '';
      END;
    ELSE
      BEGIN
        Aux := 'insert into comandf(CodComandf,CodComanda,'||aField||') values(nextval(''seq_comandf_codcomandf''),'||aCodComanda||','''||Val||''')';
        EXECUTE Aux;
      EXCEPTION WHEN others THEN
        Aux := '';
      END;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_updatecmdf</obj_name>
  <obj_hashval>71c37253879ab8562e351ca66027973d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_updatecmdf(INOUT wme_result numeric, INOUT acodstare1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  Cant       double precision;
  aSetG      numeric;
  aSet       numeric;
  aAn        numeric;
  aAnG       numeric;
  aCodOferta numeric;
begin
  BEGIN
    SELECT se.an, se.saptamana, se.ang, se.saptamanag, se.codoferta
    INTO aAn, aSet, aAnG, aSetG, aCodOferta
    FROM stareestimari1 se1
    INNER JOIN stareestimari se ON  se.codstare = se1.codstare
    WHERE
       se1.codstare1 = aCodStare1;
  EXCEPTION WHEN others THEN
    aSet := 0;
  END;

  IF  aSet = 0 THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  IF  aSetG = aSet THEN
    INSERT INTO stareestimari2(codstare2, codstare1, codstare, codcomanda1, datadoc, nrdoc, codpart, codobiect, umsec, restacceptat, pu, codmoneda, termen, saptamana)
    SELECT NEXTVAL('SEQ_STAREESTIMARI2_CODSTARE2'), se1.codstare1, se.codstare, c1.codcomanda1, c.datadoc, c.nrdoc, c.partener, c1.codobiect, c1.umsec, c1.restacceptat, c1.pu, c.moneda, c1.termen, aSet
    FROM stareestimari1 se1, stareestimari se, comanda1 c1, comanda c
    WHERE  se1.codstare1 = aCodStare1 and  se.codstare = se1.codstare and  se1.codobiect = c1.codobiect
      and  c1.codcomanda = c.codcomanda and  se.an = aAn and  se.saptamana = aSet and  se.ang = aAnG
      and  se.saptamanag = aSetG and  COALESCE( c.anulat, 0) = 0 and  c.operat = 1
      and  c1.termen &lt;= (SELECT iso_week_to_date.WME_RESULT FROM iso_week_to_date(NULL, aAnG, aSetG)) + 6
      and  c.tipdoc = 8 and  c1.restacceptat &lt;&gt; 0 and  c.subunitatea = se.subunitatea and  COALESCE( c.inchisa, 0) = 0
      and  NOT  EXISTS (SELECT se2.codcomanda1 FROM stareestimari2 se2 WHERE se2.codcomanda1 = c1.codcomanda1)
      and  NOT  EXISTS (SELECT l.codcomanda1 FROM planiflink l WHERE l.codcomanda1 = c1.codcomanda1);
  ELSE
    INSERT INTO stareestimari2(codstare2, codstare1, codstare, codcomanda1, datadoc, nrdoc, codpart, codobiect, umsec, restacceptat, pu, codmoneda, termen, saptamana)
    SELECT NEXTVAL('SEQ_STAREESTIMARI2_CODSTARE2'), se1.codstare1, se.codstare, c1.codcomanda1, c.datadoc, c.nrdoc, c.partener, c1.codobiect, c1.umsec, c1.restacceptat, c1.pu, c.moneda, c1.termen, aSet
    FROM stareestimari1 se1, stareestimari se, comanda1 c1, comanda c
    WHERE  se.codstare = se1.codstare and  se1.codobiect = c1.codobiect and  c1.codcomanda = c.codcomanda
      and  se.an = aAn and  se.saptamana = aSet and  se.ang = aAnG and  se.saptamanag = aSetG
      and  COALESCE( c.anulat, 0) = 0 and  c.operat = 1
      and c1.termen BETWEEN (SELECT iso_week_to_date.WME_RESULT FROM iso_week_to_date(NULL, aAnG, aSetG))
                        AND (SELECT iso_week_to_date.WME_RESULT FROM iso_week_to_date(NULL, aAnG, aSetG)) + 6
      and  c.tipdoc = 8 and  c1.restacceptat &lt;&gt; 0 and  c.subunitatea = se.subunitatea and  COALESCE( c.inchisa, 0) = 0
      and  NOT  EXISTS (SELECT se2.codcomanda1 FROM stareestimari2 se2 WHERE se2.codcomanda1 = c1.codcomanda1)
      and  NOT  EXISTS (SELECT l.codcomanda1 FROM planiflink l WHERE l.codcomanda1 = c1.codcomanda1);
  END IF;

  UPDATE stareestimari1 se1
  SET
  CmdF = (SELECT sum( se2.restacceptat) FROM stareestimari2 se2 WHERE se2.codstare = se1.codstare and  se2.codstare1 = se1.codstare1),
  pret = (SELECT o1.pret FROM oferta1 o1 WHERE o1.codoferta = aCodOferta and  se1.codobiect = o1.codobiect)
  WHERE
   se1.codstare1 = acodstare1;

  BEGIN
    SELECT COALESCE( cmdf, 0) INTO cant FROM stareestimari1 WHERE codstare1 = acodstare1;
  EXCEPTION WHEN others THEN
    cant := 0;
  END;

  WME_Result :=  cant;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_vallcls</obj_name>
  <obj_hashval>ea6c8aba9601af899019cb6c298cf30d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_vallcls(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANIFCMD.vAllCls', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_vallclss</obj_name>
  <obj_hashval>406cda81e2a6e2ed1b81684d849405f5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_vallclss(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANIFCMD.vAllClsS', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_vallprod</obj_name>
  <obj_hashval>34710bdd30ec94e3ea7a61e35750b156</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_vallprod(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANIFCMD.vAllProd', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprod_bagamateriale</obj_name>
  <obj_hashval>2e4fab8d7bfc8ec1918623ce269110ad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprod_bagamateriale(anodoriginal numeric, acodobiect numeric, anecesar numeric, acodprodcomp numeric, anivel numeric, acodplanifprod1 numeric, acodplanifprod numeric, aobservatii character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_TMP             RECORD;
  vcodplanifnod     numeric;
  vcodplanifnodorig numeric;
  aCount            numeric;
  vCodProdComp      numeric;
begin
  FOR v_tmp IN (SELECT mat.codobiect,
                       CASE WHEN  COALESCE( mat.tip, 3) &lt;= 2 THEN COALESCE( pc.codprodcomp, 0) ELSE 0 END  CODPRODCOMP,
                       aNecesar / CASE WHEN  COALESCE( prod.cant, 0)=0 THEN 1 ELSE  prod.cant END  * mat.cant CANT,
                       mat.codmat, mat.indexlocal,
                       CASE WHEN  COALESCE( mat.tip, 3) &lt;= 2 THEN 1 ELSE 3 END  TIP,
                       aObservatii || '.' || LPAD( to_char( mat.IndexLocal,'9999999999'), 2, '0') OBSERVATII, prod.cant LOTOPTIM, mat.cant CANTMAT
                FROM prodmat mat
                INNER JOIN prodcomp prod ON  prod.codprodcomp = mat.codprodcomp
                LEFT JOIN prodcomp pc ON  pc.codobiect = mat.codobiect and  pc.implicit = 1 and  mat.tip &lt;= 2
                WHERE mat.codprodcomp = aCodProdComp
                ORDER BY mat.indexlocal
               )
  LOOP
    SELECT NEXTVAL('SEQ_PLANIFNOD_CODPLANIFNOD') INTO vcodplanifnod;

    INSERT INTO planifnod(codplanifnod, codplanifprod1, codplanifprod, cant, nodoriginal, pozitie, tip, codobiect, indexparinte, codprodmat, nivel, ordine, versiune, cantprodreteta, cantmatreteta, necesar)
    VALUES(vcodplanifnod, aCodPlanifProd1, aCodPlanifProd, v_tmp.cant, aNodOriginal, v_tmp.indexlocal,
           CASE WHEN  v_tmp.codprodcomp &gt; 0 THEN 1 ELSE 3 END ,
           v_tmp.codobiect, v_tmp.Observatii, v_tmp.codmat, aNivel, v_tmp.indexlocal, 0, v_tmp.lotoptim, v_tmp.cantmat, v_tmp.cant
          );

    IF  v_tmp.CodProdComp &gt; 0 THEN
      SELECT NEXTVAL('SEQ_PLANIFNOD_CODPLANIFNOD') INTO vcodplanifnodorig;

      INSERT INTO planifnod(codplanifnod, codplanifprod1, codplanifprod, cant, nodoriginal, pozitie, tip, codobiect, indexparinte, codprodmat, nivel, ordine, versiune, cantprodreteta, cantmatreteta, necesar, codreteta)
      VALUES(vcodplanifnodorig, aCodPlanifProd1, aCodPlanifProd, v_tmp.cant, aNodOriginal, v_tmp.indexlocal,
             CASE WHEN  v_tmp.codprodcomp &gt; 0 THEN 1 ELSE 3 END ,
             v_tmp.codobiect, v_tmp.Observatii, v_tmp.codmat, aNivel, v_tmp.indexlocal, 1, v_tmp.lotoptim, v_tmp.cantmat, v_tmp.cant, v_tmp.codprodcomp
            );

      PERFORM pkg_planifprod_BagaMateriale( vcodplanifnodorig, v_tmp.CodObiect, v_tmp.Cant, v_tmp.CodProdComp, aNivel + 1, aCodPlanifProd1, aCodPlanifProd, v_tmp.observatii);
    ELSE
      IF  v_tmp.tip = 1 THEN
        SELECT count( *) INTO aCount FROM prodcomp WHERE codobiect = v_tmp.codobiect and  COALESCE( anulat, 0) = 0 and  COALESCE( inactiv, 0) = 0;
        IF  aCount = 1 THEN
          BEGIN
            SELECT codprodcomp INTO vCodProdComp FROM prodcomp WHERE codobiect = v_tmp.codobiect and  COALESCE( anulat, 0) = 0 and  COALESCE( inactiv, 0) = 0;
          EXCEPTION WHEN others THEN
            vCodProdComp := 0;
          END;

          SELECT NEXTVAL('SEQ_PLANIFNOD_CODPLANIFNOD') INTO vcodplanifnodorig;

          INSERT INTO planifnod(codplanifnod, codplanifprod1, codplanifprod, cant, nodoriginal, pozitie, tip, codobiect, indexparinte, codprodmat, nivel, ordine, versiune, cantprodreteta, cantmatreteta, necesar, codreteta)
          VALUES(vcodplanifnodorig, aCodPlanifProd1, aCodPlanifProd, v_tmp.cant, aNodOriginal, v_tmp.indexlocal,
                 CASE WHEN  vcodprodcomp &gt; 0 THEN 1 ELSE 3 END ,
                 v_tmp.codobiect, v_tmp.Observatii, v_tmp.codmat, aNivel, v_tmp.indexlocal, 1, v_tmp.lotoptim, v_tmp.cantmat, v_tmp.cant, vcodprodcomp
                );

          IF  vCodProdComp &gt; 0 THEN
            PERFORM pkg_planifprod_BagaMateriale( vcodplanifnodorig, v_tmp.CodObiect, v_tmp.Cant, vCodProdComp, aNivel + 1, aCodPlanifProd1, aCodPlanifProd, v_tmp.observatii);
          END IF;
        END IF;
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprod_carnetdoc_i</obj_name>
  <obj_hashval>9c6b1a85c1ca4948a958ff2875612241</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprod_carnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANIFPROD.CARNETDOC_I', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprod_ct_monitor</obj_name>
  <obj_hashval>2b4a42b5f838f75dc9d48f4f518774f0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprod_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_PLANIFPROD.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_45';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprod_genstruct</obj_name>
  <obj_hashval>b88f2ae7211216c9652f4199dd25ed28</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprod_genstruct(INOUT wme_result numeric, INOUT vcodplanifprod numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  V_XXX RECORD;
  Rez               numeric;
  vcodplanifnod     numeric;
  vcodplanifnodorig numeric;
  vCodProdComp      numeric;
  aCount            numeric;
begin
  Rez := 0;
  FOR v_rec IN (SELECT p1.codobiect, p1.codplanifprod1, p1.necesar FROM planifprod1 p1 WHERE p1.codplanifprod = vCodPlanifProd) LOOP
    SELECT count( *) INTO aCount FROM prodcomp WHERE codobiect = v_rec.codobiect and  implicit = 1 and  COALESCE( anulat, 0) = 0 and  COALESCE( inactiv, 0) = 0;
    IF  aCount = 1 THEN
      FOR v_xxx IN (SELECT codprodcomp FROM prodcomp WHERE codobiect = v_rec.codobiect and  implicit = 1 and  COALESCE( anulat, 0) = 0 and  COALESCE( inactiv, 0) = 0)
      LOOP
        DELETE FROM planifnod WHERE codplanifprod = vcodplanifprod;

        SELECT NEXTVAL('SEQ_PLANIFNOD_CODPLANIFNOD') INTO vcodplanifnod;

        INSERT INTO planifnod(codplanifnod, codplanifprod1, codplanifprod, nodoriginal, codobiect, pozitie, nivel, tip, versiune, indexparinte, necesar, cant, cantmatreteta, cantprodreteta)
        VALUES(vcodplanifnod, v_rec.codplanifprod1, vcodplanifprod, 0, v_rec.codobiect, 0, 0, 1, 0, '.00', v_rec.necesar, v_rec.necesar, 0, 0);

        SELECT NEXTVAL('SEQ_PLANIFNOD_CODPLANIFNOD') INTO vcodplanifnodorig;

        INSERT INTO planifnod(codplanifnod, codplanifprod1, codplanifprod, nodoriginal, codobiect, pozitie, nivel, tip, versiune, indexparinte, necesar, cant, cantmatreteta, cantprodreteta, codreteta)
        VALUES(vcodplanifnodorig, v_rec.codplanifprod1, vcodplanifprod, vcodplanifnod, v_rec.codobiect, 0, 0, 1, 1, '.00', v_rec.necesar, v_rec.necesar, 0, 0, v_xxx.codprodcomp);

        PERFORM pkg_planifprod_BagaMateriale( vcodplanifnodorig, v_rec.codobiect, v_rec.necesar, v_xxx.codprodcomp, 1, v_rec.codplanifprod1, vCodPlanifProd, '.00');
      END LOOP;
    ELSE
      SELECT count( *) INTO aCount FROM prodcomp WHERE codobiect = v_rec.codobiect and  COALESCE( anulat, 0) = 0 and  COALESCE( inactiv, 0) = 0;
      IF  aCount = 1 THEN
        FOR v_xxx IN (SELECT codprodcomp FROM prodcomp WHERE codobiect = v_rec.codobiect and  COALESCE( anulat, 0) = 0 and  COALESCE( inactiv, 0) = 0) LOOP
          DELETE FROM planifnod WHERE codplanifprod = vcodplanifprod;

          SELECT NEXTVAL('SEQ_PLANIFNOD_CODPLANIFNOD') INTO vcodplanifnod;

          INSERT INTO planifnod(codplanifnod, codplanifprod1, codplanifprod, nodoriginal, codobiect, pozitie, nivel, tip, versiune, indexparinte, necesar, cant, cantmatreteta, cantprodreteta)
          VALUES(vcodplanifnod, v_rec.codplanifprod1, vcodplanifprod, 0, v_rec.codobiect, 0, 0, 1, 0, '.00', v_rec.necesar, v_rec.necesar, 0, 0);

          SELECT NEXTVAL('SEQ_PLANIFNOD_CODPLANIFNOD') INTO vcodplanifnodorig;

          INSERT INTO planifnod(codplanifnod, codplanifprod1, codplanifprod, nodoriginal, codobiect, pozitie, nivel, tip, versiune, indexparinte, necesar, cant, cantmatreteta, cantprodreteta, codreteta)
          VALUES(vcodplanifnodorig, v_rec.codplanifprod1, vcodplanifprod, vcodplanifnod, v_rec.codobiect, 0, 0, 1, 1, '.00', v_rec.necesar, v_rec.necesar, 0, 0, v_xxx.codprodcomp);

          PERFORM pkg_planifprod_BagaMateriale( vcodplanifnodorig, v_rec.codobiect, v_rec.necesar, v_xxx.codprodcomp, 1, v_rec.codplanifprod1, vCodPlanifProd, '.00');
        END LOOP;
      END IF;
    END IF;
  END LOOP;

  SELECT count( *) INTO Rez FROM planifnod WHERE codplanifprod = vcodplanifprod and  tip = 3 and  versiune = 1 and  COALESCE( codreteta, 0) = 0;
  IF  Rez = 0 THEN
    UPDATE planifprod SET operat = 1 WHERE codplanifprod = vcodplanifprod;
  END IF;

  WME_Result :=  Rez;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprod_getcarnetdoc_i</obj_name>
  <obj_hashval>dd87746496274551b2bdb237d720c87e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprod_getcarnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANIFPROD.CARNETDOC_I', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprod_getct_monitor</obj_name>
  <obj_hashval>c5de914e9311a353df7634e83bed44b7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprod_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_PLANIFPROD.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_45';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprod_getnrdoc_i</obj_name>
  <obj_hashval>b7a8f73d448dd269bb7154788b5425c6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprod_getnrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANIFPROD.NRDOC_I', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprod_nrdoc_i</obj_name>
  <obj_hashval>cdeae4011b973555cf22bad60ce47207</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprod_nrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANIFPROD.NRDOC_I', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprod_setct_monitor</obj_name>
  <obj_hashval>8bd466d999a6522cbf1f863afebc493a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprod_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANIFPROD.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprod_setnrdoc_i</obj_name>
  <obj_hashval>6689b7e47882b08d13ad981c08f286d6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprod_setnrdoc_i(anrdoc numeric, acarnet numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANIFPROD.CARNETDOC_I',to_char(ACARNET,'999999999999999999'),false);
perform set_config('PKG_PLANIFPROD.NRDOC_I',to_char(ANRDOC,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprod_sp_deleterecord</obj_name>
  <obj_hashval>37465ccf4ee11c83f48199faf3693058</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprod_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDataDoc   date;
  aDoc       varchar;
  ACARNETDOC numeric;
  ANRDOC     numeric;
BEGIN
  --Florin 01.06.2023 - monitor
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_planifprod_setct_monitor('MON_45');
  SELECT DATE_TRUNC('DAY', DATE_TRUNC('DAY', to_date( AN, 'yyyy'), 'yyyy'), 'iw') + (  Saptamana - 1)  * 7, SAPTAMANA, carnetdoc, nrdoc
  INTO aDATADOC, ADOC, acarnetdoc, anrdoc
  FROM PLANIFPROD WHERE CODPLANIFPROD = RECID;

  IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_PLANIFPROD.CT_MONITOR', true))))
  THEN
    PERFORM pkg_userfirme_postlogcucommit( 'PLANIFPROD', (current_setting('PKG_GLOBALS.USERNAME', true)), 'S', RECID, (current_setting('PKG_GLOBALS.FIRMANAME', true)), (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL)), aDataDoc, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  PERFORM PKG_PLANIFPROD_SP_LOCKRECORD( RecId);
  DELETE FROM PLANIFNOD   WHERE CodPLANIFPROD = RecId;
  DELETE FROM PLANIFPROD1 WHERE CodPLANIFPROD = RecId;
  DELETE FROM PLANIFPROD  WHERE CodPLANIFPROD = RecId;

  IF  aCARNETDOC &lt;&gt; 0 THEN
    PERFORM PKG_CARNETEDOC_RELEASENUMARDOC( aCARNETDOC, aNRDOC);
    PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE( aCARNETDOC);
  END IF;

  PERFORM NotifyModif( 2, RecId, 'PLANIFPROD');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprod_sp_lockrecord</obj_name>
  <obj_hashval>a0f7cdef4b78fbb792be401732e550e5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprod_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodPlanifProd INTO Tmp FROM PLANIFPROD WHERE CodPlanifProd = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_block_sectie</obj_name>
  <obj_hashval>b9f3e4999c533c4887b02a950cbf032f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_block_sectie(auserid numeric, acodgest numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM planiflock WHERE userid = aUserId;
  INSERT INTO planiflock(userid, codgest) VALUES(aUserId, aCodGest);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_clearsalvare</obj_name>
  <obj_hashval>0e18a7323b7dff4ff82279277b2080a1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_clearsalvare(aanluna numeric, acodgest numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM PLANIFPRODLUN WHERE ANLUNA = AANLUNA AND  CODGEST = ACODGEST;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_cleartables</obj_name>
  <obj_hashval>a59041d6d4050a7633f4c98ac5360ff6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_cleartables()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  VUSERID numeric;
begin
  VUSERID := (SELECT PKG_GLOBALS_GETUSERID.WME_RESULT FROM PKG_GLOBALS_GETUSERID(NULL,NULL));
  DELETE FROM TMP_CMD       WHERE USERID = VUSERID;
  DELETE FROM TMP_CMD_PLUNA WHERE USERID = VUSERID;
  DELETE FROM TMP_PLUNA     WHERE USERID = VUSERID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_getfirstdateofweek</obj_name>
  <obj_hashval>603d2322add0b0951806f68c4293b125</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_getfirstdateofweek(INOUT wme_result character varying, INOUT asaptamana numeric, INOUT aan numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  to_char( (SELECT iso_week_to_date.WME_RESULT FROM iso_week_to_date(NULL, aAn, aSaptamana)), 'dd.mm.yyyy');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_getvallcls</obj_name>
  <obj_hashval>e773860fe9355e124cf14c9592f7c6f4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_getvallcls(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANIFPRODLUN.vAllCls', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_getvallgest</obj_name>
  <obj_hashval>1c82937ff8c3d35303a8ef4bec286a7c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_getvallgest(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANIFPRODLUN.vAllGest', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_getvallioart</obj_name>
  <obj_hashval>685b02b75ded1e4705a87e5dce168311</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_getvallioart(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANIFPRODLUN.vAllIOArt', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_getvanlunafin</obj_name>
  <obj_hashval>30eb42a992e1db886f500a75bd349ff5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_getvanlunafin(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANIFPRODLUN.vAnLunaFin', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_getvanlunaini</obj_name>
  <obj_hashval>61bf6924976be1b85cbf2b4cd0cec175</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_getvanlunaini(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANIFPRODLUN.vAnLunaIni', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_getvcodcatpret</obj_name>
  <obj_hashval>bf75877093b7b27f370130bd5fe296fa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_getvcodcatpret(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANIFPRODLUN.vCodCatPret', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_getvcodgest</obj_name>
  <obj_hashval>77227a52aa7262c966709fa37a028ee0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_getvcodgest(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANIFPRODLUN.vCodGest', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_getvcodmoneda</obj_name>
  <obj_hashval>ef622b913ea9e9fba7327618235a73ef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_getvcodmoneda(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANIFPRODLUN.vCodMoneda', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_getvsaptamana</obj_name>
  <obj_hashval>8906b93f86618f11c6cf454714727c82</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_getvsaptamana(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANIFPRODLUN.vSaptamana', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_insertsalvare</obj_name>
  <obj_hashval>d232dca8b0ec6756757c4d5542fe05b3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_insertsalvare(aanluna numeric, acodobiect numeric, pl1 numeric, pl2 numeric, pl3 numeric, pl4 numeric, pl5 numeric, pl numeric, lansare numeric, acodgest numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM PLANIFPRODLUN WHERE ANLUNA = AANLUNA AND  CODOBIECT = ACODOBIECT;
  INSERT INTO PLANIFPRODLUN(CODOBIECT, PLWEEK1, PLWEEK2, PLWEEK3, PLWEEK4, PLWEEK5, ANLUNA, PLANIFICAT, LANSARE, CODGEST)
  VALUES(ACODOBIECT, PL1, PL2, PL3, PL4, PL5, AANLUNA, PL, LANSARE, ACODGEST);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_setparams</obj_name>
  <obj_hashval>e77f2c8a4c4bab339b3ee22f3df9a228</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_setparams(asaptamana numeric, acodgest numeric, acodcatpret numeric, aallcls numeric, aallgest numeric, aallioart numeric, acodmoneda numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_PLANIFPRODLUN.vSaptamana' ,to_char(aSaptamana ,'999999999999999999'),false);
  perform set_config('PKG_PLANIFPRODLUN.vCodGest'   ,to_char(aCodGest   ,'999999999999999999'),false);
  perform set_config('PKG_PLANIFPRODLUN.vCodCatPret',to_char(aCodCatPret,'999999999999999999'),false);
  perform set_config('PKG_PLANIFPRODLUN.vAllCls'    ,to_char(aAllCls    ,'999999999999999999'),false);
  perform set_config('PKG_PLANIFPRODLUN.vAllGest'   ,to_char(aAllGest   ,'999999999999999999'),false);
  perform set_config('PKG_PLANIFPRODLUN.vAllIOArt'  ,to_char(aAllIOArt  ,'999999999999999999'),false);
  perform set_config('PKG_PLANIFPRODLUN.vCodMoneda' ,to_char(aCodMoneda ,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_setparamsvanz</obj_name>
  <obj_hashval>df14c1d4dc3da98c315b066e25ccc296</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_setparamsvanz(aanlunaini numeric, aanlunafin numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANIFPRODLUN.vAnLunaIni',to_char(aAnLunaIni,'999999999999999999'),false);
perform set_config('PKG_PLANIFPRODLUN.vAnLunaFin',to_char(aAnLunaFin,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_setvanlunafin</obj_name>
  <obj_hashval>f81ea777f2d56e69109e4e04540a984d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_setvanlunafin(avanlunafin numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANIFPRODLUN.vAnLunaFin',to_char(avAnLunaFin,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_setvanlunaini</obj_name>
  <obj_hashval>8b59cee75d0a9f33b2557daf451c4dee</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_setvanlunaini(avanlunaini numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANIFPRODLUN.vAnLunaIni',to_char(avAnLunaIni,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_setvcodcatpret</obj_name>
  <obj_hashval>3b6aa5c774cb99c0c9e7053733ad67aa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_setvcodcatpret(avcodcatpret numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANIFPRODLUN.vCodCatPret',to_char(avCodCatPret,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_setvcodgest</obj_name>
  <obj_hashval>1ddc59e02e966917aad4498684d929d7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_setvcodgest(avcodgest numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANIFPRODLUN.vCodGest',to_char(avCodGest,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_setvcodmoneda</obj_name>
  <obj_hashval>f43268c15f8c1b806c6e711a0b72aa7f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_setvcodmoneda(avcodmoneda numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANIFPRODLUN.vCodMoneda',to_char(avCodMoneda,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_setvsaptamana</obj_name>
  <obj_hashval>19cfd5afc20971b8922ff3b3c50a9de8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_setvsaptamana(avsaptamana numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANIFPRODLUN.vSaptamana',to_char(avSaptamana,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_umple_tmp_cmd</obj_name>
  <obj_hashval>1aeea9a8c75fa9851666657862b13794</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_umple_tmp_cmd()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  VUSERID numeric;
begin
  VUSERID := (SELECT PKG_GLOBALS_GETUSERID.WME_RESULT FROM PKG_GLOBALS_GETUSERID (NULL,NULL));
  DELETE FROM TMP_CMD WHERE USERID = VUSERID;

  INSERT INTO TMP_CMD (CODOBIECT, CANTC, USERID)
  SELECT C1.CODCOMANDA1, SUM (L.CANT) CANT, VUSERID
  FROM TMP_PLUNA        TL
    INNER JOIN COMANDA1 C1 ON C1.CODOBIECT      = TL.CODOBIECT
    INNER JOIN COMANDA  C  ON C.CODCOMANDA      = C1.CODCOMANDA
    INNER JOIN CMDLINK  L  ON L.CODLINIECOMANDA = C1.CODCOMANDA1
  WHERE
    C1.RESTACCEPTAT &gt; 0
    AND C.TIPDOC = 18
    AND C.ANULAT = 0
    AND TL.USERID = VUSERID
  GROUP BY
    C1.CODCOMANDA1;

  DELETE FROM TMP_CMD_PLUNA WHERE USERID = VUSERID;

  INSERT INTO TMP_CMD_PLUNA (CODCOMANDA1, CANT1, CANT2, CANT3, CANT4, TIP, USERID, CODOBIECT)
  SELECT C1.CODCOMANDA1, C1.CANTACCEPTAT, COALESCE (LANSATE.CANTC, 0) , C1.RESTACCEPTAT, C1.CANTACCEPTAT - COALESCE (LANSATE.CANTC, 0) , 18, VUSERID, C1.CODOBIECT
  FROM TMP_PLUNA        TL
    INNER JOIN COMANDA1 C1      ON C1.CODOBIECT = TL.CODOBIECT
    INNER JOIN COMANDA  C       ON C.CODCOMANDA = C1.CODCOMANDA
    LEFT JOIN TMP_CMD   LANSATE ON LANSATE.CODOBIECT = C1.CODCOMANDA1 AND LANSATE.USERID = VUSERID
  WHERE
    C1.RESTACCEPTAT &gt; 0
    AND C.TIPDOC = 18
    AND C.ANULAT = 0
    AND TL.USERID = VUSERID;

  IF TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.vCodGest', true)) ,'999999999999999999') &gt; 0 THEN
    DELETE FROM TMP_CMD WHERE USERID = VUSERID;

    INSERT INTO TMP_CMD (CODOBIECT, CANTC, USERID, TIP)
    SELECT C1.CODCOMANDA1, SUM (L.CANT) CANT, VUSERID, TO_CHAR (PF1.CODPROGRAMF1,'9999999999')
    FROM TMP_PLUNA            TL
      INNER JOIN COMANDA1     C1   ON C1.CODOBIECT       = TL.CODOBIECT
      INNER JOIN COMANDA      C    ON C.CODCOMANDA       = C1.CODCOMANDA
      INNER JOIN CMDPRODMAT   PROD ON PROD.CODCOMANDA1   = C1.CODCOMANDA1
      INNER JOIN INTRPRODLINK L    ON PROD.CODCMDPRODMAT = L.CODLINIECOMANDA
      INNER JOIN PROGRAMF1    PF1  ON PF1.CODPROGRAMF1   = L.CODPROGRAMF1
      INNER JOIN INTRARI1     I1   ON L.CODINTR1         = I1.CODINTR1
      INNER JOIN INTRARI      I    ON I.CODINTR          = I1.CODINTR
    WHERE
      C.TIPDOC = 53
      AND C.ANULAT = 0
      AND I.ANULAT = 0
      AND C.CODGEST = TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.VCODGEST', true)) ,'999999999999999999')
      AND TL.USERID = VUSERID
    GROUP BY
      C1.CODCOMANDA1, PF1.CODPROGRAMF1;

    INSERT INTO TMP_CMD_PLUNA (CANT1, CANT2, CANT3, TERMEN, TIP, CODPROGRAMF1, USERID, WEEK, CODOBIECT)
    SELECT PF1.CANTPROGRAMAT, COALESCE (PREDATE.CANTC, 0) , PF1.CANTPROGRAMAT - COALESCE (PREDATE.CANTC, 0) , PF1.TERMEN,
      53, PF1.CODPROGRAMF1, VUSERID, (TO_CHAR (PF1.TERMEN, 'IW'))::numeric , C1.CODOBIECT
    FROM TMP_PLUNA          TL
      INNER JOIN CMDPRODMAT PROD    ON TL.CODOBIECT      = PROD.CODOBIECT AND PROD.TIP = 0
      INNER JOIN COMANDA1   C1      ON PROD.CODCOMANDA1  = C1.CODCOMANDA1
      INNER JOIN COMANDA    C       ON C.CODCOMANDA      = C1.CODCOMANDA
      INNER JOIN PROGRAMF1  PF1     ON PF1.CODCOMANDA1   = C1.CODCOMANDA1
      LEFT JOIN TMP_CMD     PREDATE ON PREDATE.CODOBIECT = C1.CODCOMANDA1 and PREDATE.TIP::numeric = PF1.CODPROGRAMF1 AND PREDATE.USERID = VUSERID
    WHERE
      PROD.REST &gt; 0
      AND C.CODGEST = TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.VCODGEST', true)) ,'999999999999999999')
      AND C.TIPDOC = 53
      AND C.ANULAT = 0
      AND TL.USERID = VUSERID;

    DELETE FROM TMP_CMD WHERE USERID = VUSERID;

    INSERT INTO TMP_CMD (CODOBIECT, CANTC, USERID)
    SELECT C1.CODCOMANDA1, SUM (L.CANT) CANT, VUSERID
    FROM TMP_PLUNA                    TL
      INNER JOIN COMANDA1             C1   ON C1.CODOBIECT       = TL.CODOBIECT
      INNER JOIN COMANDA              C    ON C.CODCOMANDA       = C1.CODCOMANDA
      INNER JOIN CMDPRODMAT           PROD ON PROD.CODCOMANDA1   = C1.CODCOMANDA1
      INNER JOIN INTRPRODLINK         L    ON PROD.CODCMDPRODMAT = L.CODLINIECOMANDA
      INNER JOIN INTRARI1             I1   ON L.CODINTR1         = I1.CODINTR1
      INNER JOIN INTRARI              I    ON I.CODINTR          = I1.CODINTR
    WHERE
      C.TIPDOC = 53
      AND C.ANULAT = 0
      AND I.ANULAT = 0
      AND C.CODGEST = TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.VCODGEST', true)) ,'999999999999999999')
      AND TL.USERID = VUSERID
      AND COALESCE (L.CODPROGRAMF1, 0) = 0
    GROUP BY
      C1.CODCOMANDA1;

    INSERT INTO TMP_CMD_PLUNA (CODCOMANDA1, CANT1, CANT2, CANT3, TERMEN, TIP, USERID, WEEK, CODOBIECT)
    SELECT C1.CODCOMANDA1,
           C1.CANTACCEPTAT - (SELECT COALESCE (SUM (PF1.CANTPROGRAMAT) , 0) FROM PROGRAMF1 PF1 WHERE PF1.CODCOMANDA1 = C1.CODCOMANDA1) ,
           COALESCE (PREDATE.CANTC, 0) ,
           C1.CANTACCEPTAT - (SELECT COALESCE (SUM (PF1.CANTPROGRAMAT) , 0) FROM PROGRAMF1 PF1 WHERE PF1.CODCOMANDA1 = C1.CODCOMANDA1) - COALESCE (PREDATE.CANTC, 0) ,
           C1.TERMEN, 53, VUSERID, (TO_CHAR (C1.TERMEN, 'IW'))::numeric , C1.CODOBIECT
    FROM TMP_PLUNA          TL
      INNER JOIN CMDPRODMAT PROD    ON TL.CODOBIECT      = PROD.CODOBIECT AND PROD.TIP = 0
      INNER JOIN COMANDA1   C1      ON PROD.CODCOMANDA1  = C1.CODCOMANDA1
      INNER JOIN COMANDA    C       ON C.CODCOMANDA      = C1.CODCOMANDA
      LEFT  JOIN TMP_CMD    PREDATE ON PREDATE.CODOBIECT = C1.CODCOMANDA1 AND PREDATE.USERID = VUSERID
    WHERE
      PROD.REST &gt; 0
      AND C.CODGEST = TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.VCODGEST', true)) ,'999999999999999999')
      AND C.TIPDOC = 53
      AND C.ANULAT = 0
      AND TL.USERID = VUSERID;

    DELETE FROM TMP_CMD_PLUNA WHERE USERID = VUSERID AND TIP = 53 AND CODPROGRAMF1 IS NULL AND CANT1 = 0;

  ELSE
    DELETE FROM TMP_CMD WHERE USERID = VUSERID;

    INSERT INTO TMP_CMD (CODOBIECT, CANTC, USERID, TIP)
    SELECT C1.CODCOMANDA1, SUM (L.CANT) CANT, VUSERID, TO_CHAR (PF1.CODPROGRAMF1,'9999999999')
    FROM TMP_PLUNA                    TL
      INNER JOIN COMANDA1             C1   ON C1.CODOBIECT       = TL.CODOBIECT
      INNER JOIN COMANDA              C    ON C.CODCOMANDA       = C1.CODCOMANDA
      INNER JOIN CMDPRODMAT           PROD ON PROD.CODCOMANDA1   = C1.CODCOMANDA1
      INNER JOIN INTRPRODLINK         L    ON PROD.CODCMDPRODMAT = L.CODLINIECOMANDA
      INNER JOIN PROGRAMF1            PF1  ON PF1.CODPROGRAMF1   = L.CODPROGRAMF1
      INNER JOIN INTRARI1             I1   ON L.CODINTR1         = I1.CODINTR1
      INNER JOIN INTRARI              I    ON I.CODINTR          = I1.CODINTR
    WHERE
      C.TIPDOC = 53
      AND C.ANULAT = 0
      AND I.ANULAT = 0
      AND TL.USERID = VUSERID
    GROUP BY
      C1.CODCOMANDA1, PF1.CODPROGRAMF1;

    INSERT INTO TMP_CMD_PLUNA (CANT1, CANT2, CANT3, TERMEN, TIP, CODPROGRAMF1, USERID, WEEK, CODOBIECT)
    SELECT PF1.CANTPROGRAMAT, COALESCE (PREDATE.CANTC, 0) , PF1.CANTPROGRAMAT - COALESCE (PREDATE.CANTC, 0) , PF1.TERMEN,
           53, PF1.CODPROGRAMF1, VUSERID,  (TO_CHAR (PF1.TERMEN, 'IW'))::numeric, C1.CODOBIECT
    FROM TMP_PLUNA          TL
      INNER JOIN CMDPRODMAT PROD    ON TL.CODOBIECT      = PROD.CODOBIECT AND PROD.TIP = 0
      INNER JOIN COMANDA1   C1      ON PROD.CODCOMANDA1  = C1.CODCOMANDA1
      INNER JOIN COMANDA    C       ON C.CODCOMANDA      = C1.CODCOMANDA
      INNER JOIN PROGRAMF1  PF1     ON PF1.CODCOMANDA1   = C1.CODCOMANDA1
      LEFT JOIN TMP_CMD     PREDATE ON PREDATE.CODOBIECT = C1.CODCOMANDA1 AND PREDATE.TIP::numeric = PF1.CODPROGRAMF1 AND PREDATE.USERID = VUSERID
    WHERE
      PROD.REST &gt; 0
      AND C.TIPDOC = 53
      AND C.ANULAT = 0
      AND TL.USERID = VUSERID;

    DELETE FROM TMP_CMD WHERE USERID = VUSERID;

    INSERT INTO TMP_CMD (CODOBIECT, CANTC, USERID)
    SELECT C1.CODCOMANDA1, SUM (L.CANT) CANT, VUSERID
    FROM TMP_PLUNA                    TL
      INNER JOIN COMANDA1             C1   ON C1.CODOBIECT       = TL.CODOBIECT
      INNER JOIN COMANDA              C    ON C.CODCOMANDA       = C1.CODCOMANDA
      INNER JOIN CMDPRODMAT           PROD ON PROD.CODCOMANDA1   = C1.CODCOMANDA1
      INNER JOIN INTRPRODLINK         L    ON PROD.CODCMDPRODMAT = L.CODLINIECOMANDA
      INNER JOIN INTRARI1             I1   ON L.CODINTR1         = I1.CODINTR1
      INNER JOIN INTRARI              I    ON I.CODINTR          = I1.CODINTR
    WHERE
      C.TIPDOC = 53
      AND C.ANULAT = 0
      AND I.ANULAT = 0
      AND TL.USERID = VUSERID
      AND COALESCE (L.CODPROGRAMF1, 0) = 0
    GROUP BY
      C1.CODCOMANDA1;

    INSERT INTO TMP_CMD_PLUNA (CODCOMANDA1, CANT1, CANT2, CANT3, TERMEN, TIP, USERID, WEEK, CODOBIECT)
    SELECT C1.CODCOMANDA1,
           C1.CANTACCEPTAT - (SELECT COALESCE (SUM (PF1.CANTPROGRAMAT) , 0) FROM PROGRAMF1 PF1 WHERE PF1.CODCOMANDA1 = C1.CODCOMANDA1) ,
           COALESCE (PREDATE.CANTC, 0) ,
           C1.CANTACCEPTAT - (SELECT COALESCE (SUM (PF1.CANTPROGRAMAT) , 0) FROM PROGRAMF1 PF1 WHERE PF1.CODCOMANDA1 = C1.CODCOMANDA1) - COALESCE (PREDATE.CANTC, 0) ,
           C1.TERMEN, 53, VUSERID, (TO_CHAR (C1.TERMEN, 'IW'))::numeric , C1.CODOBIECT
    FROM TMP_PLUNA          TL
      INNER JOIN CMDPRODMAT PROD    ON TL.CODOBIECT      = PROD.CODOBIECT AND PROD.TIP = 0
      INNER JOIN COMANDA1   C1      ON PROD.CODCOMANDA1  = C1.CODCOMANDA1
      INNER JOIN COMANDA    C       ON C.CODCOMANDA      = C1.CODCOMANDA
      LEFT JOIN TMP_CMD     PREDATE ON PREDATE.CODOBIECT = C1.CODCOMANDA1 AND PREDATE.USERID = VUSERID
    WHERE
      PROD.REST &gt; 0
      AND C.TIPDOC = 53
      AND C.ANULAT = 0
      AND TL.USERID = VUSERID;

    DELETE FROM TMP_CMD_PLUNA WHERE USERID = VUSERID AND TIP = 53 AND CODPROGRAMF1 IS NULL AND CANT1 = 0;
  END IF;

  DELETE FROM TMP_CMD_PLUNA WHERE USERID = VUSERID AND CANT3 &lt;= 0;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_unblock</obj_name>
  <obj_hashval>8c836e3920d7bae83e7a0630e7dc40f0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_unblock(auserid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM planiflock WHERE userid = aUserId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_update_lansare</obj_name>
  <obj_hashval>7ae71f6d1c8f526b3c64f11a21cdab9e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_update_lansare(aanluna numeric, acodobiect numeric, alansare numeric, acodgest numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  ACOUNT numeric;
begin
  SELECT count( *) INTO ACOUNT FROM planifprodlun WHERE anluna = aanluna and  codobiect = acodobiect and  codgest = acodgest;
  IF  acount &gt; 0 THEN
    UPDATE PLANIFPRODLUN SET LANSARE = ALANSARE WHERE anluna = aanluna and  codobiect = acodobiect and  codgest = acodgest;
  ELSE
    INSERT INTO PLANIFPRODLUN(CODOBIECT, ANLUNA, LANSARE, CODGEST)
    VALUES(ACODOBIECT, AANLUNA, ALANSARE, ACODGEST);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_update_planif</obj_name>
  <obj_hashval>834525d1cd43cf3cbf0066b3b8d2aea1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_update_planif(aanluna numeric, acodobiect numeric, pl1 numeric, pl2 numeric, pl3 numeric, pl4 numeric, pl5 numeric, pl numeric, acodgest numeric, cuupd boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  ACOUNT numeric;
begin
  SELECT count( *) INTO ACOUNT FROM planifprodlun WHERE anluna = aanluna and  codobiect = acodobiect and  codgest = acodgest;
  IF  acount &gt; 0 THEN
    IF CuUPD THEN
      UPDATE PLANIFPRODLUN
      SET
      PLWEEK1    = PL1,
      PLWEEK2    = PL2,
      PLWEEK3    = PL3,
      PLWEEK4    = PL4,
      PLWEEK5    = PL5,
      PLANIFICAT = PL
      WHERE
       anluna = aanluna and  codobiect = acodobiect and  codgest = acodgest;
    END IF;
  ELSE
    INSERT INTO PLANIFPRODLUN(CODOBIECT, ANLUNA, PLWEEK1, PLWEEK2, PLWEEK3, PLWEEK4, PLWEEK5, PLANIFICAT, CODGEST)
    VALUES(ACODOBIECT, AANLUNA, PL1, PL2, PL3, PL4, PL5, PL, ACODGEST);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_updatenext</obj_name>
  <obj_hashval>4cc6c389b01ac36aaf14b4306960788f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_updatenext(acodobiect numeric, aanluna numeric, acodgest numeric, aplanificat numeric, aplweek1 numeric, aplweek2 numeric, aplweek3 numeric, aplweek4 numeric, aplweek5 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  UPDATE planifprodlun
  SET
  planificat = aPlanificat,
  plweek1 = aplweek1,
  plweek2 = aplweek2,
  plweek3 = aplweek3,
  plweek4 = aplweek4,
  plweek5 = aplweek5
  WHERE
   codgest = acodgest and  codobiect = acodobiect and  anluna = aanluna;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_updatevanz</obj_name>
  <obj_hashval>08e895ca3b05921bba8fcfb31a569a66</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_updatevanz(arefresh numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V       RECORD;
  vUserID numeric;
begin
  vUserID := (SELECT PKG_GLOBALS_GETUSERID.WME_RESULT FROM PKG_GLOBALS_GETUSERID(NULL,NULL));
  IF  aRefresh &gt; 0 THEN
    UPDATE tmp_pluna SET mediev = 0;
  END IF;

  FOR V IN (SELECT TL.CODOBIECT CODOBIECT, SUM( L1.CANT) REST
            FROM TMP_PLUNA TL
                INNER JOIN IESIRI1 I1 ON  I1.CODOBIECT = TL.CODOBIECT
                INNER JOIN LIVR1   L1 ON  L1.CODIES1   = I1.CODIES1
                INNER JOIN LIVR    L  ON  L1.CODLIVR   = L.CODLIVR
                INNER JOIN IESIRI  I  ON  I1.CODIES    = I.CODIES AND  L.CODIES = I.CODIES
            WHERE I.ANULAT = 0
              AND I.AN * 12 + I.LUNA BETWEEN TO_NUMBER((current_setting('PKG_PLANIFPRODLUN.vAnLunaIni', true)),'999999999999999999') AND TO_NUMBER((current_setting('PKG_PLANIFPRODLUN.vAnLunaFin', true)),'999999999999999999')
              AND I.TIPDOC IN (19, 20) AND  TL.USERID = VUSERID
            GROUP BY TL.CODOBIECT
  )
  LOOP
    UPDATE  TMP_PLUNA TMP SET MEDIEV = V.REST WHERE TMP.CODOBIECT = V.CODOBIECT and  TMP.USERID = VUSERID;
  END LOOP;

  UPDATE TMP_PLUNA
  SET
  MEDIEV = MEDIEV / trunc( TO_NUMBER((current_setting('PKG_PLANIFPRODLUN.vAnLunaFin', true)),'999999999999999999') - TO_NUMBER((current_setting('PKG_PLANIFPRODLUN.vAnLunaIni', true)),'999999999999999999') + 1);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_vcodcatpret</obj_name>
  <obj_hashval>6166ebdf71e92077a3fb572b6e5e9735</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_vcodcatpret(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANIFPRODLUN.vCodCatPret', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_vcodmoneda</obj_name>
  <obj_hashval>3d69d0e7beb53a6d0ab51663969233b4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_vcodmoneda(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANIFPRODLUN.vCodMoneda', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_vsaptamana</obj_name>
  <obj_hashval>1e967ffcd4299b49decc594beca667ed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_vsaptamana(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANIFPRODLUN.vSaptamana', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plati_carnetdoc_i</obj_name>
  <obj_hashval>2e111f8e7782eaf2c6b97581583a5f11</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plati_carnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PLATI.CARNETDOC_I', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plati_checkaddcontdest</obj_name>
  <obj_hashval>330b146201b220ef148d3b0b7a685eb4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plati_checkaddcontdest(acodpart numeric, acontdest character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCONT    numeric;
  aCODBANK numeric;
  NR       numeric;
begin
  BEGIN
    SELECT CODPARTB INTO aCONT FROM NPARTB WHERE CONTBANCA = aCONTDEST AND  CODPART = aCODPART;
  EXCEPTION WHEN OTHERS THEN
    aCONT := 0;
  END;

  IF  aCONT = 0 THEN
    BEGIN
      SELECT CODBANK INTO aCODBANK FROM NBANK WHERE UPPER(CODBNR) = UPPER(SUBSTR(Replace(aCONTDEST, ' ', ''), 5, 4));
    EXCEPTION WHEN OTHERS THEN
      aCODBANK := 0;
    END;

    IF  aCODBANK &lt;&gt; 0 THEN
      INSERT INTO NPARTB(CODPARTB, CODPART, CODBANK, CONTBANCA)
      VALUES(NEXTVAL('SEQ_NPARTB_CODPARTB'), aCODPART, aCODBANK, aCONTDEST);

      SELECT COUNT(*) INTO NR FROM NPARTB WHERE CODPART = aCODPART;
      IF  NR = 0 THEN
        UPDATE NPARTB SET IMPLICIT = 1 WHERE CODPART = aCODPART;
      END IF;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plati_getcarnetdoc_i</obj_name>
  <obj_hashval>02b8e1c871665150ff1bf87373a0e391</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plati_getcarnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PLATI.CARNETDOC_I', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plati_getnrdoc_i</obj_name>
  <obj_hashval>a69ebe73e8ea077a6a845e5e180d3892</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plati_getnrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PLATI.NRDOC_I', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plati_getsoldbuget</obj_name>
  <obj_hashval>9e688868ead9934552ba273b70637aa4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plati_getsoldbuget(INOUT wme_result numeric, INOUT acodanalizanod numeric, INOUT aan numeric, INOUT aluna numeric, INOUT acodplata numeric, INOUT atipdoc numeric DEFAULT 0)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aSold       numeric;
  x           numeric;
  y           numeric;
  aLuna1      numeric;
  aLuna2      numeric;
  aTipSold    numeric;
  aCodAnaliza numeric;
begin
  IF  aTipDoc = 1 THEN
    BEGIN
      SELECT codanaliza INTO aCodAnaliza FROM analizanod WHERE codanalizanod = aCodAnalizaNod;
      EXECUTE
      'DO LANGUAGE PLPGSQL $$ ' ||
      'BEGIN' || coalesce(Chr(10),'') ||
      '  DELETE FROM TMP_BUGETANALIZA;' || coalesce(Chr(10),'') ||
      '  PERFORM PKG_ANALIZA_GetBugete( ' || coalesce(aCodAnaliza::varchar ,'') || ', ' || coalesce(current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric,'') || ', 1, 12, 9, 0 );' || coalesce(Chr(10),'') ||
      '  DELETE FROM TMP_BUGETANALIZA WHERE CODANALIZANOD IN (SELECT DISTINCT NODPARINTE FROM ANALIZANOD WHERE CODANALIZA = ' || coalesce(aCodAnaliza::varchar ,'') || ');' || coalesce(Chr(10),'') ||
      'END $$;';
    EXCEPTION WHEN others THEN
      aCodAnaliza := 0;
    END;

    BEGIN
      SELECT (SELECT sum(CASE WHEN  codcentru = 1 THEN B1 + B2 + B3 + B4 + B5 + B6 + B7 + B8 + B9 + B10 + B11 + B12 ELSE 0 END )
              FROM TMP_BUGETANALIZA WHERE codanalizanod = aCodanalizanod
             )
             -
             (SELECT sum(CASE WHEN  codcentru = 4 THEN B1 + B2 + B3 + B4 + B5 + B6 + B7 + B8 + B9 + B10 + B11 + B12 ELSE 0 END )
              FROM TMP_BUGETANALIZA WHERE codanalizanod = aCodanalizanod
             )
      INTO aSold;
    EXCEPTION WHEN others THEN
      aSold := 0;
    END;
  ELSE
    BEGIN
      BEGIN
        SELECT COALESCE((fnc_GetValConstantaLucru('TipValoriBuget'))::numeric, 1)
        INTO aTipSold;
      EXCEPTION WHEN OTHERS THEN
        aTipSold := 1;
      END;

      IF  aTipSold = 1 THEN
        aLuna1 := aLuna;
        aLuna2 := aLuna;
      ELSIF aTipSold = 2 THEN
        aLuna1 := aLuna;
        aLuna2 := Trunc((  aLuna + 2)  / 3) * 3;
        aLuna1 := aLuna2 - 2;
      END IF;

      SELECT Sum(COALESCE(Buget, 0)) INTO aSold
      FROM (SELECT BUGET FROM BUGETANALIZA BA WHERE BA.AN = aAn AND BA.Luna BETWEEN aLuna1 AND aLuna2 AND  BA.CodAnalizaNod = aCodAnalizaNod AND  BA.Tip = 9
            union ALL
            SELECT R1.VCredit BUGET
            FROM Bugetrectif1 R1 INNER JOIN Bugetrectif R ON  R.Codbugetrectif = R1.CODBUGETRECTIF
            WHERE R.AN = aAn AND R.LunaDest BETWEEN aLuna1 AND aLuna2 and  R1.CodNodDest = aCodAnalizaNod and  COALESCE(R1.VCredit, 0) &lt;&gt; 0
            union ALL
            SELECT -R1.VCredit BUGET
            FROM Bugetrectif1 R1 INNER JOIN Bugetrectif R ON  R.Codbugetrectif = R1.CODBUGETRECTIF
            WHERE R.AN = aAn AND R.LunaSursa BETWEEN aLuna1 AND aLuna2 AND  R1.CodNodSursa = aCodAnalizaNod and  COALESCE(R1.VCredit, 0) &lt;&gt; 0
            union ALL
            SELECT -p1.VALOARE BUGET
            FROM Plati1 P1 INNER JOIN Plati P ON  P.CodPlata = P1.CodPlata
            WHERE P.An = aAn AND P.Luna BETWEEN aLuna1 AND aLuna2 and  P.TipDoc = 1 AND  P1.CodAnalizaNodx = aCodAnalizaNod and P1.CodObligPIF IN (0, 1, 2) and (   aCodPlata = 0 or  P.CodPlata &lt;&gt; aCodPlata)
            union ALL
            SELECT -P1.Valoare BUGET
            FROM ObligPIF O
                INNER JOIN Plati1 P1 ON  P1.CodObligPIF = O.CodObligPIF
                INNER JOIN Plati P ON  P.Codplata = P1.Codplata
            WHERE P.An = aAn AND P.Luna BETWEEN aLuna1 AND aLuna2 and  P.TipDoc = 1 AND  O.CodAnalizaNod = aCodAnalizaNod and (   NOT P1.CodObligPIF IN (0, 1, 2))  and (   aCodPlata = 0 or  P.CodPlata &lt;&gt; aCodPlata)
            union ALL
            SELECT -R1.VPLATAAPROB BUGET
            FROM Bugetrectif1 R1 INNER JOIN Bugetrectif R ON  R.Codbugetrectif = R1.CODBUGETRECTIF
            WHERE R.AN = aAn AND R.LunaDest BETWEEN aLuna1 AND aLuna2 and  R1.CodNodDest = aCodAnalizaNod and  COALESCE(R1.VPLATAAPROB, 0) &lt;&gt; 0
            union ALL
            SELECT +R1.VPLATAAPROB BUGET
            FROM Bugetrectif1 R1 INNER JOIN Bugetrectif R ON  R.Codbugetrectif = R1.CODBUGETRECTIF
            WHERE R.AN = aAn AND R.LunaSursa BETWEEN aLuna1 AND aLuna2 AND  R1.CodNodSursa = aCodAnalizaNod and  COALESCE(R1.VPLATAAPROB, 0) &lt;&gt; 0
           ) A_PG;
    EXCEPTION WHEN OTHERS THEN
      aSold := 0;
    END;
  END IF;

  WME_Result :=  aSold;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plati_getsoldbuget</obj_name>
  <obj_hashval>24e891f0cd5ac6e72980448e030682c1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plati_getsoldbuget(acodanalizanod numeric, aan numeric, aluna numeric, acodplata numeric, atipdoc numeric DEFAULT 0)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aSold       numeric;
  x           numeric;
  y           numeric;
  aLuna1       numeric;
  aLuna2       numeric;
  aTipSold     numeric;
  aCodAnaliza numeric;
BEGIN
  --Adina 06.10.2020
  IF  aTipDoc = 1 THEN
    BEGIN
      SELECT codanaliza INTO aCodAnaliza FROM analizanod WHERE  codanalizanod = aCodAnalizaNod;

      EXECUTE
      'DO LANGUAGE PLPGSQL $$ ' ||
      '  BEGIN' || coalesce(Chr(10),'') ||
      '    DELETE FROM TMP_BUGETANALIZA;' || coalesce(Chr(10),'') ||
      '    PERFORM PKG_ANALIZA_GetBugete( ' || coalesce(aCodAnaliza::varchar ,'') || ', ' || coalesce(getANLUCRU(),'') || ', 1, 12, 9, 0 );' || coalesce(Chr(10),'') ||
      '    DELETE FROM TMP_BUGETANALIZA WHERE CODANALIZANOD IN (SELECT DISTINCT NODPARINTE FROM ANALIZANOD WHERE CODANALIZA = ' || coalesce(aCodAnaliza::varchar ,'') || ');' || coalesce(Chr(10),'') ||
      'END $$;';
    EXCEPTION WHEN others THEN
      aCodAnaliza := 0;
    END;

    BEGIN
      SELECT (SELECT sum(CASE WHEN codcentru = 1 THEN B1+B2+B3+B4+B5+B6+B7+B8+B9+B10+B11+B12 ELSE 0 END) FROM TMP_BUGETANALIZA WHERE codanalizanod = aCodanalizanod)
              -
             (SELECT sum(CASE WHEN codcentru = 4 THEN B1+B2+B3+B4+B5+B6+B7+B8+B9+B10+B11+B12 ELSE 0 END) FROM TMP_BUGETANALIZA WHERE codanalizanod = aCodanalizanod)
      INTO aSold;
    EXCEPTION WHEN others THEN
      aSold := 0;
    END;
  ELSE
    BEGIN
      BEGIN
        SELECT COALESCE(fnc_GetValConstanta('TipValoriBuget', getANLUCRU(), getLUNALUCRU())::numeric, 1) INTO aTipSold;
      EXCEPTION WHEN OTHERS THEN
        aTipSold := 1;
      END;

      IF  aTipSold = 1 THEN
        aLuna1 := aLuna;
        aLuna2 := aLuna;
      ELSIF aTipSold = 2 THEN
        aLuna1 := aLuna;
        aLuna2 := Trunc((  aLuna + 2)  / 3) * 3;
        aLuna1 := aLuna2 - 2;
      ELSIF aTipSold = 3 THEN
         aLuna1 := 1;
         aLuna2 := 12;
      END IF;

      SELECT Sum(COALESCE(Buget, 0)) INTO aSold
      FROM (SELECT BUGET
            FROM BUGETANALIZA BA
            WHERE BA.AN = aAn AND BA.Luna BETWEEN aLuna1 AND aLuna2 AND  BA.CodAnalizaNod = aCodAnalizaNod AND  BA.Tip = 9
            union ALL
            SELECT R1.VCredit BUGET
            FROM   Bugetrectif1 R1
                  INNER JOIN Bugetrectif R ON  R.Codbugetrectif = R1.CODBUGETRECTIF
            WHERE R.AN = aAn AND R.LunaDest BETWEEN aLuna1 AND aLuna2 and  R1.CodNodDest = aCodAnalizaNod and  COALESCE(R1.VCredit, 0) &lt;&gt; 0
            union ALL
            SELECT -R1.VCredit BUGET
            FROM   Bugetrectif1 R1
                  INNER JOIN Bugetrectif R ON  R.Codbugetrectif = R1.CODBUGETRECTIF
            WHERE R.AN = aAn AND R.LunaSursa BETWEEN aLuna1 AND aLuna2 AND  R1.CodNodSursa = aCodAnalizaNod and  COALESCE(R1.VCredit, 0) &lt;&gt; 0
            union ALL
            SELECT -p1.VALOARE BUGET
            FROM   Plati1 P1
                  INNER JOIN Plati P ON  P.CodPlata = P1.CodPlata
            WHERE P.An = aAn AND P.Luna BETWEEN aLuna1 AND aLuna2 and P.TipDoc = 1 AND  P1.CodAnalizaNodx = aCodAnalizaNod and P1.CodObligPIF IN (0, 1, 2) and (aCodPlata = 0 or P.CodPlata &lt;&gt; aCodPlata)
            union ALL
            SELECT -P1.Valoare BUGET
            FROM   ObligPIF O
                  INNER JOIN Plati1 P1 ON  P1.CodObligPIF = O.CodObligPIF
                  INNER JOIN Plati P ON  P.Codplata = P1.Codplata
            WHERE P.An = aAn AND P.Luna BETWEEN aLuna1 AND aLuna2 and  P.TipDoc = 1 AND  O.CodAnalizaNod = aCodAnalizaNod and (   NOT P1.CodObligPIF IN (0, 1, 2))  and (   aCodPlata = 0 or  P.CodPlata &lt;&gt; aCodPlata)
            union ALL
            SELECT -R1.VPLATAAPROB BUGET
            FROM   Bugetrectif1 R1
                  INNER JOIN Bugetrectif R ON  R.Codbugetrectif = R1.CODBUGETRECTIF
            WHERE R.AN = aAn AND R.LunaDest BETWEEN aLuna1 AND aLuna2 and  R1.CodNodDest = aCodAnalizaNod and  COALESCE(R1.VPLATAAPROB, 0) &lt;&gt; 0
            union ALL
            SELECT +R1.VPLATAAPROB BUGET
            FROM   Bugetrectif1 R1
                  INNER JOIN Bugetrectif R ON  R.Codbugetrectif = R1.CODBUGETRECTIF
            WHERE R.AN = aAn AND R.LunaSursa BETWEEN aLuna1 AND aLuna2 AND  R1.CodNodSursa = aCodAnalizaNod and  COALESCE(R1.VPLATAAPROB, 0) &lt;&gt; 0
           ) A_PG;
    EXCEPTION WHEN OTHERS THEN
      aSold := 0;
    END;
  END IF;

  RETURN  aSold;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plati_getsoldbuget1</obj_name>
  <obj_hashval>5e7894ef57685250cb0714ff15bf30eb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plati_getsoldbuget1(INOUT wme_result numeric, INOUT acodanalizanod numeric, INOUT aan numeric, INOUT aluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aSold    numeric;
  aLuna1   numeric;
  aLuna2   numeric;
  aTipSold numeric;
begin
  BEGIN
    BEGIN
      SELECT COALESCE((fnc_GetValConstantaLucru('TipValoriBuget'))::numeric, 1)
      INTO aTipSold;
    EXCEPTION WHEN OTHERS THEN
      aTipSold := 1;
    END;

    IF  aTipSold = 1 THEN
      aLuna1 := aLuna;
      aLuna2 := aLuna;
    ELSIF aTipSold = 2 THEN
      aLuna1 := aLuna;
      aLuna2 := Trunc((  aLuna + 2)  / 3) * 3;
      aLuna1 := aLuna2 - 2;
    END IF;

    SELECT Sum(COALESCE(Buget, 0)) INTO aSold
    FROM (SELECT BUGET FROM BUGETANALIZA BA WHERE BA.AN = aAn AND BA.Luna BETWEEN aLuna1 AND aLuna2 AND  BA.CodAnalizaNod = aCodAnalizaNod AND  BA.Tip = 9
          union ALL
          SELECT R1.VCredit BUGET
          FROM Bugetrectif1 R1 INNER JOIN Bugetrectif R ON  R.Codbugetrectif = R1.CODBUGETRECTIF
          WHERE R.AN = aAn AND R.LunaDest BETWEEN aLuna1 AND aLuna2 and  R1.CodNodDest = aCodAnalizaNod
          union ALL
          SELECT -R1.VCredit BUGET
          FROM Bugetrectif1 R1 INNER JOIN Bugetrectif R ON  R.Codbugetrectif = R1.CODBUGETRECTIF
          WHERE R.AN = aAn AND R.LunaSursa BETWEEN aLuna1 AND aLuna2 AND  R1.CodNodSursa = aCodAnalizaNod
          union ALL
          SELECT -C1.PU * C1.CantComandat BUGET
          FROM COMANDA1 C1
              INNER JOIN COMANDA    C ON  C.CodComanda    = C1.CodComanda
              INNER JOIN AnalizaNod N ON  N.CodAnalizaNod = C1.CodAnalizaNod
          WHERE C.TipDoc = 8 and  C.An = aAn AND C.Luna BETWEEN aLuna1 AND aLuna2 and  C1.Codanalizanod = aCodAnalizaNod
         ) A_PG;
  EXCEPTION WHEN OTHERS THEN
    aSold := 0;
  END;

  WME_Result :=  aSold;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plati_sp_deleterecord</obj_name>
  <obj_hashval>fd276258fa9a3844752e292e38076a37</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plati_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  ACARNETDOC numeric;
  ANRDOC     numeric;
BEGIN
  --Florin 19.11.2024 - sinc. Oracle
  --Florin 20.09.2022 - sinc. Oracle
  SELECT CARNETDOC, NRDOC INTO ACARNETDOC, ANRDOC FROM PLATI WHERE CODPLATA = RECID;

  PERFORM PKG_PLATI_SP_LOCKRECORD(RecId);
  PERFORM PKG_CFGTABLES_EXT_DELETERECORD (recId, 105);

  DELETE FROM PLATI1 WHERE CODPLATA = RecId;
  DELETE FROM PLATI2 WHERE CODPLATA = RecId;
  DELETE FROM PLATI  WHERE CODPLATA = RecId;

  PERFORM PKG_CARNETEDOC_RELEASENUMARDOC(ACARNETDOC, ANRDOC);
  PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE(ACARNETDOC);
  PERFORM NotifyModif(2, RecId, 'PLATI');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plati_sp_postrecords</obj_name>
  <obj_hashval>e397433eb39d5c3892e5403990af123e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plati_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC      RECORD;
  ACARNETDOC numeric;
  ANRDOC     numeric;
BEGIN
  --Florin 19.11.2024 - sinc. Oracle
  --Florinn 16.05.2024 - sinc. Oracle
  --Florin 20.09.2022 - sinc. Oracle
  SELECT CARNETDOC, NRDOC INTO ACARNETDOC, ANRDOC FROM TMP_PLATI;

  UPDATE TMP_PLATI1 SET DINCARETVA = VALOARE WHERE SPLITTVA = 1;
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT(105);
  IF  Operation = 0 THEN
    SELECT CODPLATA INTO RECID FROM TMP_PLATI;

    UPDATE PLATI P
    SET
    (DATA, CODBANKCONT, VALOARE, VALOAREDEREPARTIZAT, APROBAT, CARNETDOC, NRDOC, TipDoc, CodAnaliza, AN, LUNA, OBS, CURS)
    =
    (SELECT DATA, CODBANKCONT, VALOARE, VALOAREDEREPARTIZAT, APROBAT, CARNETDOC, NRDOC, TipDoc, CodAnaliza, AN, LUNA, OBS, CURS FROM TMP_PLATI TP)
    WHERE
     P.CODPLATA = RECID;

    DELETE FROM PLATI1 P1 WHERE CODPLATA = RECID AND  NOT  EXISTS (SELECT CODPLATA1 FROM TMP_PLATI1 WHERE CODPLATA1 = P1.CODPLATA1);

    DELETE FROM PLATI2 P2
    WHERE
      CODPLATA = RECID
      AND NOT EXISTS (SELECT CODPLATA2 FROM TMP_PLATI2 WHERE CODPLATA2 = P2.CODPLATA2);

    FOR V_REC IN (SELECT * FROM TMP_PLATI1) LOOP
      IF  V_REC.CODPLATA1 &lt; 0 THEN
        INSERT INTO PLATI1(CODPLATA1, CODPLATA, CODOBLIGPIF, VALOARE, SPLITTVA, REST, CODMONEDA, CONTDEST, ADRESAFURN, CODSWIFT, CODBNR, CODSTATISTICBNR, TIPCOMISION, CODBANK, INDEXLOCAL, CODPART, DINCARETVA, Codanalizanodx, codpers, codcont)
        VALUES(NEXTVAL('SEQ_PLATI1_CODPLATA1'), RECID, V_REC.CODOBLIGPIF, V_REC.VALOARE, V_REC.SPLITTVA, V_REC.REST, V_REC.CODMONEDA, V_REC.CONTDEST, V_REC.ADRESAFURN, V_REC.CODSWIFT, V_REC.CODBNR, V_REC.CODSTATISTICBNR, V_REC.TIPCOMISION, V_REC.CODBANK, V_REC.INDEXLOCAL, V_REC.CODPART, V_REC.DINCARETVA, COALESCE(V_REC.Codanalizanodx, V_REC.Codanalizanod), V_REC.codpers, V_REC.codcont);
      ELSE
        UPDATE PLATI1
        SET
        VALOARE         = V_REC.VALOARE,
        SPLITTVA        = V_REC.SPLITTVA,
        REST            = V_REC.REST,
        CODMONEDA       = V_REC.CODMONEDA,
        CONTDEST        = V_REC.CONTDEST,
        ADRESAFURN      = V_REC.ADRESAFURN,
        CODSWIFT        = V_REC.CODSWIFT,
        CODBNR          = V_REC.CODBNR,
        CODSTATISTICBNR = V_REC.CODSTATISTICBNR,
        TIPCOMISION     = V_REC.TIPCOMISION,
        CODBANK         = V_REC.CODBANK,
        INDEXLOCAL      = V_REC.INDEXLOCAL,
        CODPART         = V_REC.CODPART,
        DINCARETVA      = V_REC.DINCARETVA,
        Codanalizanodx  = COALESCE(V_REC.Codanalizanodx, V_REC.Codanalizanod),
        codpers         = V_REC.codpers,
        codcont         = V_REC.codcont
        WHERE
         CODPLATA1 = V_REC.CODPLATA1;
      END IF;
    END LOOP;

      FOR V_REC IN (SELECT * FROM TMP_PLATI2)
      LOOP
        IF V_REC.CODPLATA2 &lt; 0 THEN
          INSERT INTO PLATI2(CODPLATA2, CODPLATA, CODPERS, CONTDEST, CODSWIFT, VALOARE, NRDOC)
          VALUES(NEXTVAL('SEQ_PLATI2_CODPLATA2'), RECID,  V_REC.CODPERS, V_REC.CONTDEST, V_REC.CODSWIFT, V_REC.VALOARE, V_REC.NRDOC );
        ELSE
          UPDATE PLATI2
          SET
            CODPERS  = V_REC.CODPERS,
            CONTDEST = V_REC.CONTDEST,
            CODSWIFT = V_REC.CODSWIFT,
            VALOARE  = V_REC.VALOARE,
            NRDOC    = V_REC.NRDOC
          WHERE
            CODPLATA2 = V_REC.CODPLATA2;
        END IF;
      END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_PLATI_CODPLATA') INTO RecID;
    PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('PLATI', RecId);

    INSERT INTO PLATI(CODPLATA, DATA, CODBANKCONT, VALOARE, CARNETDOC, NRDOC, TipDoc, userid, datacreare, CodAnaliza, AN, LUNA, SUBUNITATEA, VALOAREDEREPARTIZAT, APROBAT, OBS, CURS)
    SELECT RECID, DATA, CODBANKCONT, VALOARE, CARNETDOC, NRDOC, TipDoc, current_setting('PKG_GLOBALS.USERID', true)::numeric, CURRENT_TIMESTAMP, CodAnaliza, AN, LUNA, SUBUNITATEA, VALOAREDEREPARTIZAT, APROBAT, OBS, CURS
    FROM TMP_PLATI;

    INSERT INTO PLATI1(CODPLATA1, CODPLATA, CODOBLIGPIF, VALOARE, SPLITTVA, REST, CODMONEDA, CONTDEST, ADRESAFURN, CODSWIFT, CODBNR, CODSTATISTICBNR, TIPCOMISION, CODBANK, INDEXLOCAL, CODPART, DINCARETVA, Codanalizanodx, codpers, codcont)
    SELECT NEXTVAL('SEQ_PLATI1_CODPLATA1'), RECID, CODOBLIGPIF, VALOARE, SPLITTVA, REST, CODMONEDA, CONTDEST, ADRESAFURN, CODSWIFT, CODBNR, CODSTATISTICBNR, TIPCOMISION, CODBANK, INDEXLOCAL, CODPART, DINCARETVA, COALESCE(Codanalizanodx, Codanalizanod), codpers, codcont
    FROM TMP_PLATI1;

    INSERT INTO PLATI2(CODPLATA2, CODPLATA, CODPERS, CONTDEST, CODSWIFT, VALOARE, NRDOC)
    SELECT NEXTVAL('SEQ_PLATI2_CODPLATA2'), RECID,  CODPERS, CONTDEST, CODSWIFT, VALOARE, NRDOC
    FROM
      TMP_PLATI2;
  END IF;

  IF (current_setting('PKG_PLATI.CARNETDOC_I', true)::numeric &lt;&gt; 0)  AND (current_setting('PKG_PLATI.NRDOC_I', true)::numeric &lt;&gt; 0)  AND (ACARNETDOC &lt;&gt; current_setting('PKG_PLATI.CARNETDOC_I', true)::numeric OR  ANRDOC &lt;&gt; current_setting('PKG_PLATI.NRDOC_I', true)::numeric)
  THEN
    PERFORM PKG_CARNETEDOC_RELEASENUMARDOC(current_setting('PKG_PLATI.CARNETDOC_I', true)::numeric, current_setting('PKG_PLATI.NRDOC_I', true)::numeric);
    PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE(current_setting('PKG_PLATI.CARNETDOC_I', true)::numeric);
  END IF;

  PERFORM PKG_CARNETEDOC_SOLVENUMARDOC(ACARNETDOC, (ANRDOC)::character varying);
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS(105);
  PERFORM NotifyModif(Operation, RecId, 'PLATI');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_am_miscari_cu_pmp</obj_name>
  <obj_hashval>dfdaebf4aa59fbecb4e5cf63ddfbd5fc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_am_miscari_cu_pmp()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  cntio     NUMERIC;
  cntdoc    NUMERIC;
  vAntemp   NUMERIC(4) := current_setting('PKG_GLOBALS.ANTEMP'  , true)::numeric;
  vLunaTemp NUMERIC(2) := current_setting('PKG_GLOBALS.LUNATEMP', true)::numeric;
BEGIN
  --Stef   01.03.2023
  PERFORM pkg_stoc_generare_facturi_make_config_luna();

  SELECT count(1) INTO cntio FROM TMP_IOART_LUNA IO WHERE io.mg = 3;
  IF cntio = 0 THEN
    RETURN 0;
  END IF;

  DELETE FROM tmp_pmp_act_luna;

  INSERT INTO tmp_pmp_act_luna(codies, tipdoc, codlivr1, codobiect, codsubunit, pmp,pmpvaluta)
  SELECT i.CodIes, i.TipDoc, l1.codlivr1, ns.codobiect, i.subunitatea, l1.pmp, l1.pmpvaluta
  FROM iesiri i
    INNER JOIN livr           l  ON l.codies      = i.codies
    INNER JOIN livr1          l1 ON l.codlivr     = l1.codlivr
    INNER JOIN nirstoc        ns ON ns.codnirstoc = l1.codnirstoc
    INNER JOIN tmp_ioart_luna io ON io.codioart   = ns.codioart AND io.mg = 3
  WHERE i.an = vAntemp AND i.luna = vLunaTemp;

  INSERT INTO tmp_pmp_act_luna(codies, tipdoc, codlivr1, codobiect, codsubunit, pmp,pmpvaluta)
  SELECT i.CodIntr, i.TipDoc, l1.codlivr1, ns.codobiect,i.subunitatea, l1.pmp, l1.pmpvaluta
  FROM intrari i
    INNER JOIN livr           l  ON l.codintr      = i.codintr
    INNER JOIN livr1          l1 on l.codlivr     = l1.codlivr
    INNER JOIN nirstoc        ns on ns.codnirstoc = l1.codnirstoc
    INNER JOIN tmp_ioart_luna io ON io.codioart   = ns.codioart AND io.mg = 3
  WHERE i.an = vAntemp AND i.luna = vLunaTemp;

  INSERT INTO tmp_pmp_act_luna(codies, tipdoc, codlivr1, codobiect, codsubunit, pmp,pmpvaluta)
  SELECT TR.CodTransf, TR.TipDoc, l1.codlivr1, ns.codobiect,TR.subunitatea, l1.pmp, l1.pmpvaluta
  FROM transf tr
    INNER JOIN livr           l  ON l.CodTransf   = tr.CodTransf
    INNER JOIN livr1          l1 on l.codlivr     = l1.codlivr
    INNER JOIN nirstoc        ns on ns.codnirstoc = l1.codnirstoc
    INNER JOIN tmp_ioart_luna io ON io.codioart   = ns.codioart AND io.mg = 3
  WHERE tr.an = vAntemp AND tr.luna = vLunaTemp;

  SELECT Count(1) INTO cntdoc FROM tmp_pmp_act_luna;
  RETURN cntdoc;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_calc_pmp2</obj_name>
  <obj_hashval>e8bfddc512e4b4ba0748dd2b963eaea0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_calc_pmp2(tip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  cntio   numeric;
  cntdoc  numeric;
  pmpval_ double precision;
  pmp_    double precision;
BEGIN
  --Adina 02.12.2020 tichet 41389
  --Adina 01.12.2020 tichet 41367
  --Adina 28 iulie 2020
  --Bogdan 15.08.2020
  DELETE FROM tmp_pmp;

  IF  Tip = 2 THEN
    INSERT INTO tmp_pmp(codobiect, Codsubunit)
    SELECT distinct CodObiect, CodSubunit FROM tmp_pmp_act_luna;
  ELSE
    INSERT INTO tmp_pmp(codobiect, Codsubunit)
    SELECT distinct CodObiect, 1 FROM tmp_pmp_act_luna;
  END IF;

  FOR v_rec IN (SELECT * FROM tmp_pmp)
  LOOP
    --pmp_ := (SELECT PKG_PMP_GET_PMP_OBIECT.WME_RESULT FROM PKG_PMP_GET_PMP_OBIECT(NULL, v_rec.CodObiect, v_rec.CodSubunit, pmpval_::numeric,null::numeric,null::numeric));
    SELECT PKG_PMP_GET_PMP_OBIECT.WME_RESULT, PKG_PMP_GET_PMP_OBIECT.pmpvaluta
    INTO pmp_, pmpval_
    FROM PKG_PMP_GET_PMP_OBIECT(NULL, v_rec.CodObiect, v_rec.CodSubunit, null::numeric,null::numeric,null::numeric);

    UPDATE tmp_pmp
    SET
      pmp           = pmp_,
      pmpvaluta     = pmpval_,
      pmpprec       = (current_setting('PKG_PMP.G_PMP_PREC',true))::numeric,
      pmpprecvaluta = (current_setting('PKG_PMP.G_PMP_PREC_VAL',true))::numeric
    WHERE
      codobiect = v_rec.codobiect and  codsubunit = v_rec.codsubunit;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_g_pmp_last</obj_name>
  <obj_hashval>369938699e00b88b7b80f644815715ce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_g_pmp_last(INOUT wme_result double precision, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PMP.G_PMP_LAST', true)),'99999999999.9999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_g_pmp_last_val</obj_name>
  <obj_hashval>edfac2ac95c979213c0d02fed831e940</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_g_pmp_last_val(INOUT wme_result double precision, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PMP.G_PMP_LAST_VAL', true)),'99999999999.9999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_g_pmp_lei</obj_name>
  <obj_hashval>40819e95e7990127d8bdd45e9a51c64f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_g_pmp_lei(INOUT wme_result double precision, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PMP.G_PMP_LEI', true)),'99999999999.9999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_g_pmp_prec</obj_name>
  <obj_hashval>0b21cecfe2847401b17a7e02aa299a21</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_g_pmp_prec(INOUT wme_result double precision, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PMP.G_PMP_PREC', true)),'99999999999.9999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_g_pmp_prec_val</obj_name>
  <obj_hashval>753806d3e37d95ebcb9e0dc3b9a794a3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_g_pmp_prec_val(INOUT wme_result double precision, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PMP.G_PMP_PREC_VAL', true)),'99999999999.9999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_get_pmp_last</obj_name>
  <obj_hashval>3efd4cb33b27aff3095914d6eed3abe7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_get_pmp_last(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT acodsubunit numeric, INOUT xan numeric DEFAULT 0, INOUT xluna numeric DEFAULT 0)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 14.09.2020
  perform set_config('PKG_PMP.G_PMP_LEI'     ,to_char(-1,'99999999999.9999999'),false);
  perform set_config('PKG_PMP.G_PMP_VALUTA'  ,to_char(-1,'99999999999.9999999'),false);
  perform set_config('PKG_PMP.G_PMP_PREC'    ,to_char(-1,'99999999999.9999999'),false);
  perform set_config('PKG_PMP.G_PMP_PREC_VAL',to_char(-1,'99999999999.9999999'),false);
  perform set_config('PKG_PMP.G_PMP_LAST'    ,to_char(-1,'99999999999.9999999'),false);
  perform set_config('PKG_PMP.G_PMP_LAST_VAL',to_char(-1,'99999999999.9999999'),false);
  perform set_config('PKG_PMP.G_PMP_LEI'     ,to_char((SELECT PKG_PMP_GET_PMP_OBIECT.WME_RESULT FROM PKG_PMP_GET_PMP_OBIECT(NULL, aCodObiect, aCodSubunit, TO_NUMBER((current_setting('PKG_PMP.G_PMP_VALUTA', true)),'99999999999.9999999'), COALESCE( XAN, 0), COALESCE( XLUNA, 0))),'99999999999.9999999'),false);

  WME_Result :=  TO_NUMBER((current_setting('PKG_PMP.G_PMP_LAST', true)),'99999999999.9999999');
  RETURN;

  perform set_config('PKG_PMP.G_PMP_LAST',to_char(-1,'99999999999.9999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_get_pmp_last_valuta_from_var</obj_name>
  <obj_hashval>6a25c47f14ce6a25e6c9d75d9ac4bbe4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_get_pmp_last_valuta_from_var(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER((current_setting('PKG_PMP.G_PMP_LAST_VAL', true)),'99999999999.9999999');
RETURN;
perform set_config('PKG_PMP.G_PMP_LAST_VAL',to_char(-1,'99999999999.9999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_get_pmp_lei</obj_name>
  <obj_hashval>0051fc98f549b0bf2eeaed80d311a64e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_get_pmp_lei(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT acodsubunit numeric, INOUT xan numeric, INOUT xluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 01.12.2020 tichete 41352,41353
  perform set_config('PKG_PMP.G_PMP_LEI',     to_char(-1,'99999999999.9999999'),false);
  perform set_config('PKG_PMP.G_PMP_VALUTA',  to_char(-1,'99999999999.9999999'),false);
  perform set_config('PKG_PMP.G_PMP_PREC',    to_char(-1,'99999999999.9999999'),false);
  perform set_config('PKG_PMP.G_PMP_PREC_VAL',to_char(-1,'99999999999.9999999'),false);
  perform set_config('PKG_PMP.G_PMP_LAST',    to_char(-1,'99999999999.9999999'),false);
  perform set_config('PKG_PMP.G_PMP_LASt_VAL',to_char(-1,'99999999999.9999999'),false);
  perform set_config('PKG_PMP.G_PMP_LEI',     to_char((SELECT PKG_PMP_GET_PMP_OBIECT.WME_RESULT FROM PKG_PMP_GET_PMP_OBIECT(NULL, aCodObiect, aCodSubunit, TO_NUMBER(current_setting('PKG_PMP.G_PMP_VALUTA', true),'99999999999.9999999'), COALESCE( XAN, 0), COALESCE( XLUNA, 0))),'99999999999.9999999'),false);
  WME_Result :=  TO_NUMBER(current_setting('PKG_PMP.G_PMP_LEI', true),'99999999999.9999999');
  RETURN;
  perform set_config('PKG_PMP.G_PMP_LEI',to_char(-1,'99999999999.9999999'),false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_get_pmp_lei</obj_name>
  <obj_hashval>570ff2c3838c47474bfc1d1540a77be3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_get_pmp_lei(acodobiect numeric, acodsubunit numeric, xan numeric, xluna numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 01.12.2020 tichete 41352,41353
  perform set_config('PKG_PMP.G_PMP_LEI',     to_char(-1,'99999999999.9999999'),false);
  perform set_config('PKG_PMP.G_PMP_VALUTA',  to_char(-1,'99999999999.9999999'),false);
  perform set_config('PKG_PMP.G_PMP_PREC',    to_char(-1,'99999999999.9999999'),false);
  perform set_config('PKG_PMP.G_PMP_PREC_VAL',to_char(-1,'99999999999.9999999'),false);
  perform set_config('PKG_PMP.G_PMP_LAST',    to_char(-1,'99999999999.9999999'),false);
  perform set_config('PKG_PMP.G_PMP_LASt_VAL',to_char(-1,'99999999999.9999999'),false);
  perform set_config('PKG_PMP.G_PMP_LEI',     to_char((SELECT PKG_PMP_GET_PMP_OBIECT.WME_RESULT FROM PKG_PMP_GET_PMP_OBIECT(NULL, aCodObiect, aCodSubunit, current_setting('PKG_PMP.G_PMP_VALUTA', true)::NUMERIC, COALESCE( XAN, 0), COALESCE( XLUNA, 0))),'99999999999.9999999'),false);
  RETURN current_setting('PKG_PMP.G_PMP_LEI', true)::NUMERIC;
  perform set_config('PKG_PMP.G_PMP_LEI',to_char(-1,'99999999999.9999999'),false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_get_pmp_obiect</obj_name>
  <obj_hashval>fbec8e3f6c9e8e236480d15bffba727f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_get_pmp_obiect(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT acodsubunit numeric, INOUT pmpvaluta numeric, INOUT xan numeric, INOUT xluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  VREC RECORD;
  iPMP          NUMERIC(20,7) := 0;
  iPMPVal       NUMERIC(20,7) := 0;
  iPMPPrec      NUMERIC(20,7) := 0;
  iPMPPrecVal   NUMERIC(20,7) := 0;
  iPMPLast      NUMERIC(20,7) := 0;
  iPMPLastVal   NUMERIC(20,7) := 0;
  aCANTINTR     NUMERIC(20,7) := 0;
  aVALINTR      NUMERIC(20,7) := 0;
  aVALVALUTA    NUMERIC(20,7) := 0;
  CANTINTRPREC  NUMERIC(20,7) := 0;
  VALINTRPREC   NUMERIC(20,7) := 0;
  VALVALUTAPREC NUMERIC(20,7) := 0;
  iAn           NUMERIC(4);
  iLuna         NUMERIC(2);
  iAnPrec       NUMERIC(4);
  iLunaPrec     NUMERIC(2);

  sSQL          TEXT;
BEGIN
  -- Bogdan 10.04.2023 corectie luna precedenta
  -- Stef 02.03.2023
  iAn   := Coalesce(xAn,0);
  iLuna := Coalesce(xLuna,0);
  IF iAn = 0 THEN
    iAn   := getAnLucru();
    iLuna := getLunaLucru();
  END IF;


  SELECT NEWAN, NEWLUNA INTO iAnPrec, iLunaPrec FROM PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA( iAn, iLuna, iAnPrec, iLunaPrec);
  PERFORM PKG_GLOBALS_SetLunaTemp( iAn, iLuna);
  PERFORM PKG_CATEGCONST_CONST_TO_TMP_CONSTANTE('TRANSFPMP');

  BEGIN
    SELECT SUM(CANTINTR),  SUM(VALINTR), SUM(VALVALUTA) INTO STRICT CANTINTRPREC, VALINTRPREC , VALVALUTAPREC
    FROM PMPLUNA
    WHERE an = iAnPrec AND luna = iLunaPrec
      AND CodObiect  = aCodObiect
      AND CodSubunit = CASE aCodSubunit WHEN 1 THEN CodSubunit ELSE aCodSubunit END;
  EXCEPTION
    WHEN OTHERS THEN CANTINTRPREC := 0; VALINTRPREC := 0; VALVALUTAPREC := 0;
  END;

  CANTINTRPREC  := Coalesce(CANTINTRPREC ,0);
  VALINTRPREC   := Coalesce(VALINTRPREC  ,0);
  VALVALUTAPREC := Coalesce(VALVALUTAPREC,0);

  IF Coalesce(CANTINTRPREC,0) &lt;&gt; 0 THEN
    iPMPPrec    := Round(VALINTRPREC   / CANTINTRPREC,7);
    iPMPPrecVal := Round(VALVALUTAPREC / CANTINTRPREC,7);
  END IF;

  BEGIN
    EXECUTE 'SELECT Sum(VALINTR), Sum(CANTINTR), Sum(VALVALUTA) FROM ('||V_PMP_LUNA(aCodObiect, aCodSubunit)||') aa ' INTO STRICT aVALINTR, aCANTINTR, aVALVALUTA;
  EXCEPTION
    WHEN OTHERS THEN aCANTINTR := 0; aVALINTR := 0; aVALVALUTA := 0;
  END;

  aVALINTR   := Coalesce(aVALINTR  ,0) + Coalesce(VALINTRPREC,  0);
  aCANTINTR  := Coalesce(aCANTINTR ,0) + Coalesce(CANTINTRPREC, 0);
  aVALVALUTA := Coalesce(aVALVALUTA,0) + Coalesce(VALVALUTAPREC,0);
  IF aCANTINTR &lt;&gt; 0 THEN
    iPMP    := Round(aVALINTR   / aCANTINTR,7);
    iPMPVal := Round(aVALVALUTA / aCANTINTR,7);
  END IF;

  iPMPLast    := iPMP;
  iPMPLastVal := iPMPVal;

  IF iPMPLast = 0    THEN iPMPLast    := iPMPPrec;    END IF;
  IF iPMPLastVal = 0 THEN iPMPLastVal := iPMPPrecVal; END IF;

  IF iPMPLast = 0 OR iPMPLastVal = 0 THEN
    FOR vRec IN (
      SELECT SUM(CANTINTR) CANT, SUM(VALINTR) VAL, SUM(VALVALUTA) VALV
      FROM PMPLUNA
      WHERE an = iAnPrec AND luna = iLunaPrec
        AND CodObiect  = aCodObiect
        AND CodSubunit = CASE aCodSubunit WHEN 1 THEN CodSubunit ELSE aCodSubunit END
      GROUP BY AN     , LUNA
      ORDER BY AN DESC, LUNA DESC
    ) LOOP
      IF iPMPLast    = 0 AND vRec.Cant &lt;&gt; 0 THEN iPMPLast    := Round(vRec.Val  / vRec.Cant,7); END IF;
      IF iPMPLastVal = 0 AND vRec.Cant &lt;&gt; 0 THEN iPMPLastVal := Round(vRec.ValV / vRec.Cant,7); END IF;
      EXIT WHEN iPMPLast &lt;&gt; 0 AND iPMPLastVal &lt;&gt; 0;
    END LOOP;
  END IF;

  perform set_config('PKG_PMP.G_PMP_PREC'    ,to_char(iPMPPrec   ::text),false);
  perform set_config('PKG_PMP.G_PMP_PREC_VAL',to_char(iPMPPrecVal::text),false);
  perform set_config('PKG_PMP.G_PMP_LAST'    ,to_char(iPMPLast   ::text),false);
  perform set_config('PKG_PMP.G_PMP_LAST_VAL',to_char(iPMPLastVal::text),false);

  PMPValuta  := iPMPVal;
  WME_Result := iPMP;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_get_pmp_obiect_doc</obj_name>
  <obj_hashval>0a8bafdfb1413b6544a20921a01bfe5b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_get_pmp_obiect_doc(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT acodsubunit numeric, INOUT apmpcodintr numeric, INOUT apmpcodies numeric, INOUT apmpcodtransf numeric, INOUT pmpvaluta numeric, INOUT xan numeric, INOUT xluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  iResult       double precision := -1;
  iResultValuta double precision := -1;
  aCANTINTR     double precision := 0;
  aVALINTR      double precision := 0;
  aVALVALUTA    double precision := 0;
  CANTINTRPREC  double precision := 0;
  VALINTRPREC   double precision := 0;
  VALVALUTAPREC double precision := 0;
  NR            numeric := 0;
  IAN           numeric;
  ILUNA         numeric;
begin
  -- Bogdan 10.04.2023 corectie STRICT
  --Florin 10.01.2021 - fixat 52544
  PERFORM PKG_Globals_SetPMPCodDocs( aPMPCodIntr, aPMPCodIes, aPMPCodTransf);

  IAN   := COALESCE( XAN, 0);
  ILUNA := COALESCE( XLUNA, 0);

  IF  IAN = 0 THEN
    IAN   := TO_NUMBER((current_setting('PKG_GLOBALS.AnLucru'  , true)),'999999999999999999');
    ILUNA := TO_NUMBER((current_setting('PKG_GLOBALS.LunaLucru', true)),'999999999999999999');
  END IF;

  PERFORM pkg_globals_SetLunaTemp( IAN, ILUNA);
  execute 'SELECT COUNT( *) FROM ('|| V_PMP_LUNA_DOC() || ') aa WHERE aa.CodObiect = ' || aCodObiect INTO NR;
  IF  NR = 0 THEN
    IF  aCodSubunit = 1 THEN
      BEGIN
        SELECT sum( valIntr), Sum( CantIntr), SUM( VALVALUTA)
        INTO STRICT  aValIntr, aCantIntr, aVALVALUTA
        FROM pmpluna
        WHERE (an * 12 + luna)  = (IAN * 12 + ILUNA - 1)  and  codobiect = aCodObiect;
      EXCEPTION WHEN OTHERS THEN
        aCANTINTR  := 0;
        aVALINTR   := 0;
        aVALVALUTA := 0;
      END;
    ELSE
      BEGIN
        SELECT sum( valIntr), Sum( CantIntr), SUM( VALVALUTA)
        INTO STRICT  aValIntr, aCantIntr, aVALVALUTA
        FROM pmpluna
        WHERE (an * 12 + luna)  = (IAN * 12 + ILUNA - 1)  and  codobiect = aCodObiect and  codsubunit = aCodSubunit;
      EXCEPTION WHEN OTHERS THEN
        aCANTINTR  := 0;
        aVALINTR   := 0;
        aVALVALUTA := 0;
      END;
    END IF;
  ELSE
    IF  aCodSubunit = 1 THEN
      BEGIN
        execute 'SELECT sum( v.VALINTR), sum( v.CANTINTR), sum( v.VALVALUTA)
        FROM ('|| V_PMP_LUNA_DOC() || ') aa
        WHERE aa.CODOBIECT = ' || aCodObiect INTO STRICT  aVALINTR, aCANTINTR, aVALVALUTA;
      EXCEPTION WHEN OTHERS THEN
        aCANTINTR  := 0;
        aVALINTR   := 0;
        aVALVALUTA := 0;
      END;

      BEGIN
        SELECT SUM( CANTINTR), SUM( VALINTR), SUM( VALVALUTA)
        INTO STRICT  CANTINTRPREC, VALINTRPREC, VALVALUTAPREC
        FROM PMPLUNA
        WHERE (an * 12 + luna)  = (IAN * 12 + ILUNA - 1)  AND  CODOBIECT = aCodObiect;
      EXCEPTION WHEN OTHERS THEN
        CANTINTRPREC  := 0;
        VALINTRPREC   := 0;
        VALVALUTAPREC := 0;
      END;
    ELSE
      BEGIN
        execute 'SELECT Sum( v.VALINTR), Sum( v.CANTINTR), sum( v.VALVALUTA)
        FROM ('|| V_PMP_LUNA_DOC() || ') aa
        WHERE aa.CODOBIECT = '|| aCodObiect || ' and  aa.CODSUBUNIT = || ' aCodSubunit INTO STRICT  aVALINTR, aCANTINTR, aVALVALUTA;
      EXCEPTION WHEN OTHERS THEN
        aCANTINTR  := 0;
        aVALINTR   := 0;
        aVALVALUTA := 0;
      END;

      BEGIN
        SELECT SUM( CANTINTR), SUM( VALINTR), SUM( VALVALUTA)
        INTO STRICT  CANTINTRPREC, VALINTRPREC, VALVALUTAPREC
        FROM PMPLUNA
        WHERE (an * 12 + luna)  = (IAN * 12 + ILUNA - 1)  AND  CODOBIECT = aCodObiect and  codsubunit = aCodSubunit;
      EXCEPTION WHEN OTHERS THEN
        CANTINTRPREC  := 0;
        VALINTRPREC   := 0;
        VALVALUTAPREC := 0;
      END;
    END IF;

    aVALINTR   := aVALINTR   + COALESCE( VALINTRPREC  , 0);
    aCANTINTR  := aCANTINTR  + COALESCE( CANTINTRPREC , 0);
    aVALVALUTA := aVALVALUTA + COALESCE( VALVALUTAPREC, 0);
  END IF;

  iResult       := 0;
  iResultValuta := 0;

  IF  aCANTINTR &lt;&gt; 0 THEN
    iResult       := aVALINTR / aCANTINTR;
    iResultValuta := aVALVALUTA / aCANTINTR;
  END IF;

  pmpvaluta := round( iResultValuta::numeric, 7);

  WME_Result :=  round( iResult::numeric, 7);
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_get_pmp_prec_from_var</obj_name>
  <obj_hashval>e263cb2094f59f5d53ae698b984cec1b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_get_pmp_prec_from_var(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER((current_setting('PKG_PMP.G_PMP_PREC', true)),'99999999999.9999999');
RETURN;
perform set_config('PKG_PMP.G_PMP_PREC',to_char(-1,'99999999999.9999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_get_pmp_valuta_from_var</obj_name>
  <obj_hashval>8142e3a2c31a95998edd139345061542</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_get_pmp_valuta_from_var()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 13.10.2020
  RETURN TO_NUMBER(current_setting('PKG_PMP.G_PMP_VALUTA', true),'99999999999.9999999');
  perform set_config('PKG_PMP.G_PMP_VALUTA',to_char(-1,'99999999999.9999999'),false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_get_pmp_valuta_from_var</obj_name>
  <obj_hashval>7a75c70fa23c33c5aa34f07332aaa39b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_get_pmp_valuta_from_var(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  WME_Result :=  TO_NUMBER(current_setting('PKG_PMP.G_PMP_VALUTA', true),'99999999999.9999999');
  RETURN;
  perform set_config('PKG_PMP.G_PMP_VALUTA',to_char(-1,'99999999999.9999999'),false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_getg_pmp_last</obj_name>
  <obj_hashval>0824bd78fcf47fdd2337e8ade232bf24</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_getg_pmp_last(INOUT wme_result double precision, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PMP.G_PMP_LAST', true)),'99999999999.9999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_setg_pmp_last</obj_name>
  <obj_hashval>78381418c11946e60c8949a8a2a9366c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_setg_pmp_last(ag_pmp_last double precision)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PMP.G_PMP_LAST',to_char(aG_PMP_LAST,'99999999999.9999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_setg_pmp_last_val</obj_name>
  <obj_hashval>3fe132dba991cdd44f580fbec1ed4ea5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_setg_pmp_last_val(ag_pmp_last_val double precision)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PMP.G_PMP_LAST_VAL',to_char(aG_PMP_LAST_VAL,'99999999999.9999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_setg_pmp_lei</obj_name>
  <obj_hashval>65857f48a9e3cf375455eac83d186d9c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_setg_pmp_lei(ag_pmp_lei double precision)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PMP.G_PMP_LEI',to_char(aG_PMP_LEI,'99999999999.9999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_setg_pmp_prec</obj_name>
  <obj_hashval>fae56a27a2ce5871402cb63f8e3a8ff4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_setg_pmp_prec(ag_pmp_prec double precision)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PMP.G_PMP_PREC',to_char(aG_PMP_PREC,'99999999999.9999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_setg_pmp_prec_val</obj_name>
  <obj_hashval>5f010df175573386b2c28040722414f8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_setg_pmp_prec_val(ag_pmp_prec_val double precision)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PMP.G_PMP_PREC_VAL',to_char(aG_PMP_PREC_VAL,'99999999999.9999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_setg_pmp_valuta</obj_name>
  <obj_hashval>d8af5ff33e756a6e0eaf56f9ef5f21b3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_setg_pmp_valuta(ag_pmp_valuta double precision)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PMP.G_PMP_VALUTA',to_char(aG_PMP_VALUTA,'99999999999.9999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_updatepmp</obj_name>
  <obj_hashval>959848a7f7e518c0c0512b4deb866513</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_updatepmp(tip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  V_X   RECORD;
  aCant           NUMERIC(20,7);
  pmpNou          NUMERIC(20,7);
  pmpVechi        NUMERIC(20,7);
  aValIntr        NUMERIC(20,7);
  aCantIntr       NUMERIC(20,7);
  ValIntrPREC     NUMERIC(20,7);
  CantIntrPREC    NUMERIC(20,7);
  liniLivr        NUMERIC(20);
  NR              NUMERIC(20);
  amIntrariInLuna BOOLEAN    := false;
  vAnTemp         NUMERIC(4) := current_setting('PKG_GLOBALS.ANTEMP'  , true)::numeric;
  vLunaTemp       NUMERIC(2) := current_setting('PKG_GLOBALS.LUNATEMP', true)::numeric;
BEGIN
  --Stef 03.03.2023
  UPDATE jurnal1 SET dirty = 0 WHERE an = vAntemp AND LUNA = vLunaTemp AND tipdoc = -9 AND coddoc = -999;

  IF  PKG_PMP_AM_MISCARI_CU_PMP() = 0 THEN
    RETURN;
  END IF;

  PERFORM PKG_PMP_CALC_PMP(Tip);

  --update jurnal1
  EXECUTE 'UPDATE jurnal1 j
  SET dirty = 1
  FROM (
    SELECT DISTINCT t.codies, t.tipdoc
    FROM tmp_pmp_act_luna t INNER JOIN tmp_pmp a ON a.codobiect = t.codobiect'||CASE WHEN Tip = 2 THEN ' AND a.codsubunit = t.codsubunit' ELSE '' END||'
    WHERE (COALESCE(t.pmp, 0) &lt;&gt; COALESCE(a.pmp, 0) OR COALESCE(t.pmpvaluta, 0) &lt;&gt; COALESCE(a.pmpvaluta, 0))
  ) AS updates
  WHERE j.coddoc = updates.codies AND j.tipdoc = updates.tipdoc';

  -- update livr1
  EXECUTE 'UPDATE livr1 l
  SET pmp = a.pmp, pmpvaluta = a.pmpvaluta
  FROM tmp_pmp_act_luna t INNER JOIN tmp_pmp a ON a.codobiect = t.codobiect'||CASE WHEN Tip = 2 THEN ' AND a.codsubunit = t.codsubunit' ELSE '' END||'
  WHERE l.codlivr1 = t.codlivr1 AND (COALESCE(t.pmp, 0) &lt;&gt; COALESCE(a.pmp, 0) OR COALESCE(t.pmpvaluta, 0) &lt;&gt; COALESCE(a.pmpvaluta, 0))';

  -- update jurnal1 afectare de modificarile in livr1
  EXECUTE 'UPDATE jurnal1 j
  SET dirty = 1
  FROM (
    SELECT DISTINCT E.codies, E.tipDoc
    FROM tmp_pmp_act_luna t
      INNER JOIN tmp_pmp a   ON a.codobiect     = t.codobiect'||CASE WHEN Tip = 2 THEN ' AND a.codsubunit = t.codsubunit' ELSE '' END||'
      INNER JOIN LIVR1   L1  ON l1.codlivr1     = t.codlivr1
      INNER JOIN IESLINK LK  ON LK.Codlinieaviz = L1.CodIes1
      INNER JOIN IESIRI1 E1  ON E1.CODIES1      = LK.Codies1
      INNER JOIN IESIRI  E   ON E. CODIES       = E1.Codies
      INNER JOIN IESIRI1 EE1 ON EE1.CODIES1     = L1.Codies1
      INNER JOIN IESIRI  EE  ON EE. CODIES      = EE1.Codies
    WHERE EE.TipDoc = 20 AND EE.Custodie = 1 AND (COALESCE(t.pmp, 0) &lt;&gt; COALESCE(a.pmp, 0) OR COALESCE(t.pmpvaluta, 0) &lt;&gt; COALESCE(a.pmpvaluta, 0))
  ) AS updates
  WHERE j.coddoc = updates.codies AND j.tipdoc = updates.tipdoc';
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_postcalcul_sp_deleterecord</obj_name>
  <obj_hashval>5e0f0f1c70e5d3dc0138848f20af4a8b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_postcalcul_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC          RECORD;
  V_REC_JURN_SUB RECORD;
  sJob           varchar;
begin
  PERFORM PKG_GLOBALS_MarkDirtyJurnal();
  PERFORM PKG_POSTCALCUL_SP_LOCKRECORD( RecId);

  FOR V_REC IN (SELECT * FROM JURNAL WHERE CODDOC = RecID AND  TIPDOC = 72) LOOP
    UPDATE NCONTRUL
    SET
    RULAJCD  = RULAJCD  - V_REC.VALOARE,
    RULAJVCD = RULAJVCD - V_REC.VALOAREV
    WHERE
     CODCONT = V_REC.CONTD AND  AN = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') AND  LUNA = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999');

    FOR V_REC_JURN_SUB IN (SELECT * FROM NCONTRUL WHERE CODCONT = V_REC.CONTD AND  AN = V_REC.AN AND  LUNA = V_REC.LUNA) LOOP
      UPDATE NCONTRULSUB
      SET
      RULAJCD  = RULAJCD  - V_REC.VALOARE,
      RULAJVCD = RULAJVCD - V_REC.VALOAREV
      WHERE
       CODCONTRUL = V_REC_JURN_SUB.CODCONTRUL AND  SUBUNITATEA = V_REC.SUBUNITATEA;
    END LOOP;

    UPDATE NCONTRUL
    SET
    RULAJCC  = RULAJCC  - V_REC.VALOARE,
    RULAJVCC = RULAJVCC - V_REC.VALOAREV
    WHERE
     CODCONT = V_REC.CONTC AND  AN = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') AND  LUNA = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999');

    FOR V_REC_JURN_SUB IN (SELECT * FROM NCONTRUL WHERE CODCONT = V_REC.CONTC AND  AN = V_REC.AN AND  LUNA = V_REC.LUNA) LOOP
      UPDATE NCONTRULSUB
      SET
      RULAJCC  = RULAJCC  - V_REC.VALOARE,
      RULAJVCC = RULAJVCC - V_REC.VALOAREV
      WHERE
       CODCONTRUL = V_REC_JURN_SUB.CODCONTRUL AND  SUBUNITATEA = V_REC.SUBUNITATEA;
    END LOOP;
  END LOOP;

  DELETE FROM JURNAL   WHERE CODDOC = RecID AND  TIPDOC = 72;
  DELETE FROM JURNAL1  WHERE CODDOC = RecID AND  TIPDOC = 72;
  DELETE FROM PCGEST   WHERE CODPC  = RecId;
  DELETE FROM PCART    WHERE CODPC  = RecId;
  DELETE FROM PCDIR    WHERE CODPC  = RecId;
  DELETE FROM PCSECTII WHERE CODPC  = RecId;
  DELETE FROM PCALCUL  WHERE CODPC  = RecId;

  PERFORM NotifyModif( 2, RecId, 'PCALCUL');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_postcalcul_sp_insertrecord</obj_name>
  <obj_hashval>353308d1f0811f32bfb142cdb12df811</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_postcalcul_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Subunit numeric;
  AnLuna  numeric;
  aAn     numeric;
  aLuna   numeric;
begin
  INSERT INTO TMP_PCALCUL (CODPC) VALUES (0);

  aAn     := current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric;
  aLuna   := current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric;
  AnLuna  := aAn * 12 + aLuna;
  Subunit := current_setting ('PKG_GLOBALS.SUBUNITATE_DOC', true) ::numeric;
  PERFORM PKG_POSTCALCUL_GET_PCSECTII_1 (ANLuna, Subunit);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_postcalcul_updatefinala</obj_name>
  <obj_hashval>18d2be36f02108e0f7ed3347ec083339</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_postcalcul_updatefinala(INOUT wme_result boolean, INOUT acodpc numeric, INOUT aoperat numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  Done BOOLEAN;
begin
  BEGIN
    UPDATE PCALCUL SET OPERAT = aOperat WHERE codPC = aCodPC;
    Done := True;
  EXCEPTION WHEN others THEN
    Done := False;
  END;

  WME_Result :=  Done;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_postretail_checkartdeleted</obj_name>
  <obj_hashval>86b9ae310a6ab24c1a8592cf617d5715</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_postretail_checkartdeleted()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  NR1 numeric := 0;
  NR2 numeric := 0;
  NR3 numeric := 0;
  NR4 numeric := 0;
BEGIN
  --Florin 18.01.2023 - fixat 56787
  --Florin 17.11.2022 - sinc. Oracle
  FOR V_REC IN (SELECT CODOBIECT, O.CODARTICOL FROM TMP_NARTDELETED D, NARTOBJ O WHERE O.CODARTICOL = D.CODARTICOL) LOOP
    SELECT COUNT(*) INTO NR1 FROM EMULARE1 WHERE CODOBIECT = V_REC.CODOBIECT;
    SELECT COUNT(*) INTO NR2 FROM RESTCMD1 WHERE CODOBIECT = V_REC.CODOBIECT;
    SELECT COUNT(*) INTO NR3 FROM RESTNP1   WHERE CODOBIECT = V_REC.CODOBIECT;
    SELECT COUNT(*) INTO NR4 FROM IESIRI1  WHERE CODOBIECT = V_REC.CODOBIECT;

    IF  NR1 + NR2 + NR3 + NR4 = 0 THEN
      DELETE FROM RESTARTINACTIVE WHERE CODOBIECT = V_REC.CODOBIECT;
      DELETE FROM NARTOBJ1        WHERE CODOBIECT = V_REC.CODOBIECT;
      DELETE FROM PRETM           WHERE CODOBIECT = V_REC.CODOBIECT;
      DELETE FROM NATROBJ         WHERE CODOBIECT = V_REC.CODOBIECT;
      DELETE FROM NARTOBJ         WHERE CODOBIECT = V_REC.CODOBIECT;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT D.CODARTICOL
  FROM
   TMP_NARTDELETED  D,
   NART A
  WHERE
   D.CODARTICOL = A.CODARTICOL
  )
  LOOP
    SELECT COUNT( *) INTO NR1 FROM NARTOBJ WHERE CODARTICOL = V_REC.CODARTICOL;
    IF NR1 = 0 THEN
      DELETE FROM NART1         WHERE CODARTICOL = V_REC.CODARTICOL;
      DELETE FROM NARTIMPLICITE WHERE CODARTICOL = V_REC.CODARTICOL;
      DELETE FROM NARTATR       WHERE CODARTICOL = V_REC.CODARTICOL;
      DELETE FROM NART          WHERE CODARTICOL = V_REC.CODARTICOL;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_postretail_checkfuzgest</obj_name>
  <obj_hashval>2f104f9db9a2b4bdb57d49340b9e4fee</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_postretail_checkfuzgest()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN (SELECT F.CODGESTINIT AS CODGEST_OLD, F.CODGESTFIN AS CODGEST_NEW FROM TMP_FUZGEST F) LOOP
    UPDATE EMULARE1          SET CODGEST       = V_REC.CODGEST_NEW WHERE CODGEST       = V_REC.CODGEST_OLD;
    UPDATE RESTCMD1          SET CODGEST       = V_REC.CODGEST_NEW WHERE CODGEST       = V_REC.CODGEST_OLD;
    UPDATE RESTGESTIMPLICITE SET GESTIMPLICITA = V_REC.CODGEST_NEW WHERE GESTIMPLICITA = V_REC.CODGEST_OLD;
    UPDATE NAGENDA           SET CODGEST       = V_REC.CODGEST_NEW WHERE CODGEST       = V_REC.CODGEST_OLD;
  END LOOP;

  FOR V_REC IN (SELECT F.CODGESTINIT AS CODGEST_OLD, F.CODGESTFIN AS CODGEST_NEW FROM TMP_FUZGEST F) LOOP
    DELETE FROM NGEST1 WHERE CODGEST = V_REC.CODGEST_OLD;
    DELETE FROM NGEST  WHERE CODGEST = V_REC.CODGEST_OLD;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_postretail_checkfuzionari</obj_name>
  <obj_hashval>77ee2258e29fabfda9287900b4ce6f7b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_postretail_checkfuzionari()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN (SELECT O_OLD.CODOBIECT AS CODOBIECT_OLD, O_OLD.CODARTICOL AS CODARTICOL_OLD, O_NEW.CODOBIECT AS CODOBIECT_NEW, O_NEW.CODARTICOL AS CODARTICOL_NEW
                FROM NARTOBJ O_OLD, NARTOBJ O_NEW, TMP_FUZART F
                WHERE O_OLD.CODARTICOL = F.CODARTINIT AND  O_NEW.CODARTICOL = F.CODARTFIN
               )
  LOOP
    UPDATE EMULARE1          SET CODOBIECT = V_REC.CODOBIECT_NEW WHERE CODOBIECT = V_REC.CODOBIECT_OLD;
    UPDATE IESIRI1RETAIL   SET CODOBIECT = V_REC.CODOBIECT_NEW WHERE CODOBIECT = V_REC.CODOBIECT_OLD;
    UPDATE RESTCMD1          SET CODOBIECT = V_REC.CODOBIECT_NEW WHERE CODOBIECT = V_REC.CODOBIECT_OLD;
    UPDATE RESTARTINACTIVE   SET CODOBIECT = V_REC.CODOBIECT_NEW WHERE CODOBIECT = V_REC.CODOBIECT_OLD;
    UPDATE RESTGESTIMPLICITE SET CODOBIECT = V_REC.CODOBIECT_NEW WHERE CODOBIECT = V_REC.CODOBIECT_OLD;
    UPDATE RESTNP1           SET CODOBIECT = V_REC.CODOBIECT_NEW WHERE CODOBIECT = V_REC.CODOBIECT_OLD;
    UPDATE IESIRI1           SET CODOBIECT = V_REC.CODOBIECT_NEW WHERE CODOBIECT = V_REC.CODOBIECT_OLD;
  END LOOP;

  FOR V_REC IN (SELECT O_OLD.CODOBIECT AS CODOBIECT_OLD, O_OLD.CODARTICOL AS CODARTICOL_OLD, O_NEW.CODOBIECT AS CODOBIECT_NEW, O_NEW.CODARTICOL AS CODARTICOL_NEW
                FROM NARTOBJ O_OLD, NARTOBJ O_NEW, TMP_FUZART F
                WHERE O_OLD.CODARTICOL = F.CODARTINIT AND  O_NEW.CODARTICOL = F.CODARTFIN
               )
  LOOP
    DELETE FROM NARTOBJ1      WHERE CODOBIECT  = V_REC.CODOBIECT_OLD;
    DELETE FROM PRETM         WHERE CODOBIECT  = V_REC.CODOBIECT_OLD;
    DELETE FROM NATROBJ       WHERE CODOBIECT  = V_REC.CODOBIECT_OLD;
    DELETE FROM NARTOBJ       WHERE CODOBIECT  = V_REC.CODOBIECT_OLD;
    DELETE FROM NART1         WHERE CODARTICOL = V_REC.CODARTICOL_OLD;
    DELETE FROM NARTIMPLICITE WHERE CODARTICOL = V_REC.CODARTICOL_OLD;
    DELETE FROM NART          WHERE CODARTICOL = V_REC.CODARTICOL_OLD;
  END LOOP;

  BEGIN
    FOR V_REC IN (SELECT CODOBIECT, CODRESTAURANT, COUNT( *) FROM RESTARTINACTIVE GROUP BY CODOBIECT, CODRESTAURANT) LOOP
      DELETE FROM RESTARTINACTIVE
      WHERE  CODOBIECT = V_REC.CODOBIECT AND  CODRESTAURANT = V_REC.CODRESTAURANT
        AND  COD &gt; (SELECT MIN( COD) FROM RESTARTINACTIVE WHERE CODOBIECT = V_REC.CODOBIECT AND  CODRESTAURANT = V_REC.CODRESTAURANT);
    END LOOP;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_postretail_checkfuzionaripart</obj_name>
  <obj_hashval>1037362d1193680d50fec62038c4c313</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_postretail_checkfuzionaripart()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  CODSEDIU_R_OLD NUMERIC;
  CODSEDIU_R_NEW NUMERIC;
BEGIN
  --Florin 28.06.2023 - sinc. Oracle (28.06.2023)
  --Florin 16.06.2023 - sinc. Oracle (14.06.2023)
  --Florin 28.12.2021 - sinc. Oracle
  FOR V_REC IN -- fuzionare parteneri
    (SELECT F.CODPARTINIT AS CODPART_OLD, F.CODPARTFIN AS CODPART_NEW FROM TMP_FUZPART F WHERE CODPARTINIT &lt;&gt; CODPARTFIN) LOOP
      UPDATE EMULARE SET CODPART = V_REC.CODPART_NEW WHERE CODPART = V_REC.CODPART_OLD;
      UPDATE RESTNP  SET CODPART = V_REC.CODPART_NEW WHERE CODPART = V_REC.CODPART_OLD;
      UPDATE IESIRI SET PARTENER = V_REC.CODPART_NEW WHERE PARTENER = V_REC.CODPART_OLD;

      DELETE FROM NPART1      WHERE CODPART = V_REC.CODPART_OLD;
      DELETE FROM NPART       WHERE CODPART = V_REC.CODPART_OLD;
      DELETE FROM NPARTRETAIL WHERE CODPART = V_REC.CODPART_OLD;
  END LOOP;

  FOR V_REC IN -- fuzionare sedii
    (SELECT F.CODLOCINIT AS CODLOCATIE_OLD, F.CODLOCFIN AS CODLOCATIE_NEW
    from TMP_FUZPART F where CODPARTINIT = CODPARTFIN AND COALESCE(CODLOCINIT, 0) &lt;&gt; COALESCE(CODLOCFIN, 0)
    AND COALESCE(CODLOCINIT, 0) &gt; 0 ORDER BY DATA)
    LOOP
      UPDATE EMULARE set CODLOCATIE = V_REC.CODLOCATIE_NEW where CODLOCATIE = V_REC.CODLOCATIE_OLD;
      UPDATE IESIRI set CODLOCATIE = V_REC.CODLOCATIE_NEW where CODLOCATIE = V_REC.CODLOCATIE_OLD;
      BEGIN
        SELECT MIN(CODSEDIU) INTO CODSEDIU_R_OLD FROM NSEDIIPARTRETAIL  WHERE CODAGENDA = v_rec.codlocatie_old;
        EXCEPTION WHEN OTHERS THEN CODSEDIU_R_OLD := 0;
      END;
      BEGIN
        SELECT MIN(CODSEDIU) INTO CODSEDIU_R_NEW FROM NSEDIIPARTRETAIL  WHERE CODAGENDA = v_rec.codlocatie_new;
        EXCEPTION WHEN OTHERS THEN CODSEDIU_R_NEW := 0;
      END;
      IF COALESCE(CODSEDIU_R_OLD, 0) &lt;&gt; 0 AND COALESCE(CODSEDIU_R_NEW, 0) &lt;&gt; 0 THEN
        UPDATE EMULARE set codsediuretail = CODSEDIU_R_NEW where codsediuretail = CODSEDIU_R_OLD;
        UPDATE IESIRIRETAIL set codsediuretail = CODSEDIU_R_NEW where codsediuretail = CODSEDIU_R_OLD;
      END IF;
      DELETE FROM NSEDIIPARTRETAIL where CODAGENDA =  V_REC.CODLOCATIE_OLD;
      DELETE FROM NAGENDA where CODAGENDA =  V_REC.CODLOCATIE_OLD;
    END LOOP;

  -- stergeri manuale pe baza, care nu provin din fuzionari
  FOR V_REC IN (SELECT * FROM NSEDIIPARTRETAIL WHERE COALESCE(CODAGENDA, 0) &gt; 0 AND COALESCE(CODAGENDA, 0) NOT IN (SELECT CODAGENDA FROM NAGENDA))
  LOOP
    UPDATE IESIRIRETAIL
    SET
      codsediuretail = NULL
    WHERE
      codsediuretail = V_REC.CODSEDIU;

    UPDATE EMULARE
    SET
      codsediuretail = NULL
    WHERE
      codsediuretail = V_REC.CODSEDIU;


    DELETE FROM NSEDIIPARTRETAIL
    WHERE
      CODSEDIU = V_REC.CODSEDIU;
  END LOOP;

  -- curata incoerente;
   FOR V_REC IN (SELECT SP.* FROM NSEDIIPARTRETAIL SP INNER JOIN NPARTRETAIL P ON P.CODPARTRETAIL = SP.CODPARTRETAIL AND P.TIPMODIF IS NULL AND SP.CODAGENDA IS NULL)
   LOOP
      UPDATE IESIRIRETAIL
      SET
        codsediuretail = NULL
      WHERE
        codsediuretail = V_REC.CODSEDIU;

      UPDATE EMULARE
      SET
        codsediuretail = NULL
      WHERE
        codsediuretail = V_REC.CODSEDIU;

    DELETE FROM NSEDIIPARTRETAIL
    WHERE
      CODSEDIU = V_REC.CODSEDIU;
   END LOOP;

    FOR V_REC IN (SELECT SP.* FROM NSEDIIPARTRETAIL SP WHERE codpartretail not in (select CODPARTRETAIL FROM NPARTRETAIL ) )
    LOOP
      UPDATE IESIRIRETAIL
      SET
        codsediuretail = NULL
      WHERE
        codsediuretail = V_REC.CODSEDIU;

      UPDATE EMULARE
      SET
        codsediuretail = NULL
      WHERE
        codsediuretail = V_REC.CODSEDIU;

      DELETE FROM NCODFISCRETAIL
      WHERE
        codPartRetail = V_REC.CODPARTRETAIL;

      DELETE FROM NSEDIIPARTRETAIL
      WHERE
        CODSEDIU = V_REC.CODSEDIU;
    END LOOP;

    for v_rec in (select * from npartretail where codpart is not null and codpart not in (select codpart from npart))
    LOOP
      UPDATE IESIRIRETAIL
      SET
        codpartretail = NULL
      WHERE
        codPartRetail = V_REC.CODPARTRETAIL;

      UPDATE EMULARE
      SET
        codpartretail = NULL
      WHERE
        codPartRetail = V_REC.CODPARTRETAIL;

      DELETE FROM NCODFISCRETAIL
      WHERE
        codPartRetail = V_REC.CODPARTRETAIL;

      DELETE FROM NPARTRETAIL
      WHERE
        codPartRetail = V_REC.CODPARTRETAIL;
    END LOOP;

END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_postretail_checkfuzlocalit</obj_name>
  <obj_hashval>aa8875593df1f043be8e98075854c8c8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_postretail_checkfuzlocalit()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN (SELECT F.CODLOCALITINIT AS CODLOCALIT_OLD, F.CODLOCALITFIN AS CODLOCALIT_NEW FROM TMP_FUZLOCALIT F) LOOP
    UPDATE NAGENDA          SET CODLOCALIT = V_REC.CODLOCALIT_NEW WHERE CODLOCALIT = V_REC.CODLOCALIT_OLD;
    UPDATE NSEDIIPARTRETAIL SET CODLOCALIT = V_REC.CODLOCALIT_NEW WHERE CODLOCALIT = V_REC.CODLOCALIT_OLD;
  END LOOP;

  FOR V_REC IN (SELECT F.CODLOCALITINIT AS CODLOCALIT_OLD, F.CODLOCALITFIN AS CODLOCALIT_NEW FROM TMP_FUZLOCALIT F) LOOP
    DELETE FROM NLOCALIT WHERE CODLOCALIT = V_REC.CODLOCALIT_OLD;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_postretail_getsintezastoc</obj_name>
  <obj_hashval>6dad39fe968e2a251aa86c439144767b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_postretail_getsintezastoc()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC_N  RECORD;
  V_REC_NS RECORD;
  aCODNIR  numeric;
begin
  DELETE FROM NIRSTOC;
  DELETE FROM NIR;

  FOR V_REC_N IN (SELECT  DISTINCT CODGESTPROD FROM TMP_NIRSTOC_MAN) LOOP
    aCODNIR := NEXTVAL('SEQ_NIR_CODNIR');
    INSERT INTO NIR(CODNIR, GEST, OPERAT)
    VALUES(aCODNIR, V_REC_N.CODGESTPROD, 1);

    FOR V_REC_NS IN (SELECT * FROM TMP_NIRSTOC_MAN WHERE CODGESTPROD = V_REC_N.CODGESTPROD) LOOP
      INSERT INTO NIRSTOC(CODNIRSTOC, CODNIR, CODOBIECT, CODIOART, REST)
      VALUES(NEXTVAL('SEQ_NIRSTOC_CODNIRSTOC'), aCODNIR, V_REC_NS.CODOBIECT, V_REC_NS.CODIOART, V_REC_NS.REST);
    END LOOP;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_postretail_memo_modif_pret_retail</obj_name>
  <obj_hashval>4e2c74e6991399930794ab6356a4c92e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_postretail_memo_modif_pret_retail(acodobiect numeric, acodsubunit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC    RECORD;
  aCODSYNC numeric;
BEGIN
  --Florin 19.08.2022 - sinc. Oracle (18.08.2022)
  --Florin 24.05.2022 - sinc. Oracle
  --Bogdan 07.04.2022 PG - Intrari: modificari de pret in syncpretretail
  FOR V_REC IN (SELECT P.COD AS CODPOSTRETAIL, O.CODOBIECT, PM.LEI AS PRETNOU, PM.CODCATPRET
                FROM POSTRETAIL P, PRETM PM, NARTOBJ O, NART A, NCATPRET CP
                WHERE  PM.SUBUNITATEA = aCodSubunit AND  P.SUBUNITATEA = aCODSUBUNIT AND  PM.CODOBIECT = aCODOBIECT
                  AND  O.CODOBIECT = aCODOBIECT AND  A.CODARTICOL = O.CODARTICOL AND  COALESCE( A.CASADEMARCAT, 0) = 1
                  AND  PM.CODCATPRET = CP.CODCATPRET AND CP.TIP IN (1, 2)
               )
  LOOP
    BEGIN
      SELECT CODSYNC INTO STRICT aCODSYNC FROM SYNCPRETRETAIL WHERE CODPOSTRETAIL = V_REC.CODPOSTRETAIL AND  CODOBIECT = V_REC.CODOBIECT AND  CODCATPRET = V_REC.CODCATPRET;
    EXCEPTION WHEN OTHERS THEN
      aCODSYNC := 0;
    END;

    IF  aCODSYNC = 0 THEN
      INSERT INTO SYNCPRETRETAIL(CODSYNC, CODPOSTRETAIL, CODOBIECT, CODCATPRET, PRETNOU, DATA, SINCRONIZAT)
      VALUES(NEXTVAL('SEQ_SYSNPRETRETAIL_CODSYNC'), V_REC.CODPOSTRETAIL, V_REC.CODOBIECT, V_REC.CODCATPRET, V_REC.PRETNOU, CURRENT_TIMESTAMP, 0);
    ELSE
      UPDATE SYNCPRETRETAIL
      SET
      PRETNOU     = V_REC.PRETNOU,
      DATA        = CURRENT_TIMESTAMP,
      SINCRONIZAT = 0
      WHERE
       CODSYNC = aCODSYNC AND PRETNOU &lt;&gt; V_REC.PRETNOU;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_postretail_memo_modif_promo_retail</obj_name>
  <obj_hashval>fc5a7001cabee040b775f339b61d4d32</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_postretail_memo_modif_promo_retail(acodpromo numeric, atipmodif numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
V_REC RECORD;
begin
FOR V_REC IN
(
SELECT COD
FROM POSTRETAIL
)
LOOP
INSERT INTO SYNCPROMORETAIL
(
CODSYNCPROMO, CODPROMO, CODPOSTRETAIL, SINCRONIZAT, DATA, TIPMODIF
)
VALUES
(
NEXTVAL('SEQ_SYNCPROMORETAIL_CODSYNC'), aCODPROMO, V_REC.COD, 0, CURRENT_TIMESTAMP, aTIPMODIF
);
END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_postretail_post_monetare_retail</obj_name>
  <obj_hashval>b531ad02e2efa729de5cf7b83d995a36</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_postretail_post_monetare_retail()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  DELETE FROM GENMONETARERETAIL WHERE CODPOSTRETAIL IN (SELECT CODPOSTRETAIL FROM TMP_GENMONETARERETAIL);

  FOR V_REC IN (SELECT * FROM TMP_GENMONETARERETAIL) LOOP
    UPDATE GENMONETARERETAIL
    SET
    (CARNETDOC, CARNETLIVR, CARNETCMD, CARNETNP, CARNETBC, CARNETNIR, CONTINTERMED, CONTCASH, CONTCEC, CONTCARD, CONTTICHET, DESCARCAREPROD)
    =
    (SELECT V_REC.CARNETDOC, V_REC.CARNETLIVR, V_REC.CARNETCMD, V_REC.CARNETNP, V_REC.CARNETBC, V_REC.CARNETNIR, V_REC.CONTINTERMED, V_REC.CONTCASH, V_REC.CONTCEC, V_REC.CONTCARD, V_REC.CONTTICHET, V_REC.DESCARCAREPROD)
    WHERE
     CODPOSTRETAIL = V_REC.CODPOSTRETAIL;

    IF NOT FOUND THEN
      INSERT INTO GENMONETARERETAIL(CODPOSTRETAIL, CARNETDOC, CARNETLIVR, CARNETCMD, CARNETNP, CARNETBC, CARNETNIR, CONTINTERMED, CONTCASH, CONTCEC, CONTCARD, CONTTICHET, DESCARCAREPROD)
      VALUES(V_REC.CODPOSTRETAIL, V_REC.CARNETDOC, V_REC.CARNETLIVR, V_REC.CARNETCMD, V_REC.CARNETNP, V_REC.CARNETBC, V_REC.CARNETNIR, V_REC.CONTINTERMED, V_REC.CONTCASH, V_REC.CONTCEC, V_REC.CONTCARD, V_REC.CONTTICHET, V_REC.DESCARCAREPROD);
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_postretail_preia_sinteza_emulare</obj_name>
  <obj_hashval>0089745aa3540ff7bd78cbe4049858d2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_postretail_preia_sinteza_emulare(acodpostretail numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  ER_REC  RECORD;
  ER1_REC RECORD;
  V_REC   RECORD;
  ER2     RECORD;
begin
  --Bogdan 27.01.2021


  FOR V_REC IN
  (
   SELECT CODSINTEZA
   FROM SINTEZAEMULARE S, TMP_EMULARE E
   WHERE
     S.CODPOSTRETAIL = aCODPOSTRETAIL AND  S.CODEMULARE = E.CODEMULARE
  )
  LOOP
   DELETE FROM SINTEZAEMULARE2
   WHERE
    CODSINTEZA = V_REC.CODSINTEZA;
    DELETE FROM SINTEZAEMULARE1
    WHERE
      CODSINTEZA = V_REC.CODSINTEZA;
   DELETE FROM SINTEZAEMULARE
   WHERE
     CODSINTEZA = V_REC.CODSINTEZA;
  END LOOP;




  FOR ER_REC IN (SELECT E.* FROM EMULARERETAIL E WHERE E.CODPOSTRETAIL = aCODPOSTRETAIL) LOOP
    UPDATE SINTEZAEMULARE SE
    SET
      NRBON           = ER_REC.NRBON,
      DATABON         = ER_REC.DATABON,
      VALOARE         = ER_REC.VALOARE,
      VALOAREDISCOUNT = ER_REC.VALOAREDISCOUNT,
      LISTAT          = ER_REC.LISTAT,
      PRELUAT         = ER_REC.PRELUAT,
      CODCASAMARCAT   = ER_REC.CODCASAMARCAT,
      TVATOTAL        = ER_REC.TVATOTAL,
      TVADISCOUNT     = ER_REC.TVADISCOUNT,
      DATACREARE      = ER_REC.DATACREARE,
      DATALISTARE     = ER_REC.DATALISTARE,
      CODIES          = ER_REC.CODIES,
      CODPART         = ER_REC.CODPART,
      CODPERS         = ER_REC.CODPERS,
      CODLOCATIE      = ER_REC.CODLOCATIE,
      CODAGENT        = ER_REC.CODAGENT,
      OBS             = ER_REC.OBS,
      IDBON           = ER_REC.IDBON,
      DELEGAT         = DELEGAT
    WHERE
      SE.CODEMULARE = ER_REC.CODEMULARE AND SE.CODPOSTRETAIL = ER_REC.CODPOSTRETAIL;

    IF NOT FOUND THEN
      INSERT INTO SINTEZAEMULARE AS SE (CODSINTEZA, CODEMULARE, NRBON, DATABON,
          VALOARE, VALOAREDISCOUNT, LISTAT, PRELUAT,
          CODCASAMARCAT, TVATOTAL, TVADISCOUNT, DATACREARE,
          DATALISTARE, CODIES, CODPART, CODPERS,
          CODPOSTRETAIL, CODLOCATIE, CODAGENT, OBS,
          IDBON, DELEGAT)
        VALUES (NEXTVAL ('SEQ_SINTEZAEMULARE_CODSINTEZA') , ER_REC.CODEMULARE, ER_REC.NRBON, ER_REC.DATABON,
          ER_REC.VALOARE, ER_REC.VALOAREDISCOUNT, ER_REC.LISTAT, ER_REC.PRELUAT,
          ER_REC.CODCASAMARCAT, ER_REC.TVATOTAL, ER_REC.TVADISCOUNT, ER_REC.DATACREARE,
          ER_REC.DATALISTARE, ER_REC.CODIES, ER_REC.CODPART, ER_REC.CODPERS,
          ER_REC.CODPOSTRETAIL, ER_REC.CODLOCATIE, ER_REC.CODAGENT, ER_REC.OBS,
          ER_REC.IDBON, ER_REC.DELEGAT);
    END IF;
  END LOOP;

  FOR ER1_REC IN (SELECT E1.*, S.CODSINTEZA, E.CODPOSTRETAIL AS CODPOST_RETAIL
                  FROM EMULARE1RETAIL E1, EMULARERETAIL E, SINTEZAEMULARE S
                  WHERE
                    E.CODPOSTRETAIL = aCODPOSTRETAIL
                    AND E.CODEMULARE = E1.CODEMULARE
                    AND E1.CODPOSTRETAIL = aCODPOSTRETAIL
                    AND S.CODEMULARE = E.CODEMULARE
                    AND S.CODPOSTRETAIL = E.CODPOSTRETAIL)
  LOOP
    UPDATE SINTEZAEMULARE1 SE1
    SET
      CODOBIECT  = ER1_REC.CODOBIECT,
      INDEXLOCAL = ER1_REC.INDEXLOCAL,
      PRETART    = ER1_REC.PRETART,
      PRET       = ER1_REC.PRET,
      CANT       = ER1_REC.CANT,
      UMSEC      = ER1_REC.UMSEC,
      DISCOUNT   = ER1_REC.DISCOUNT,
      TVA        = ER1_REC.TVA,
      TIPLINIE   = ER1_REC.TIPLINIE,
      CONTSERV   = ER1_REC.CONTSERV,
      CADOU      = ER1_REC.CADOU,
      PRETPROMO  = ER1_REC.PRETPROMO
    WHERE
      SE1.CODEMULARE1 = ER1_REC.CODEMULARE1 AND SE1.CODPOSTRETAIL = ER1_REC.CODPOST_RETAIL;

    IF NOT FOUND THEN
      INSERT INTO SINTEZAEMULARE1 AS SE1 (CODSINTEZA1, CODSINTEZA, CODEMULARE1, CODPOSTRETAIL,
          CODOBIECT, INDEXLOCAL, PRETART, PRET,
          CANT, UMSEC, DISCOUNT, TVA,
          TIPLINIE, CONTSERV, CADOU, PRETPROMO)
        VALUES (NEXTVAL ('SEQ_SINTEZAEMUL1_CODSINTEZA1') , ER1_REC.CODSINTEZA, ER1_REC.CODEMULARE1, ER1_REC.CODPOSTRETAIL,
          ER1_REC.CODOBIECT, ER1_REC.INDEXLOCAL, ER1_REC.PRETART, ER1_REC.PRET,
          ER1_REC.CANT, ER1_REC.UMSEC, ER1_REC.DISCOUNT, ER1_REC.TVA,
          ER1_REC.TIPLINIE, ER1_REC.CONTSERV, ER1_REC.CADOU, ER1_REC.PRETPROMO);
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT *
                FROM (SELECT S.CODSINTEZA, ER.CODEMULARE, S1.CODSINTEZA1, ER1.CODEMULARE1
                      FROM EMULARERETAIL ER, SINTEZAEMULARE S, SINTEZAEMULARE1 S1
                        LEFT JOIN EMULARE1RETAIL ER1 ON ER1.CODEMULARE1 = S1.CODEMULARE1 AND ER1.CODPOSTRETAIL = aCODPOSTRETAIL
                      WHERE
                        ER.CODEMULARE = S.CODEMULARE
                        AND ER.CODPOSTRETAIL = aCODPOSTRETAIL
                        AND S.CODPOSTRETAIL = aCODPOSTRETAIL
                        AND S1.CODSINTEZA = S.CODSINTEZA) A_PG
                WHERE CODEMULARE1 IS NULL)
  LOOP
    DELETE FROM SINTEZAEMULARE1 WHERE CODSINTEZA1 = V_REC.CODSINTEZA1;
  END LOOP;

  FOR ER2 IN (SELECT E2.*, S.CODSINTEZA, E.CODPOSTRETAIL AS CODPOST_RETAIL
              FROM EMULARE2RETAIL E2, EMULARERETAIL E, SINTEZAEMULARE S
              WHERE
                E.CODPOSTRETAIL = aCODPOSTRETAIL
                AND E.CODEMULARE = E2.CODEMULARE
                AND S.CODEMULARE = E.CODEMULARE
                AND S.CODPOSTRETAIL = E.CODPOSTRETAIL)
  LOOP
    UPDATE SINTEZAEMULARE2 SE2
    SET
    TIPPLATA    = ER2.TIPPLATA,
    VALOARE     = ER2.VALOARE,
    DENUMIRE    = ER2.DENUMIRE,
    CODBANKCONT = ER2.CODBANKCONT
    WHERE
      SE2.CODEMULARE2 = ER2.CODEMULARE2 AND SE2.CODPOSTRETAIL = ER2.CODPOST_RETAIL;

    IF NOT FOUND THEN
      INSERT INTO SINTEZAEMULARE2 AS SE2 (CODSINTEZA2, CODSINTEZA, CODEMULARE2, CODPOSTRETAIL, TIPPLATA, VALOARE, DENUMIRE, CODBANKCONT)
      VALUES (NEXTVAL ('SEQ_SINTEZAEMUL2_CODSINTEZA2') , ER2.CODSINTEZA, ER2.CODEMULARE2, ER2.CODPOSTRETAIL, ER2.TIPPLATA, ER2.VALOARE, ER2.DENUMIRE, ER2.CODBANKCONT);
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_postretail_prepare_genmonetare_retail</obj_name>
  <obj_hashval>97bb40be39a8c0a6c11a865099650a5d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_postretail_prepare_genmonetare_retail(acodsubunit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  --Bogdan 27.01.2021
  DELETE FROM TMP_GENMONETARERETAIL;

  INSERT INTO TMP_GENMONETARERETAIL (CODPOSTRETAIL, CARNETDOC, CARNETLIVR, CARNETCMD,
      CARNETNP, CARNETBC, CARNETNIR, CONTINTERMED,
      CONTCASH, CONTCEC, CONTCARD, CONTTICHET,
      DESCARCAREPROD, DENUMIRE, ID, NUMEFIRMA,
      SUBUNITATEA, DEN_SUBUNIT)
  SELECT G.CODPOSTRETAIL, G.CARNETDOC, G.CARNETLIVR, G.CARNETCMD,
    G.CARNETNP, G.CARNETBC, G.CARNETNIR, G.CONTINTERMED,
    G.CONTCASH, G.CONTCEC, G.CONTCARD, G.CONTTICHET,
    G.DESCARCAREPROD, R.DENUMIRE, R.ID, R.NUMEFIRMA,
    R.SUBUNITATEA, S.DEN_SUBUNIT
  FROM GENMONETARERETAIL G, POSTRETAIL R, NSUBUNIT S
  WHERE
    G.CODPOSTRETAIL = R.COD AND R.SUBUNITATEA = S.CODSUBUNIT;

  FOR V_REC IN (SELECT R.*, S.DEN_SUBUNIT FROM POSTRETAIL R, NSUBUNIT S
                WHERE R.COD NOT IN (SELECT CODPOSTRETAIL FROM TMP_GENMONETARERETAIL) AND R.SUBUNITATEA = S.CODSUBUNIT)
  LOOP
    INSERT INTO TMP_GENMONETARERETAIL (CODPOSTRETAIL, DENUMIRE, ID, NUMEFIRMA, SUBUNITATEA, DEN_SUBUNIT)
    VALUES (V_REC.COD, V_REC.DENUMIRE, V_REC.ID, V_REC.NUMEFIRMA, V_REC.SUBUNITATEA, V_REC.DEN_SUBUNIT);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_postretail_sp_lockrecord</obj_name>
  <obj_hashval>6e1f3a5305fbb6328cbececb8da13376</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_postretail_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMP numeric := 0;
begin
  SELECT COD INTO Tmp FROM POSTRETAIL WHERE COD = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_postretail_sp_postrecords</obj_name>
  <obj_hashval>1a9cd686ce32691c352c552c8c95a0a0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_postretail_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  v_rec record;
begin
  --Florin 27.11.2025 - sinc. Oracle
  IF  Operation = 0 THEN
    SELECT COD INTO RecId FROM TMP_POSTRETAIL;

    UPDATE POSTRETAIL
    SET
    (DENUMIRE, ID, NUMEFIRMA, SUBUNITATEA) = (SELECT DENUMIRE, ID, NUMEFIRMA, SUBUNITATEA FROM TMP_POSTRETAIL)
    WHERE
     COD = RECID;

   DELETE FROM INACTIVRETAIL
     WHERE
       CODPOSTRETAIL = RECID
       AND CODOBIECT NOT IN (SELECT CODOBIECT FROM TMP_INACTIVRETAIL);


  FOR V_REC IN (SELECT * FROM TMP_INACTIVRETAIL)
   LOOP

     IF V_REC.CODINACTIVRETAIL &lt; 0 THEN
       INSERT INTO INACTIVRETAIL (CODINACTIVRETAIL, CODOBIECT, CODPOSTRETAIL)
       VALUES(NEXTVAL('SEQ_INACTIVRETAIL_CODINACTIV'), V_REC.CODOBIECT, V_REC.CODPOSTRETAIL);
     ELSE
       UPDATE INACTIVRETAIL
       SET
         CODOBIECT = V_REC.CODOBIECT
       WHERE
         CODINACTIVRETAIL = V_REC.CODINACTIVRETAIL;
     END IF;
   END LOOP;

  ELSE
    SELECT NEXTVAL('SEQ_POSTRETAIL_COD') INTO RECID;

    INSERT INTO POSTRETAIL(COD, DENUMIRE, ID, NUMEFIRMA, SUBUNITATEA)
    SELECT RECID, DENUMIRE, ID, NUMEFIRMA, SUBUNITATEA FROM TMP_POSTRETAIL;

    INSERT INTO INACTIVRETAIL (CODINACTIVRETAIL, CODOBIECT, CODPOSTRETAIL)
    SELECT NEXTVAL('SEQ_INACTIVRETAIL_CODINACTIV'), CODOBIECT, RecID
    FROM
      TMP_INACTIVRETAIL;
  END IF;

  PERFORM NotifyModif( Operation, RecId, 'POSTRETAIL');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_precomanda_ct_monitor</obj_name>
  <obj_hashval>ba1b33986f1ff54480438fc526e7b6db</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_precomanda_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_PRECOMANDA.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_70';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_precomanda_getcarnetdoc_i</obj_name>
  <obj_hashval>34273713a7f9aa2b4b6012bd2b628652</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_precomanda_getcarnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PRECOMANDA.CARNETDOC_I', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_precomanda_nrdoc_i</obj_name>
  <obj_hashval>ac64c3e525d67b16d0d18a60eced563d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_precomanda_nrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PRECOMANDA.NRDOC_I', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_precomanda_salveazaprecmd</obj_name>
  <obj_hashval>b6ff5936bb2413e983fd1eb56e473ba1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_precomanda_salveazaprecmd()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodPrecomanda numeric;
  aAn            numeric;
  aSet           numeric;
  aAnG           numeric;
  aSetG          numeric;
begin
  BEGIN
    SELECT codprecomanda
    INTO aCodPrecomanda
    FROM precomanda
    WHERE
           userid      = (SELECT pkg_globals_getuserid.WME_RESULT     FROM pkg_globals_getuserid(NULL,NULL))
      and  subunitatea = (SELECT pkg_globals_GETSUBUNITATE.WME_RESULT FROM pkg_globals_GETSUBUNITATE(NULL,NULL))
      and  anc = aAn and  saptamanac = aSet and  ang = aAnG and  saptamanag = aSetG;
  EXCEPTION WHEN others THEN
    aCodPrecomanda := 0;
  END;

  IF  aCodPrecomanda = 0 THEN
    SELECT NEXTVAL('SEQ_PRECOMANDA_CODPRECOMANDA') INTO aCodPrecomanda;

    INSERT INTO precomanda(codprecomanda, userid, subunitatea, anc, saptamanac, ang, saptamanag)
    SELECT aCodPreComanda, (SELECT pkg_globals_GETUSERID.WME_RESULT FROM pkg_globals_GETUSERID(NULL,NULL)), (SELECT pkg_globals_GETSUBUNITATE.WME_RESULT FROM pkg_globals_GETSUBUNITATE(NULL,NULL)), anc, saptamanac, ang, saptamanag
    FROM tmp_precomanda;
  END IF;

  DELETE FROM precomanda1 WHERE codprecomanda = acodprecomanda and codstare1 IN (SELECT CodStare1 FROM tmp_precomanda1);

  INSERT INTO PRECOMANDA1(codprecomanda1, codprecomanda, indexlocal, codobiect, umsec, pu, cant, rest, termen, addim, procdisc, obs, pretorig, coefdiscmaj, scadenta, d1, d2, d3, cantum1, codcontract1, codcentru, codoferta1, pretum1, codpart, codpromo1, moneda, codstare1, codlocatie, cantmin, datastart)
  SELECT NEXTVAL('SEQ_PRECOMANDA1_CODPRECOMANDA1'), aCodPrecomanda, indexlocal, codobiect, umsec, pu, cant, rest, termen, addim, procdisc, obs, pretorig, coefdiscmaj, scadenta, d1, d2, d3, cantum1, codcontract1, codcentru, codoferta1, pretum1, codpart, codpromo1, moneda, codstare1, codlocatie, cantmin, datastart
  FROM TMP_PRECOMANDA1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_precomanda_setcarnetdoc_i</obj_name>
  <obj_hashval>6967e044ac8c4f455594daf0a7e327bb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_precomanda_setcarnetdoc_i(acarnetdoc_i numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PRECOMANDA.CARNETDOC_I',to_char(aCARNETDOC_I,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_precomanda_setct_monitor</obj_name>
  <obj_hashval>fd019c674ab38ee933d83e3378542c84</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_precomanda_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PRECOMANDA.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_precomanda_setnrdoc_i</obj_name>
  <obj_hashval>a6a4240a69a5f99b47e4adf286ebb607</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_precomanda_setnrdoc_i(anrdoc numeric, acarnet numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PRECOMANDA.CARNETDOC_I',to_char(ACARNET,'999999999999999999'),false);
perform set_config('PKG_PRECOMANDA.NRDOC_I',to_char(ANRDOC,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_precomanda_sp_deleterecord</obj_name>
  <obj_hashval>87201afe60560f561c1db7e622a9f800</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_precomanda_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  ACARNETDOC  numeric;
  ANRDOC      numeric;
  aCodSubunit numeric;
  aDataDoc    date;
  aDoc        varchar;
BEGIN
  --Florin 01.06.2023 - monitor
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_precomanda_setct_monitor('MON_70');
  PERFORM PKG_PRECOMANDA_SP_LOCKRECORD( RecId);

  SELECT COALESCE( CARNETDOC, 0), NRDOC, SUBUNITATEA, DATADOC, PREFIXDOC || NRDOC || '/' DATADOC
  INTO ACARNETDOC, ANRDOC, aCodSubunit, aDataDoc, ADOC
  FROM PRECOMANDA WHERE CODPRECOMANDA = RECID;

  IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_PRECOMANDA.CT_MONITOR', true))))
  THEN
    PERFORM pkg_userfirme_postlogcucommit( 'PRECOMANDA', (current_setting('PKG_GLOBALS.USERNAME', true)), 'S', RECID, (current_setting('PKG_GLOBALS.FIRMANAME', true)), aCodSubunit, aDataDoc, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  DELETE FROM PRECMDLINK  WHERE CODPRECOMANDA1 IN (SELECT CODPRECOMANDA1 FROM PRECOMANDA1 WHERE CODPRECOMANDA = RECID);
  DELETE FROM PRECOMANDA1 WHERE CODPRECOMANDA = RECID;
  DELETE FROM PRECOMANDA  WHERE CODPRECOMANDA = RecId;

  IF  aCARNETDOC &lt;&gt; 0 THEN
    PERFORM PKG_CARNETEDOC_RELEASENUMARDOC( aCARNETDOC, aNRDOC);
    PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE( aCARNETDOC);
  END IF;

  PERFORM NotifyModif( 2, RecId, 'PRECOMANDA');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_precomanda_sp_gotorecord</obj_name>
  <obj_hashval>08335c5dfa9ca4c16c0ee8f3b327927b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_precomanda_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Florin 16.11.2021 - fixat 52001
  perform pkg_precomanda_setct_monitor('MON_70');
  INSERT INTO TMP_PRECOMANDA(codprecomanda, tipdoc, anulat, blocat, operat, prefixdoc, nrdoc, carnetdoc, datadoc, valoare, an, luna, obs, moneda, subunitatea, inchisa, seriadoc, verificat, codstare1)
  SELECT codprecomanda, tipdoc, anulat, blocat, operat, prefixdoc, nrdoc, carnetdoc, datadoc, valoare, an, luna, obs, moneda, subunitatea, inchisa, seriadoc, verificat, codstare1
  FROM PRECOMANDA WHERE CodPreComanda = RecId;

  INSERT INTO TMP_PRECOMANDA1(codprecomanda1, codprecomanda, indexlocal, codobiect, umsec, pu, cant, rest, termen, addim, procdisc, obs, pretorig, coefdiscmaj, scadenta, d1, d2, d3, cantum1, codcontract1, codcentru, codoferta1, pretum1, codpart, codpromo1, moneda, valoare, DENOBIECT, DENUM, DENUM1, CODEXTERN, CODINTERN, UM1, RELATIEUM1, PARITATE, ROTUNJIRE, promo, oferta, contract, codlocatie, cantmin, datastart)
  SELECT P1.codprecomanda1, P1.codprecomanda, P1.indexlocal, P1.codobiect, P1.umsec, P1.pu, P1.cant, P1.rest, P1.termen, P1.addim, P1.procdisc, P1.obs,
         P1.pretorig, P1.coefdiscmaj, P1.scadenta, P1.d1, P1.d2, P1.d3, P1.cantum1, P1.codcontract1, P1.codcentru, P1.codoferta1, P1.pretum1, P1.codpart,
         P1.codpromo1, P1.moneda, P1.cant * P1.pu, O.DENUMIRE, U1.DEN_UM1, UMSPEC.Den_Um, O.CODEXTERN, O.CODINTERN, A.UM1, A.RELATIEUM1, u1.Paritate, O.ROTVALUTA,
         CASE WHEN  PO.CODPROMO &gt; 0 THEN PO.NRDOC || '/' || TO_CHAR( PO.DATASTART, 'DD.MM.YYYY') || '-' || TO_CHAR( PO.DATAEND, 'DD.MM.YYYY')
              ELSE null
         END ,
         CASE WHEN  OFF.CODOFERTA &gt; 0 THEN OFF.NRDOC || '/' || TO_CHAR( OFF.DATASTART, 'DD.MM.YYYY') || '-' || TO_CHAR( OFF.DATAEND, 'DD.MM.YYYY')
              ELSE NULL
         END ,
         CASE WHEN  C.CODCONTRACT &gt; 0 THEN C.NRDOC || '/' || TO_CHAR( C.DATADOC, 'DD.MM.YYYY') ELSE NULL END ,
         p1.codlocatie, p1.cantmin, p1.datastart
  FROM PRECOMANDA1 p1
      INNER JOIN NARTOBJ   O      ON  P1.CODOBIECT    = O.CODOBIECT
      INNER JOIN NART      A      ON  O.CODARTICOL    = A.CODARTICOL
      LEFT  JOIN NUM1      u1     ON  u1.CodUM1       = p1.UmSec
      LEFT  JOIN NUM       UMSPEC ON  a.um1           = UMSPEC.CODUM
      LEFT  JOIN PROMO1    PO1    ON  P1.CODPROMO1    = PO1.CODPROMO1
      LEFT  JOIN PROMO     PO     ON  PO.CODPROMO     = PO1.CODPROMO
      LEFT  JOIN CONTRACT1 C1     ON  C1.CODCONTRACT1 = P1.CODCONTRACT1
      LEFT  JOIN CONTRACT  C      ON  C.CODCONTRACT   = C1.CODCONTRACT
      LEFT  JOIN OFERTA1   OF1    ON  P1.CODOFERTA1   = OF1.CODOFERTA1
      LEFT  JOIN OFERTA    OFF    ON  OFF.CODOFERTA   = OF1.CODOFERTA
  WHERE CodPreComanda = RecId
  ORDER BY IndexLocal ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_precomanda_sp_postrecords</obj_name>
  <obj_hashval>892c715b459ce82b097e8893f98ce477</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_precomanda_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  vCod        numeric;
  aOperat     NUMERIC := 0;
  aInchisa    NUMERIC := 0;
  aAnulat     NUMERIC := 0;
  aCARNETDOC  numeric;
  aNRDOC      numeric;
  aCodSubunit numeric;
  aDataDoc    date;
  aDoc        varchar;
BEGIN
  --Florin 01.06.2023 - monitor
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_precomanda_setct_monitor('MON_70');
  SELECT COALESCE( OPERAT, 0), COALESCE( INCHISA, 0), COALESCE( ANULAT, 0), COALESCE( CARNETDOC, 0), NRDOC, SUBUNITATEA, DATADOC, PREFIXDOC || NRDOC || '/' || DATADOC
  INTO aOperat, aInchisa, aAnulat, aCARNETDOC, aNRDOC, aCodSubunit, aDATADOC, ADOC
  FROM TMP_PRECOMANDA;

  IF  Operation = 0 THEN
    SELECT CodPreComanda INTO RecId FROM TMP_PRECOMANDA;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_PRECOMANDA.CT_MONITOR', true))))
    THEN
      PERFORM pkg_userfirme_postlogcucommit( 'PRECOMANDA', (current_setting('PKG_GLOBALS.USERNAME', true)), 'M', RECID, (current_setting('PKG_GLOBALS.FIRMANAME', true)), aCodSubunit, aDataDoc, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    UPDATE PRECOMANDA
    SET
    (tipdoc, anulat, blocat, operat, prefixdoc, nrdoc, carnetdoc, datadoc, valoare, an, luna, obs, moneda, subunitatea, inchisa, seriadoc, verificat, codstare1)
    =
    (SELECT tipdoc, anulat, blocat, operat, prefixdoc, nrdoc, carnetdoc, datadoc, valoare, an, luna, obs, moneda, subunitatea, inchisa, seriadoc, verificat, codstare1
     FROM TMP_PRECOMANDA
    )
    WHERE
     CodPreComanda = RecId;

    DELETE FROM PRECOMANDA1 WHERE CodPreComanda = RecID AND CodPreComanda1 NOT IN (SELECT CodPreComanda1 FROM TMP_PRECOMANDA1);

    FOR v_rec IN (SELECT * FROM TMP_PRECOMANDA1 ORDER BY IndexLocal) LOOP
      IF  COALESCE( v_rec.CodPreComanda1, -1) &gt; 0 THEN
        UPDATE PRECOMANDA1
        SET
        indexlocal   = v_rec.indexlocal,
        codobiect    = v_rec.codobiect,
        umsec        = v_rec.umsec,
        pu           = v_rec.pu,
        cant         = v_rec.cant,
        rest         = v_rec.rest,
        termen       = v_rec.termen,
        addim        = v_rec.addim,
        procdisc     = v_rec.procdisc,
        obs          = v_rec.obs,
        pretorig     = v_rec.pretorig,
        coefdiscmaj  = v_rec.coefdiscmaj,
        scadenta     = v_rec.scadenta,
        d1           = v_rec.d1,
        d2           = v_rec.d2,
        d3           = v_rec.d3,
        cantum1      = v_rec.cantum1,
        codcontract1 = v_rec.codcontract1,
        codcentru    = v_rec.codcentru,
        codoferta1   = v_rec.codoferta1,
        pretum1      = v_rec.pretum1,
        codpart      = v_rec.codpart,
        codpromo1    = v_rec.codpromo1,
        moneda       = v_rec.moneda,
        codlocatie   = v_rec.codlocatie,
        cantmin      = v_rec.cantmin,
        datastart    = v_rec.datastart
        WHERE
         CODPRECOMANDA1 = v_rec.CODPRECOMANDA1;
      ELSE
        SELECT NEXTVAL('SEQ_PRECOMANDA1_CODPRECOMANDA1') INTO VCOD;

        INSERT INTO PRECOMANDA1(codprecomanda1, codprecomanda, indexlocal, codobiect, umsec, pu, cant, rest, termen, addim, procdisc, obs, pretorig, coefdiscmaj, scadenta, d1, d2, d3, cantum1, codcontract1, codcentru, codoferta1, pretum1, codpart, codpromo1, moneda, codlocatie, cantmin, datastart)
        VALUES(vCod, RecID, v_rec.indexlocal, v_rec.codobiect, v_rec.umsec, v_rec.pu, v_rec.cant, v_rec.rest, v_rec.termen, v_rec.addim, v_rec.procdisc, v_rec.obs, v_rec.pretorig, v_rec.coefdiscmaj, v_rec.scadenta, v_rec.d1, v_rec.d2, v_rec.d3, v_rec.cantum1, v_rec.codcontract1, v_rec.codcentru, v_rec.codoferta1, v_rec.pretum1, v_rec.codpart, v_rec.codpromo1, v_rec.moneda, v_rec.codlocatie, v_rec.cantmin, v_rec.datastart);
      END IF;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_PRECOMANDA_CODPRECOMANDA') INTO RecId;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_PRECOMANDA.CT_MONITOR', true))))
    THEN
      PERFORM pkg_userfirme_postlogcucommit( 'PRECOMANDA', (current_setting('PKG_GLOBALS.USERNAME', true)), 'A', RECID, (current_setting('PKG_GLOBALS.FIRMANAME', true)), aCodSubunit, aDataDoc, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    INSERT INTO PRECOMANDA(codprecomanda, tipdoc, anulat, blocat, operat, prefixdoc, nrdoc, carnetdoc, datadoc, valoare, an, luna, obs, moneda, subunitatea, inchisa, seriadoc, verificat, codstare1)
    SELECT RECID, tipdoc, anulat, blocat, operat, prefixdoc, nrdoc, carnetdoc, datadoc, valoare, an, luna, obs, moneda, subunitatea, inchisa, seriadoc, verificat, codstare1
    FROM TMP_PRECOMANDA;

    INSERT INTO PRECOMANDA1(codprecomanda1, codprecomanda, indexlocal, codobiect, umsec, pu, cant, rest, termen, addim, procdisc, obs, pretorig, coefdiscmaj, scadenta, d1, d2, d3, cantum1, codcontract1, codcentru, codoferta1, pretum1, codpart, codpromo1, moneda, codlocatie, cantmin, datastart)
    SELECT NEXTVAL('SEQ_PRECOMANDA1_CODPRECOMANDA1'), RECID, indexlocal, codobiect, umsec, pu, cant, rest, termen, addim, procdisc, obs, pretorig, coefdiscmaj, scadenta, d1, d2, d3, cantum1, codcontract1, codcentru, codoferta1, pretum1, codpart, codpromo1, moneda, codlocatie, cantmin, datastart
    FROM TMP_PRECOMANDA1;
  END IF;

  PERFORM NotifyModif( Operation, RecId, 'COMANDA');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_precomanda_stergelinie</obj_name>
  <obj_hashval>58fc924817a7adce99a0f2f57ccd3dc4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_precomanda_stergelinie(acodprecomanda1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodPreComanda numeric;
  aRest          double precision;
  aCant          double precision;
  aCount         numeric;
begin
  BEGIN
    SELECT codprecomanda, Cant, Rest INTO aCodPreComanda, aCant, aRest FROM PreComanda1 WHERE CodPreComanda1 = aCodPreComanda1;
  EXCEPTION WHEN others THEN
    aCodPreComanda := 0;
  END;

  IF  aRest = 0 THEN
  END IF;

  IF  aRest &lt; aCant THEN
    UPDATE PreComanda1
    SET
    cant = cant - aRest,
    rest = 0
    WHERE
     codprecomanda1 = acodprecomanda1;
  ELSE
    DELETE FROM precmdlink  WHERE codprecomanda1 = aCodPreComanda1;
    DELETE FROM PreComanda1 WHERE CodPreComanda1 = aCodPreComanda1;

    SELECT count( *) INTO acount FROM precomanda1 WHERE codprecomanda = acodprecomanda;

    IF  acount = 0 THEN
      DELETE FROM precomanda WHERE codprecomanda = acodprecomanda;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_predariplus_duplicare</obj_name>
  <obj_hashval>5db93f39773d9e13b05618b391d9238c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_predariplus_duplicare(INOUT wme_result numeric, INOUT aid numeric, INOUT acant numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NEWID numeric;
begin
  BEGIN
    SELECT MAX( IDINREG) + 1 INTO NEWID FROM PREDARIPLUS;

    INSERT INTO PREDARIPLUS(IDINREG, NRDOC, DATADOC, CODAFA, CODEXTERN, UA, SECTIE, CANTITATEWME, DATAMODIF, NRCMD, DATACMD, FSC, SCHIMB, FORMATIE, NRNP, DATANP, USERIDBLOCAJ, CODCOMANDA1)
    SELECT NEWID, NRDOC, DATADOC, CODAFA, CODEXTERN, UA, SECTIE, ACANT, CURRENT_TIMESTAMP, NRCMD, DATACMD, FSC, SCHIMB, FORMATIE, NRNP, DATANP, (SELECT PKG_GLOBALS_GETUSERID.WME_RESULT FROM PKG_GLOBALS_GETUSERID(NULL,NULL)), CODCOMANDA1
    FROM PREDARIPLUS WHERE IDINREG = AID;
  EXCEPTION WHEN OTHERS THEN
    NEWID := 0;
  END;

  WME_Result :=  NEWID;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_predariplus_pp_lock</obj_name>
  <obj_hashval>51f9a3682b14a61fc39fbb279f73f8b3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_predariplus_pp_lock(acodcomanda1 numeric, auserid numeric, aid numeric, apreluat numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  ANRDOC   numeric;
  ADATADOC date;
begin
  BEGIN
    SELECT C.NRDOC, C.DATADOC
    INTO ANRDOC, ADATADOC
    FROM COMANDA1 C1 INNER JOIN COMANDA C ON  C.CODCOMANDA = C1.CODCOMANDA
    WHERE C1.CODCOMANDA1 = ACODCOMANDA1;
  EXCEPTION WHEN OTHERS THEN
    ANRDOC := 0;
  END;

  IF  ANRDOC &gt; 0 THEN
    UPDATE PREDARIPLUS
    SET
    NRCMD        = TO_CHAR( ANRDOC,'9999999999'),
    DATACMD      = ADATADOC,
    USERIDBLOCAJ = AUSERID,
    CODCOMANDA1  = ACODCOMANDA1,
    CANTITATEWME = APRELUAT
    WHERE
     IDINREG = AID;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_predariplus_pp_lock_allfree</obj_name>
  <obj_hashval>d0dd94f5b95db3fa144b3e5c01f85af3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_predariplus_pp_lock_allfree(auserid numeric, acodafa character varying, adatastart character varying, adatastop character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  IF ADATASTART IS NULL  AND ADATASTOP IS NULL THEN
    IF  NOT ACODAFA IS NULL THEN
      UPDATE PREDARIPLUS SET USERIDBLOCAJ = AUSERID WHERE COALESCE( USERIDBLOCAJ, 0) = 0 AND NRNP IS NULL  AND  trim( CODAFA) = ACODAFA;
    ELSE
      UPDATE PREDARIPLUS SET USERIDBLOCAJ = AUSERID WHERE COALESCE( USERIDBLOCAJ, 0) = 0 AND NRNP IS NULL;
    END IF;
  END IF;

  IF  NOT ADATASTART IS NULL  AND ADATASTOP IS NULL THEN
    IF  NOT ACODAFA IS NULL THEN
      UPDATE PREDARIPLUS SET USERIDBLOCAJ = AUSERID WHERE COALESCE( USERIDBLOCAJ, 0) = 0 AND NRNP IS NULL  AND  trim( CODAFA) = ACODAFA AND  DATADOC &gt;= TO_DATE( ADATASTART, 'DD.MM.YYYY');
    ELSE
      UPDATE PREDARIPLUS SET USERIDBLOCAJ = AUSERID WHERE COALESCE( USERIDBLOCAJ, 0) = 0 AND NRNP IS NULL  AND  DATADOC &gt;= TO_DATE( ADATASTART, 'DD.MM.YYYY');
    END IF;
  END IF;

  IF ADATASTART IS NULL  AND  NOT ADATASTOP IS NULL THEN
    IF  NOT ACODAFA IS NULL THEN
      UPDATE PREDARIPLUS SET USERIDBLOCAJ = AUSERID WHERE COALESCE( USERIDBLOCAJ, 0) = 0 AND NRNP IS NULL  AND  trim( CODAFA) = ACODAFA AND  DATADOC &lt;= TO_DATE( ADATASTOP, 'DD.MM.YYYY');
    ELSE
      UPDATE PREDARIPLUS SET USERIDBLOCAJ = AUSERID WHERE COALESCE( USERIDBLOCAJ, 0) = 0 AND NRNP IS NULL  AND  DATADOC &lt;= TO_DATE( ADATASTOP, 'DD.MM.YYYY');
    END IF;
  END IF;

  IF  NOT ADATASTART IS NULL  AND  NOT ADATASTOP IS NULL THEN
    IF  NOT ACODAFA IS NULL THEN
      UPDATE PREDARIPLUS SET USERIDBLOCAJ = AUSERID WHERE COALESCE( USERIDBLOCAJ, 0) = 0 AND NRNP IS NULL  AND  trim( CODAFA) = ACODAFA AND DATADOC BETWEEN TO_DATE( ADATASTART, 'DD.MM.YYYY') AND TO_DATE( ADATASTOP, 'DD.MM.YYYY');
    ELSE
      UPDATE PREDARIPLUS SET USERIDBLOCAJ = AUSERID WHERE COALESCE( USERIDBLOCAJ, 0) = 0 AND NRNP IS NULL  AND DATADOC BETWEEN TO_DATE( ADATASTART, 'DD.MM.YYYY') AND TO_DATE( ADATASTOP, 'DD.MM.YYYY');
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_predariplus_pp_release</obj_name>
  <obj_hashval>3e6e4ab68fd9a0cc9ec862b8c1db8949</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_predariplus_pp_release(auserid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM PREDARIPLUS PP
  WHERE  USERIDBLOCAJ = AUSERID AND NRNP IS NULL  AND CANTITATE IS NULL
    AND  EXISTS (SELECT IDINREG FROM PREDARIPLUS P WHERE PP.CODAFA = P.CODAFA AND P.NRNP IS NULL  AND  P.IDINREG &lt;&gt; PP.IDINREG);

  UPDATE PREDARIPLUS
  SET
  NRCMD        = null,
  DATACMD      = null,
  USERIDBLOCAJ = null,
  CODCOMANDA1  = null,
  CANTITATEWME = CASE WHEN cantitate IS NULL  THEN cantitatewme ELSE NULL END
  WHERE
   USERIDBLOCAJ = AUSERID AND NRNP IS NULL;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_predariplus_pp_updatenp</obj_name>
  <obj_hashval>a62dd4ebaf58b2c87834105be3d809fe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_predariplus_pp_updatenp(auserid numeric, acodcomanda1 numeric, acodintr numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  V_PP  RECORD;
begin
  FOR V_REC IN (SELECT TO_CHAR( i.nrdoc,'9999999999') NRDOC, i.datadoc, i1.obs, f.den_formatie, i.schimb, I.DATACREARE, I1.CODINTR1
                FROM INTRARI I
                     INNER JOIN INTRARI1 I1 ON  I1.CODINTR = I.CODINTR
                     LEFT  JOIN FORMATII F ON  F.CODFORMATIE = I.CODFORMATIE
                WHERE I.CODINTR = ACODINTR AND  I1.CODCMDINT1 = ACODCOMANDA1
               )
  LOOP
    FOR V_PP IN (SELECT IDINREG FROM PREDARIPLUS WHERE USERIDBLOCAJ = AUSERID AND  CODCOMANDA1 = ACODCOMANDA1) LOOP
      UPDATE PREDARIPLUS
      SET
      FSC          = V_REC.OBS,
      NRNP         = V_REC.NRDOC,
      DATANP       = V_REC.DATADOC,
      USERIDBLOCAJ = null,
      FORMATIE     = V_REC.DEN_FORMATIE,
      SCHIMB       = V_REC.SCHIMB,
      DATAWME      = V_REC.DATACREARE
      WHERE
       IDINREG = V_PP.IDINREG;

      DELETE FROM PPLINK WHERE IDINREG = V_PP.IDINREG;
      INSERT INTO PPLINK(IDINREG, CODCOMANDA1, CODINTR1) VALUES(V_PP.IDINREG, ACODCOMANDA1, V_REC.CODINTR1);
    END LOOP;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_predariplus_sterge</obj_name>
  <obj_hashval>874b1fcce8f1cb5886b6d533679d2f52</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_predariplus_sterge(aidinreg numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDoc varchar(500);
  aDataDoc date;
BEGIN
  --Florin 21.10.2022 - sinc. Oracle (18.10.2022)
  select
    'NRDOC:'||NRDOC||' '||
    'DATADOC:'||TO_CHAR(DATADOC,'DD.MM.YYYY HH24:MI')||' '||
    'CODAFA:'||CODAFA||' '||
    'CODEXTERN:'||CODEXTERN||' '||
    'UA:'||UA||' '||
    'SECTIE:'||SECTIE||' '||
    'CANTITATE:'||CANTITATE||' '||
    'DATAMODIF:'||TO_CHAR(DATAMODIF,'DD.MM.YYYY HH24:MI')||' '||
    'NRCMD:'||NRCMD||' '||
    'DATACMD:'||TO_CHAR(DATACMD,'DD.MM.YYYY HH24:MI')||' '||
    'FSC:'||FSC||' '||
    'SCHIMB:'||SCHIMB||' '||
    'FORMATIE:'||FORMATIE||' '||
    'NRNP:'||NRNP||' '||
    'DATANP:'||TO_CHAR(DATANP,'DD.MM.YYYY HH24:MI')||' '||
    'USERIDBLOCAJ:'||USERIDBLOCAJ||' '||
    'CODCOMANDA1:'||CODCOMANDA1||' '||
    'CANTITATEWME:'||CANTITATEWME||' '||
    'DATAWME:'||TO_CHAR(DATAWME,'DD.MM.YYYY HH24:MI')||' '||
    'LINIA:'||LINIA,
    DATADOC
    INTO aDoc, aDataDoc
  from predariplus where idinreg = aIDInreg;
  PERFORM WINMADMIN.PKG_USERFIRME_PostLog('PREDARIPLUS', (SELECT wme_result FROM getUSERNAME(NULL, NULL)), 'S', AIDINREG, (SELECT wme_result FROM getFIRMANAME(NULL, NULL)), GETSUBUNITATE(), aDataDoc, aDoc,
    (SELECT wme_result FROM pkg_globals_GET_EXE_VERSION(NULL, NULL)));

  DELETE FROM PREDARIPLUS WHERE IDINREG = AIDINREG;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_predariplus_update_cantitate</obj_name>
  <obj_hashval>97436bbd43ab7aac0ce93aa9d5bdc7ad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_predariplus_update_cantitate(aidinreg numeric, acantitate numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  UPDATE PREDARIPLUS SET CANTITATE = ACANTITATE WHERE IDINREG = AIDINREG;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_predariplus_update_codextern</obj_name>
  <obj_hashval>342143c98a0ede62672f62b6fc9de91b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_predariplus_update_codextern(aidinreg numeric, acodextern character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  UPDATE PREDARIPLUS SET CODEXTERN = ACODEXTERN WHERE IDINREG = AIDINREG;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_predariplus_update_linia</obj_name>
  <obj_hashval>69d376064dc57bfa119475085fd46345</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_predariplus_update_linia(aidinreg numeric, alinia character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDoc varchar(500);
  aDataDoc date;
BEGIN
  select
    'Linia: '||LINIA||'-&gt;'||aLINIA, datadoc into aDoc, adatadoc
  from predariplus where idinreg = aIDInreg;
  PERFORM WINMADMIN.PKG_USERFIRME_PostLog('PREDARIPLUS', (SELECT wme_result FROM getUSERNAME(NULL, NULL)), 'M', AIDINREG, (SELECT wme_result FROM getFIRMANAME(NULL, NULL)), GETSUBUNITATE(), aDataDoc, aDoc,
    (SELECT wme_result FROM pkg_globals_GET_EXE_VERSION(NULL, NULL)));
  UPDATE PREDARIPLUS SET LINIA = ALINIA WHERE IDINREG = AIDINREG;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_predariplus_update_sectie</obj_name>
  <obj_hashval>469846726a8685cda79a6914e8236056</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_predariplus_update_sectie(aidinreg numeric, asectie character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  UPDATE PREDARIPLUS SET SECTIE = ASECTIE WHERE IDINREG = AIDINREG;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_predariplus_verifcantwme</obj_name>
  <obj_hashval>059c6546692f21f5ba057488823fdc26</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_predariplus_verifcantwme()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  PrimaZi     date;
  PrimaZiPrec date;
begin
  SELECT DATE_TRUNC('DAY', CURRENT_TIMESTAMP) - (  to_number( to_char( CURRENT_TIMESTAMP, 'DD')) - 1) INTO PrimaZi;
  PrimaZiPrec := PrimaZi - 31;

  FOR V_REC IN (SELECT PP.IDINREG
                FROM PREDARIPLUS PP
                     INNER JOIN (SELECT COUNT( *) CATE, CODAFA FROM PREDARIPLUS GROUP BY CODAFA) CT ON  CT.CODAFA = PP.CODAFA
                WHERE CT.CATE = 1 AND PP.CANTITATEWME IS NULL  AND  NOT NRNP IS NULL  AND USERIDBLOCAJ IS NULL  AND PP.DATADOC BETWEEN PRIMAZIPREC AND CURRENT_TIMESTAMP
               )
  LOOP
    BEGIN
      UPDATE PREDARIPLUS SET CANTITATEWME = CANTITATE WHERE IDINREG = V_REC.IDINREG;
    EXCEPTION WHEN OTHERS THEN
      NULL;
    END;
  END LOOP;

  FOR V_REC IN (SELECT *
                FROM (SELECT PP.IDINREG, PP.NRNP PP_NRNP, PP.DATANP PP_DATANP, PP.FSC PP_FSC, PP.NRCMD PP_NRCMD, PP.DATACMD PP_DATACMD, PP.FORMATIE PP_FORMATIE, PP.SCHIMB PP_SCHIMB, PP.CODCOMANDA1 PP_CODCOMANDA1, TO_CHAR( I.NRDOC,'9999999999') NRNP, I.DATADOC DATANP, TO_CHAR( C.NRDOC,'9999999999') NRCMD, C.DATADOC DATACMD, I1.OBS FSC, I.SCHIMB, F.DEN_FORMATIE FORMATIE, L.CODCOMANDA1
                      FROM PREDARIPLUS PP
                          INNER JOIN PPLINK   L  ON  PP.IDINREG     = L.IDINREG
                          INNER JOIN COMANDA1 C1 ON  C1.CODCOMANDA1 = L.CODCOMANDA1
                          INNER JOIN COMANDA  C  ON  C.CODCOMANDA   = C1.CODCOMANDA
                          INNER JOIN INTRARI1 I1 ON  L.CODINTR1     = I1.CODINTR1 AND  I1.CODCMDINT1 = C1.CODCOMANDA1
                          INNER JOIN INTRARI  I  ON  I.CODINTR      = I1.CODINTR
                          LEFT  JOIN FORMATII F  ON  F.CODFORMATIE  = I.CODFORMATIE
                      WHERE PP.DATADOC BETWEEN PRIMAZIPREC AND CURRENT_TIMESTAMP
                      ) A_PG
                WHERE CODCOMANDA1 &lt;&gt; PP_CODCOMANDA1 OR  NRNP &lt;&gt; PP_NRNP OR  DATANP &lt;&gt; PP_DATANP OR  FSC &lt;&gt; PP_FSC OR  FORMATIE &lt;&gt; PP_FORMATIE OR  SCHIMB &lt;&gt; PP_SCHIMB OR  NRCMD &lt;&gt; PP_NRCMD OR  DATACMD &lt;&gt; PP_DATACMD
               )
  LOOP
    IF  V_REC.CODCOMANDA1 &lt;&gt; V_REC.PP_CODCOMANDA1 THEN
      BEGIN
        UPDATE PREDARIPLUS SET CODCOMANDA1 = V_REC.CODCOMANDA1 WHERE IDINREG = V_REC.IDINREG;
      EXCEPTION WHEN OTHERS THEN
        NULL;
      END;
    END IF;

    IF  V_REC.NRNP &lt;&gt; V_REC.PP_NRNP THEN
      BEGIN
        UPDATE PREDARIPLUS SET NRNP = V_REC.NRNP WHERE IDINREG = V_REC.IDINREG;
      EXCEPTION WHEN OTHERS THEN
        NULL;
      END;
    END IF;

    IF  V_REC.DATANP &lt;&gt; V_REC.PP_DATANP THEN
      BEGIN
        UPDATE PREDARIPLUS SET DATANP = V_REC.DATANP WHERE IDINREG = V_REC.IDINREG;
      EXCEPTION WHEN OTHERS THEN
        NULL;
      END;
    END IF;

    IF  V_REC.FSC &lt;&gt; V_REC.PP_FSC THEN
      BEGIN
        UPDATE PREDARIPLUS SET FSC = V_REC.FSC WHERE IDINREG = V_REC.IDINREG;
      EXCEPTION WHEN OTHERS THEN
        NULL;
      END;
    END IF;

    IF  V_REC.FORMATIE &lt;&gt; V_REC.PP_FORMATIE THEN
      BEGIN
        UPDATE PREDARIPLUS SET FORMATIE = V_REC.FORMATIE WHERE IDINREG = V_REC.IDINREG;
      EXCEPTION WHEN OTHERS THEN
        NULL;
      END;
    END IF;

    IF  V_REC.SCHIMB &lt;&gt; V_REC.PP_SCHIMB THEN
      BEGIN
        UPDATE PREDARIPLUS SET SCHIMB = V_REC.SCHIMB WHERE IDINREG = V_REC.IDINREG;
      EXCEPTION WHEN OTHERS THEN
        NULL;
      END;
    END IF;

    IF  V_REC.NRCMD &lt;&gt; V_REC.PP_NRCMD THEN
      BEGIN
        UPDATE PREDARIPLUS SET NRCMD = V_REC.NRCMD WHERE IDINREG = V_REC.IDINREG;
      EXCEPTION WHEN OTHERS THEN
        NULL;
      END;
    END IF;

    IF  V_REC.DATACMD &lt;&gt; V_REC.PP_DATACMD THEN
      BEGIN
        UPDATE PREDARIPLUS SET DATACMD = V_REC.DATACMD WHERE IDINREG = V_REC.IDINREG;
      EXCEPTION WHEN OTHERS THEN
        NULL;
      END;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prestatii_sp_lockrecord</obj_name>
  <obj_hashval>fa7c4a0bde9a057a0a63f82c78cc16ff</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prestatii_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMP NUMERIC(20) := 0;
BEGIN
  SELECT CODPRESTATIE INTO Tmp FROM PRESTATII WHERE CODPRESTATIE = RecId;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prestatii_sp_postrecords</obj_name>
  <obj_hashval>58105ee2f91e688c8f16b94b36f1af35</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prestatii_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  IF Operation = 0 THEN
    SELECT CODPRESTATIE INTO RecId FROM TMP_PRESTATII;
    UPDATE PRESTATII
    SET (COD,
         DENUMIRE )
     = (SELECT
          COD,
          DENUMIRE
        FROM TMP_PRESTATII )
    WHERE CODPRESTATIE = RecId;
  ELSE
    SELECT Nextval('SEQ_PRESTATII_CODPRESTATIE') INTO RecID;
    INSERT INTO PRESTATII
    (CODPRESTATIE,
     COD,
     DENUMIRE )
    SELECT
      RECID,
      COD,
      DENUMIRE
     FROM TMP_PRESTATII;
  END IF;
  PERFORM NotifyModif(Operation, RecId, 'PRESTATII');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_checkinfocursor</obj_name>
  <obj_hashval>63ebe37367d791bb1fd27f0ad124f05c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_checkinfocursor(INOUT total numeric, INOUT realizat numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  nr  numeric;
  nr1 numeric;
begin
  SELECT count(*) INTO nr  FROM nirstoc;
  SELECT count(*) INTO nr1 FROM nirstoc1;

  IF  nr1 &gt; nr THEN
    DELETE FROM nirstoc1 ns1 WHERE NOT  EXISTS (SELECT ns.codnirstoc FROM nirstoc ns WHERE ns.codnirstoc = ns1.codnirstoc);

    SELECT count(*) INTO nr1 FROM nirstoc1;
  END IF;

  IF  Nr = Nr1 THEN
    PERFORM PKG_PRETPROD_Get_DifPretProdAllSubunit();

    SELECT count(*) INTO Realizat
    FROM TMP_BALANTA_STOC tmp INNER JOIN nirstoc1 ns1 ON  ns1.codnirstoc = tmp.codobiect
    WHERE COALESCE(ns1.dirty, 0) = 0;

    SELECT count(*) INTO Total FROM TMP_BALANTA_STOC tmp INNER JOIN nirstoc1 ns1 ON  ns1.codnirstoc = tmp.codobiect;
  ELSE
    Total    := 1;
    Realizat := 0;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_checknirstoc1</obj_name>
  <obj_hashval>e589c3396c71febcb8114d2f7e5148a3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_checknirstoc1()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  nr  numeric;
  nr1 numeric;
begin
  DELETE FROM nirstoc1 ns1 WHERE not exists (SELECT 1 FROM NIRSTOC NS WHERE NS.CODNIRSTOC = NS1.CODNIRSTOC );
  DELETE FROM nirstoc1 ns1 WHERE not exists (SELECT 1 FROM NIRSTOC NS WHERE NS.CODNIRSTOC = NS1.CODNIRSTOCORIG );

  SELECT count(*) INTO nr  FROM nirstoc;
  SELECT count(*) INTO nr1 FROM nirstoc1;

  if Nr &lt;&gt; Nr1 then
    if Nr1 = 0 then
      perform PKG_PRETPROD_PopuleazaNirStoc1();
    else
      perform PKG_PRETPROD_CompleteazaNirStoc1();
    end if;
  end if;

  SELECT count(*) INTO nr  FROM nirstoc;
  SELECT count(*) INTO nr1 FROM nirstoc1;

  if nr1 &gt; nr then
    DELETE FROM nirstoc1 ns1 WHERE not exists (SELECT 1 FROM NIRSTOC NS WHERE NS.CODNIRSTOC = NS1.CODNIRSTOC );
  end if;

  perform PKG_PRETPROD_CheckNS1Reziduale();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_checknirstoc1bycodintr</obj_name>
  <obj_hashval>ddc645cb9debf6cc9c196566c9f15c93</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_checknirstoc1bycodintr(acodintr numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR v_rec IN (SELECT ns.codnirstoc, COALESCE(ns1.codnirstoc, 0) CODNIRSTOC1, COALESCE(i1.codcmdint1, 0) CODCOMANDA1
                FROM intrari1 i1
                     INNER JOIN nirstoc  ns  ON  ns.codintr1   = i1.codintr1
                     LEFT  JOIN nirstoc1 ns1 ON  ns.codnirstoc = ns1.codnirstoc
                WHERE i1.codintr = aCodIntr
               )
  LOOP
    IF  v_rec.codnirstoc1 = 0 THEN
      INSERT INTO nirstoc1(codnirstoc, codnirstocorig, tipdoc, pretmat, dinstoc, codcomanda1)
      VALUES(v_rec.codnirstoc, (SELECT pkg_list_base_utils_GETCODNIRSTOC_ORIG.WME_RESULT FROM pkg_list_base_utils_GETCODNIRSTOC_ORIG(NULL,v_Rec.codnirstoc)), 7, 0, 0, v_rec.codcomanda1);
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_checknirstoc1bycodtransf</obj_name>
  <obj_hashval>eaaec4fa63c76dc0919ed726812bac76</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_checknirstoc1bycodtransf(acodtransf numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  aRoot        numeric;
  aCodComanda1 numeric;
  aTipDoc      numeric;
begin
  FOR v_rec IN (SELECT ns.codnirstoc, COALESCE(ns1.codnirstoc, 0) CODNIRSTOC1
                FROM transf1 t1
                    INNER JOIN nirstoc  ns  ON  ns.codtransf1 = t1.codtransf1
                    LEFT  JOIN nirstoc1 ns1 ON  ns.codnirstoc = ns1.codnirstoc
                WHERE t1.codtransf = aCodTransf
                )
  LOOP
    IF  v_rec.codnirstoc1 = 0 THEN
      BEGIN
        SELECT (SELECT pkg_list_base_utils_GETCODNIRSTOC_ORIG.WME_RESULT FROM pkg_list_base_utils_GETCODNIRSTOC_ORIG(NULL,v_Rec.codnirstoc))
        INTO aRoot;
      EXCEPTION WHEN others THEN
        aRoot := 0;
      END;

      BEGIN
        SELECT COALESCE(i1.codcmdint1, 0)
        INTO aCodComanda1
        FROM nirstoc ns INNER JOIN intrari1 i1 ON  ns.codintr1 = i1.codintr1
        WHERE ns.codnirstoc = aRoot;
      EXCEPTION WHEN others THEN
        aCodComanda1 := 0;
      END;

      BEGIN
        SELECT COALESCE(nir.tipnir, 0)
        INTO aTipDoc
        FROM nirstoc ns INNER JOIN nir ON  nir.codnir = ns.codnir
        WHERE ns.codnirstoc = aRoot;
      EXCEPTION WHEN others THEN
        aTipDoc := 0;
      END;

      INSERT INTO nirstoc1(codnirstoc, codnirstocorig, tipdoc, pretmat, dinstoc, codcomanda1)
      VALUES(v_rec.codnirstoc, aRoot, aTipDoc, 0, 0, aCodComanda1);

      IF  aCodComanda1 &gt; 0 THEN
        PERFORM PKG_PRETPROD_UpdatePreturiByCodComanda1(aCodComanda1);
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_checkns1reziduale</obj_name>
  <obj_hashval>b1c13262cc43588ad16240c5a74bfea9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_checkns1reziduale()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  UPDATE nirstoc1 ns1
  SET
  codcomanda1 = null,
  pretmat     = (SELECT COALESCE(ns.pret, 0) - COALESCE(ns.adaos, 0) FROM nirstoc ns WHERE ns.codnirstoc = ns1.codnirstoc),
  dirty       = 0,
  dinstoc     = 1
  WHERE
   ns1.tipdoc = 7
   and  EXISTS (SELECT ns.codnirstoc
                FROM nirstoc ns
                    INNER JOIN intrari1 i1 ON  ns.codintr1   = i1.codintr1
                    INNER JOIN comanda1 c1 ON  i1.codcmdint1 = c1.codcomanda1
                WHERE c1.codobiect &lt;&gt; i1.codobiect and  ns.codnirstoc = ns1.codnirstocorig
               );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_completeazanirstoc1</obj_name>
  <obj_hashval>896bca39cbe7c3a37632dea29b62c6a6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_completeazanirstoc1()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform PKG_PRETPROD_CorecteazaNirStoc_Parinte();

  INSERT INTO nirstoc1
  SELECT
    ns.codnirstoc,
    ns.codnirstoc CODNIRSTOCORIG,
    n.tipnir TIPDOC,
    CASE when coalesce( D.CodDvi, 0) = 0 and coalesce( i1.codcmdint1, 0) = 0 then coalesce( ns.pret, 0) - coalesce( ns.adaos, 0)
         else 0
    end PRETMAT,
    CASE when coalesce( i1.codcmdint1, 0) = 0 then 0 else 1 end DIRTY,
    1 DINSTOC,
    CASE when c1.codobiect = i1.codobiect then coalesce( i1.codcmdint1, 0) else null end CODCOMANDA1
  FROM nirstoc ns
      left join nirstoc1 ns1 ON ns1.codnirstoc = ns.codnirstoc
      left join nir      n   ON n.codnir       = ns.codnir
      left join intrari1 i1  ON i1.codintr1    = ns.codintr1
      left join dvi      d   ON d.codintr      = n.codintr and d.tipimport = 1
      left join COMANDA1 C1  ON C1.CODCOMANDA1 = I1.CODCMDINT1
  WHERE
        coalesce( CodNirstocParinte, 0) = 0 and ns1.codnirstoc is null ;
--&lt;sstunknown&gt;
/*
 execute 'TRUNCATE TABLE tmp_nirstoc1';

insert
  into
  tmp_nirstoc1 ( codnirstoc,
  codnirstocorig,
  tipdoc,
  pretmat,
  dirty,
  dinstoc,
  codcomanda1 )
select
  codnirstoc,
  codnirstocorig,
  tipdoc,
  pretmat,
  dirty,
  dinstoc,
  codcomanda1
from
  tmp;

delete
from
  tmp_nirstoc1
where
  codnirstoc in (
  select
    codnirstoc
  from
    nirstoc1 );

insert
  into
  nirstoc1
select
  *
from
  tmp_nirstoc1;
--&lt;sstunknown&gt;
 execute 'TRUNCATE TABLE tmp_nirstoc1';
*/
end;

$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_corecteazanirstoc_parinte</obj_name>
  <obj_hashval>f0d010366606fa50bd1cb967f7af5b5a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_corecteazanirstoc_parinte()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  V_REC RECORD;
begin
  for V_REC in (SELECT ns.codnirstoc
                FROM nirstoc ns inner join nirstoc nsp ON nsp.codnirstoc = coalesce(ns.codnirstocparinte, 0)
                WHERE
                      coalesce(ns.codnirstocparinte, 0) &lt;&gt; 0
                  and coalesce(ns.codnirstocparinte, 0) &lt; ns.codnirstoc
                  and coalesce(nsp.codnirstocparinte, 0) = ns.codnirstoc
               )
  loop
    UPDATE nirstoc SET codnirstocparinte = 0 WHERE codnirstoc = V_REC.CODNIRSTOC;
  end loop;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_get_difpretprodallsubunit</obj_name>
  <obj_hashval>1c1968bb0eefe6d14007a895a7d5eb1d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_get_difpretprodallsubunit()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  N     RECORD;
  aAn   numeric;
  aLuna numeric;
BEGIN
  aAn   := GetANLUCRU();
  aLuna := GetLUNALUCRU();

  DELETE FROM TMP_BALANTA_STOC;

  PERFORM PKG_DIFPRETPROD_MAKE_STOCINITIAL_LUNA( aAN, aLUNA);
  PERFORM PKG_DIFPRETPROD_MAKE_MISCARI_IN_LUNA(  aAN, aLUNA);

  FOR N IN ( SELECT * FROM TMP_NIR_LA_DATA N) LOOP
    INSERT INTO TMP_BALANTA_STOC (CODOBIECT, STOCINITIAL, INTRARI, IESIRI) VALUES (COALESCE( N.CODOBIECT, 0), N.CANTNIR, 0, 0) ;
  END LOOP;

  FOR N IN ( SELECT * FROM TMP_NIR_IN_INTERVALUL N) LOOP
    UPDATE  TMP_BALANTA_STOC SD SET INTRARI = N.CANTNIR WHERE COALESCE( N.CODOBIECT, 0) = COALESCE( SD.CODOBIECT, 0);

    IF NOT FOUND THEN
      INSERT INTO TMP_BALANTA_STOC AS SD (CODOBIECT, STOCINITIAL, INTRARI, IESIRI) VALUES (COALESCE( N.CODOBIECT, 0), 0, N.CANTNIR, 0) ;
    END IF;
  END LOOP;

  FOR N IN ( SELECT * FROM TMP_LIVR_IN_INTERVALUL N) LOOP
    UPDATE  TMP_BALANTA_STOC SD SET IESIRI = N.CANTNIR WHERE COALESCE( N.CODOBIECT, 0) = COALESCE( SD.CODOBIECT, 0);

  IF NOT FOUND THEN
    INSERT INTO TMP_BALANTA_STOC AS SD (CODOBIECT, STOCINITIAL, INTRARI, IESIRI) VALUES (COALESCE( N.CODOBIECT, 0), 0, 0, N.CANTNIR) ;
  END IF;
  END LOOP;

  DELETE FROM TMP_BALANTA_STOC bs WHERE COALESCE( bs.stocinitial, 0) = 0 and  COALESCE( bs.Intrari, 0) = 0 and  COALESCE( bs.iesiri, 0) = 0;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_getpredaripecomanda</obj_name>
  <obj_hashval>6ae753c9e16962e30896740ce545441b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_getpredaripecomanda(INOUT wme_result numeric, INOUT acodcomanda1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCant numeric;
begin
  BEGIN
    SELECT sum(i1.cant)
    INTO aCant
    FROM intrari1 i1
        INNER JOIN intrari   i ON  i.codintr     = i1.codintr
        INNER JOIN comanda1 c1 ON  i1.codcmdint1 = c1.codcomanda1
    WHERE i1.codcmdint1 = aCodComanda1 and  COALESCE(i.anulat, 0) = 0 and  COALESCE(i.operat, 0) = 1 and  i1.codobiect = c1.codobiect;
  EXCEPTION WHEN others THEN
    aCant := 0;
  END;

  WME_Result :=  aCant;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_getpredarireziduu</obj_name>
  <obj_hashval>39c4c7cfcf9ff4700fedc0eb87728e20</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_getpredarireziduu(INOUT wme_result numeric, INOUT acodcomanda1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCant numeric;
begin
  BEGIN
    SELECT sum(i1.cant)
    INTO aCant
    FROM intrari1 i1
        INNER JOIN intrari      i ON  i.codintr         = i1.codintr
        INNER JOIN intrprodlink l ON  i1.codintr1       = l.codintr1
        INNER JOIN cmdprodmat cmd ON  cmd.codcmdprodmat = l.codliniecomanda and  cmd.tip = 0
    WHERE cmd.codcomanda1 = aCodComanda1 and  COALESCE(i.anulat, 0) = 0 and  COALESCE(i.operat, 0) = 1;
  EXCEPTION WHEN others THEN
    aCant := 0;
  END;

  WME_Result :=  aCant;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_getpretmat</obj_name>
  <obj_hashval>6343b3e70af800b264917bf2911c8c58</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_getpretmat(INOUT wme_result numeric, INOUT acodcomanda1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aPredat numeric;
  aValMat numeric;
  aPret   numeric;
BEGIN
  --Adina 15 septembrie 2020 - aranjat
  aPredat := 0;
  aValMat := 0;
  SELECT sum(i1.cant) INTO aPredat
  FROM   intrari1 i1
        INNER JOIN intrari i ON  i1.codintr = i.codintr and  i.anulat = 0 and  i.operat = 1
        INNER JOIN comanda1 c1 ON  c1.codcomanda1 = i1.codcmdint1
  WHERE c1.codobiect = i1.codobiect and  c1.codcomanda1 = aCodComanda1;

  SELECT Sum(l1.cant * COALESCE(ns1.pretmat, 0)) INTO aValMat
  FROM   iesiri1 ies1
        INNER JOIN iesiri ies ON  ies.codies = ies1.codies and  ies.anulat = 0 and  ies.operat = 1
        INNER JOIN livr1 l1 ON  l1.codies1 = ies1.codies1
        INNER JOIN livr l ON  ies.codies = l.codies and  l1.codlivr = l.codlivr
        LEFT  JOIN nirstoc1 ns1 ON  ns1.codnirstoc = l1.codnirstoc
  WHERE ies1.codcmdint1 = aCodcomanda1;

  IF  aPredat = 0 THEN
    aPret := 0;
  ELSE
    aPret := Round((aValMat / aPredat)::numeric, 7);
  END IF;

  WME_Result :=  aPret;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_gettotalpredarireziduu</obj_name>
  <obj_hashval>dc4373247fa3ff3246309eca9821b3d4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_gettotalpredarireziduu(INOUT wme_result numeric, INOUT acodcmdprodmat numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCant numeric;
begin
  BEGIN
    SELECT sum(i1.cant)
    INTO aCant
    FROM intrari1 i1
        INNER JOIN intrari      i   ON  i.codintr         = i1.codintr
        INNER JOIN intrprodlink l   ON  i1.codintr1       = l.codintr1
        INNER JOIN cmdprodmat   rez ON  l.codliniecomanda = rez.codcmdprodmat and  rez.tip = 2
        INNER JOIN comanda1     c1  ON  rez.codcomanda1   = c1.codcomanda1
        INNER JOIN cmdprodmat   r   ON  r.codcomanda1     = c1.codcomanda1
    WHERE r.codcmdprodmat = aCodCmdProdMat and  COALESCE(i.anulat, 0) = 0 and  COALESCE(i.operat, 0) = 1;
  EXCEPTION WHEN others THEN
    aCant := 0;
  END;

  WME_Result :=  aCant;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_getvalbonconsumachiz</obj_name>
  <obj_hashval>fd582937026b1b6449863a2af1342719</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_getvalbonconsumachiz(INOUT wme_result numeric, INOUT acodcomanda1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aValMat NUMERIC(20,7);
  v_rec record;
BEGIN
  --Florin 16.03.2023 - sinc. Oracle (14.15.03.2023)
  --Florin 23.05.2022 - sinc. Oracle
  --Florin 18.03.2022 - sinc. Oracle (17.03.2022)
  aValMat := 0;
  for v_rec in (select case when ns.codnirstoc &gt; 0 then (ns.pret - coalesce(ns.adaos,0)) else coalesce(lv.pretachiz,0) end * l1.cant valoare
                from iesiri1 i1
                     inner join iesiri i on i.codies = i1.codies
                     inner join livr l on l.codies = i.codies
                     inner join livr1 l1 on l1.codlivr = l.codlivr and l1.codies1 = i1.codies1
                     left join nirstoc ns on ns.codnirstoc = l1.codnirstoc
                     left join livrval lv on lv.codlivr1 = l1.codlivr1
                where i.operat = 1 and i.anulat = 0 and i1.codcmdint1 = aCodComanda1
                UNION ALL
                    SELECT
                      i1.cant*i1.pu * case when coalesce(i.moneda,0) &gt; 0 then i.curs else 1 end valoare
                    from intrari1 i1
                    inner join intrari i on i.codintr = i1.codintr
                    where COALESCE(i.anulat,0) = 0 and nvl(i.operat, 0) = 1 and i1.tiplinie = 'S'
                      and i1.codcmdint1 = aCodComanda1 and exists (
                        select mat.codobiect
                        from prodmat mat
                        inner join cmdprodmat cmd on cmd.codprodmat = mat.codmat
                        inner join comanda1 c1 on c1.codcomanda1 = cmd.codcomanda1
                        where c1.codcomanda1 = aCodComanda1 and mat.tip = 6 and mat.codobiect = i1.codobiect
                        )
                ) loop
    aValMat := aValMat + v_rec.valoare;
  end loop;
  WME_Result :=  aValMat;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_getvalmannet</obj_name>
  <obj_hashval>8877ae5b111543a8c6d6757558b7666c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_getvalmannet(INOUT wme_result numeric, INOUT acodcomanda1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aValManNet numeric;
begin
  aValManNet := 0;
  BEGIN
    SELECT sum(COALESCE(pn1.valman, 0))
    INTO aValManNet
    FROM prodnet1 pn1
    INNER JOIN prodnet pn ON  pn1.codprodnet = pn.codprodnet
    WHERE
       pn1.tip = 1 and  pn.an * 12 + pn.luna = current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric * 12 + current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric and  pn1.coddoc1 = aCodComanda1;
  EXCEPTION WHEN others THEN
    aValManNet := 0;
  END;

  WME_Result :=  aValManNet;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_getvalmanreal</obj_name>
  <obj_hashval>8128273fdd6bde919c4165eb6fcaf2aa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_getvalmanreal(INOUT wme_result numeric, INOUT acodcomanda1 numeric, INOUT adataref character varying DEFAULT to_char((CURRENT_DATE)::timestamp with time zone, 'dd.mm.yyyy'::text))
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aValMan numeric;
aCodMoneda numeric;
BEGIN
  --Florin 14.303.2023 - sinc. Oracle (13.03.2023)
  --Florin 30.12.2021 - sinc Oracle (29.12.2021)
  aValMan := 0;
    begin
      select coalesce(pc.codmoneda,0) into acodmoneda
      from prodcomp pc
           inner join comanda1 c1 on c1.codreteta = pc.codprodcomp
      where c1.codcomanda1 = acodcomanda1;
    exception when others then aCodMoneda := 0;
    end;
   if acodmoneda &gt; 0 then
  BEGIN
    SELECT sum(CASE WHEN  p2.codies1 &gt; 0 THEN i1.pu
      else Coalesce( (select nvl(Tarif,0) from Tarifeman1 tt1 WHERE p.an*12+p.luna BETWEEN tt1.alstart AND tt1.alstop and tt1.codtarif = p2.codtarif), 0)
      end * Coalesce(P2.TU, pm.tu) * P2.REALIZAT / 60 *
      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(
      COALESCE(PC.codmoneda,0), (CASE WHEN fnc_getvalconstantalucru('BancaProdV') =  0 THEN fnc_getvalconstantalucru('BancaSitV')
      ELSE fnc_getvalconstantalucru('BancaProdV') END),
      to_date(aDataRef, 'dd.mm.yyyy'))
    ) INTO aValMan
    FROM RaportP P
        INNER JOIN RaportP1 P1 ON  P1.CodRaportP  = P.CodRaportP
        INNER JOIN RaportP2 P2 ON  P2.CodRaportP1 = P1.CodRaportP1
        LEFT  JOIN ProdMan  PM ON  PM.CodMan      = P2.CodMan
        left join prodcomp pc on pc.codprodcomp = pm.codprodcomp
        LEFT  JOIN locmunca lm ON  p2.codloc      = lm.codloc
        LEFT  JOIN IESIRI1  I1 ON  I1.CODIES1     = P2.CODIES1
    WHERE P2.CodComanda1 = aCodComanda1;
  EXCEPTION WHEN others THEN
    aValMan := 0;
  END;
    else
      BEGIN
    SELECT sum(CASE WHEN  p2.codies1 &gt; 0 THEN i1.pu
      else Coalesce( (select nvl(Tarif,0) from Tarifeman1 tt1 WHERE p.an*12+p.luna BETWEEN tt1.alstart AND tt1.alstop and tt1.codtarif = p2.codtarif), 0)
      end * Coalesce(P2.TU, pm.tu) * P2.REALIZAT / 60
    ) INTO aValMan
    FROM RaportP P
        INNER JOIN RaportP1 P1 ON  P1.CodRaportP  = P.CodRaportP
        INNER JOIN RaportP2 P2 ON  P2.CodRaportP1 = P1.CodRaportP1
        LEFT  JOIN ProdMan  PM ON  PM.CodMan      = P2.CodMan
        left join prodcomp pc on pc.codprodcomp = pm.codprodcomp
        LEFT  JOIN locmunca lm ON  p2.codloc      = lm.codloc
        LEFT  JOIN IESIRI1  I1 ON  I1.CODIES1     = P2.CODIES1
    WHERE P2.CodComanda1 = aCodComanda1;
    EXCEPTION WHEN others THEN
    aValMan := 0;
    END;
    end if;
  WME_Result :=  aValMan;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_insereazacopii</obj_name>
  <obj_hashval>a2f34fa24167e9821e29050d765c7872</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_insereazacopii(acodnirstoc numeric, anivel numeric, creanga character varying, ind numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC         RECORD;
  NR             numeric;
  Rez           numeric;
  aCodComanda1   numeric;
  acount         numeric;
BEGIN
  --Adina 15 septembrie - fct.returneaza numeric
  Nr := InStr(creanga, '.' || coalesce(aCodNirStoc::varchar ,'') || '.');
  IF  NR = 0 THEN
    SELECT count(*) INTO acount
    FROM TMP_MANEVRA_LINIICOMENZI
    WHERE codcomanda1 = acodnirstoc and  cant = anivel;

    IF  acount = 0 THEN
      INSERT INTO TMP_MANEVRA_LINIICOMENZI(CodComanda1, CANT)
      VALUES(aCodNirStoc, aNivel);

      SELECT CodComanda1 INTO aCodComanda1
      FROM Nirstoc1
      WHERE CodNirStoc = aCodNirStoc;

      Rez := 0;

      IF  aCodComanda1 &gt; 0 THEN
        FOR v_rec IN (SELECT ns1.codnirstoc, Ind
                      FROM   iesiri1 ies1
                            INNER JOIN iesiri ies ON  ies.codies = ies1.codies
                            INNER JOIN livr1 l1 ON  l1.codies1 = ies1.codies1
                            INNER JOIN livr l ON  ies.codies = l.codies and  l1.codlivr = l.codlivr
                            INNER JOIN nirstoc1 ns1 ON  ns1.codnirstoc = l1.codnirstoc and  ns1.CodComanda1 &gt; 0
                      WHERE ies1.codcmdint1 = aCodComanda1 and  ies.anulat = 0 and  ies.operat = 1 and  ns1.codnirstoc &lt;&gt; aCodNirStoc
                      )
        LOOP
          Rez := Rez + pkg_pretprod_InsereazaCopii(v_rec.codnirstoc, aNivel + 1, coalesce(creanga,'') || coalesce(aCodNirStoc::varchar ,'') || '.', ind);
        END LOOP;
      END IF;
    END IF;
  ELSE
    Rez := 1;
    INSERT INTO TMP_MANEVRA2(CodUnic) VALUES(aCodNirStoc);
    UPDATE nirstoc1 SET dirty = 0, dinstoc = 1 WHERE codnirstoc = aCodNirStoc;
  END IF;

  RETURN Rez;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_insereazacopii</obj_name>
  <obj_hashval>241287b955ec97a72f47bc2650f40693</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_insereazacopii(INOUT wme_result numeric, INOUT acodnirstoc numeric, INOUT anivel numeric, INOUT creanga character varying, INOUT ind numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  NR           numeric;
  Rez          numeric;
  aCodComanda1 numeric;
  acount       numeric;
begin
  Nr := InStr(creanga, '.' || coalesce(aCodNirStoc::varchar ,'') || '.');
  IF  NR = 0 THEN
    SELECT count(*) INTO acount FROM TMP_MANEVRA_LINIICOMENZI WHERE codcomanda1 = acodnirstoc and  cant = anivel;

    IF  acount = 0 THEN
      INSERT INTO TMP_MANEVRA_LINIICOMENZI(CodComanda1, CANT)
      VALUES(aCodNirStoc, aNivel);

      SELECT CodComanda1 INTO aCodComanda1 FROM Nirstoc1 WHERE CodNirStoc = aCodNirStoc;
      Rez := 0;

      IF  aCodComanda1 &gt; 0 THEN
        FOR v_rec IN
        (
        SELECT ns1.codnirstoc, Ind
        FROM iesiri1 ies1
        INNER JOIN iesiri ies ON  ies.codies = ies1.codies
        INNER JOIN livr1 l1 ON  l1.codies1 = ies1.codies1
        INNER JOIN livr l ON  ies.codies = l.codies and  l1.codlivr = l.codlivr
        INNER JOIN nirstoc1 ns1 ON  ns1.codnirstoc = l1.codnirstoc and  ns1.CodComanda1 &gt; 0
        WHERE
           ies1.codcmdint1 = aCodComanda1 and  ies.anulat = 0 and  ies.operat = 1 and  ns1.codnirstoc &lt;&gt; aCodNirStoc
        )
        LOOP
          Rez := Rez + InsereazaCopii(v_rec.codnirstoc, aNivel + 1, coalesce(creanga,'') || coalesce(aCodNirStoc::varchar ,'') || '.', ind);
        END LOOP;
      END IF;
    END IF;
  ELSE
    Rez := 1;
    INSERT INTO TMP_MANEVRA2(CodUnic) VALUES(aCodNirStoc);

    UPDATE nirstoc1 SET dirty = 0, dinstoc = 1 WHERE codnirstoc = aCodNirStoc;
  END IF;

  WME_Result :=  Rez;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_populeazanirstoc1</obj_name>
  <obj_hashval>96c386f7a93ac1cacd66410ac20f54ec</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_populeazanirstoc1()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 05.06.2024 - recursive
  perform PKG_PRETPROD_CorecteazaNirStoc_Parinte();

  execute 'TRUNCATE TABLE nirstoc1';

  INSERT INTO nirstoc1 ( codnirstoc, codnirstocorig, tipdoc, pretmat, dirty, dinstoc, codcomanda1 )
  WITH RECURSIVE tmp(codnirstoc, codnirstocorig, tipdoc, PretMat, dirty, DinStoc, CodComanda1) AS (
    SELECT
      ns.codnirstoc, ns.codnirstoc codnirstocorig, n.tipnir tipdoc,
      CASE WHEN Nvl(D.CodDvi,0) = 0 AND Nvl(i1.codcmdint1,0) = 0 THEN Nvl(ns.pret,0)-Nvl(ns.adaos,0) ELSE 0 END PretMat,
      CASE WHEN Nvl(i1.codcmdint1,0) = 0 THEN 0 ELSE 1 END dirty,
      1 DinStoc, nvl(i1.codcmdint1,0) CodComanda1
    FROM nirstoc ns
      LEFT JOIN nir n ON n.codnir = ns.codnir
      LEFT JOIN intrari1 i1 ON i1.codintr1 = ns.codintr1
      LEFT JOIN dvi d ON d.codintr = n.codintr AND d.tipimport = 1
    WHERE Coalesce(CodNirstocParinte,0) = 0
    UNION ALL
    SELECT
      ns.codnirstoc, tmp.codnirstocorig, tmp.tipdoc, tmp.PretMat, tmp.dirty, tmp.DinStoc, tmp.CodComanda1
    FROM tmp INNER JOIN nirstoc ns ON Coalesce(ns.codnirstocparinte,0) = tmp.codnirstoc
  )
  SELECT codnirstoc, codnirstocorig, tipdoc, pretmat, dirty, dinstoc, codcomanda1
  FROM tmp;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_preiainfocursor</obj_name>
  <obj_hashval>8655d2ae944f663bdcc1df6ba010aef5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_preiainfocursor(INOUT total numeric, INOUT realizat numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_PRETPROD_CheckNirStoc1();

  SELECT count(*) INTO Realizat
  FROM TMP_BALANTA_STOC tmp INNER JOIN nirstoc1 ns1 ON  ns1.codnirstoc = tmp.codobiect
  WHERE COALESCE(ns1.dirty, 0) = 0;

  SELECT count(*) INTO Total FROM TMP_BALANTA_STOC tmp INNER JOIN nirstoc1 ns1 ON  ns1.codnirstoc = tmp.codobiect;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_setdirtynirstoc1</obj_name>
  <obj_hashval>d9496935e48949a1e9850bd6abd1fc02</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_setdirtynirstoc1(acodnirstoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodComanda1 numeric;
  NR           numeric := 0;
begin
    --Bogdan 64633 - PG- eroare generare BC din comanda interna, baza de date pe FTP
  SELECT COUNT(*) INTO NR FROM TMP_MANEVRA2 WHERE CODUNIC = aCODNIRSTOC;

  IF  NR = 0 THEN
    INSERT INTO TMP_MANEVRA2(CODUNIC) VALUES(aCODNIRSTOC);
  ELSE
    DELETE FROM tmp_manevra WHERE codunic = aCodNirStoc;
    RETURN;
  END IF;

  BEGIN
    SELECT COALESCE(codcomanda1, 0) INTO STRICT aCodComanda1 FROM nirstoc1 WHERE codnirstoc = aCodNirStoc;
  EXCEPTION WHEN others THEN
    aCodComanda1 := 0;
  END;

  IF  aCodComanda1 &gt; 0 THEN
    UPDATE nirstoc1 SET dirty = 1 WHERE codcomanda1 = aCodComanda1;

    INSERT INTO tmp_manevra(codunic)
    SELECT codnirstoc FROM nirstoc1 WHERE codcomanda1 = aCodComanda1 and  COALESCE(dirty, 0) = 0;
  END IF;

  DELETE FROM tmp_manevra WHERE codunic = aCodNirStoc;

  INSERT INTO tmp_manevra(codunic)
  SELECT nsi.codnirstoc
  FROM nirstoc ns
      INNER JOIN livr1    l1    ON  l1.codnirstoc    = ns.codnirstoc
      INNER JOIN iesiri1  i1    ON  l1.codies1       = i1.codies1 and  COALESCE(i1.codcmdint1, 0) &gt; 0
      INNER JOIN iesiri   i     ON  i.codies         = i1.codies
      INNER JOIN livr     l     ON  l.codies         = i.codies and  l1.codlivr = l.codlivr
      INNER JOIN intrari1 intr1 ON  intr1.codcmdint1 = i1.codcmdint1
      INNER JOIN nirstoc  nsi   ON  nsi.codintr1     = intr1.codintr1
  WHERE ns.codnirstoc = aCodNirStoc AND  NSI.CODNIRSTOC &lt;&gt; aCodNirStoc;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_updatecodcomanda1onnirstoc1</obj_name>
  <obj_hashval>f031bcfa70f4058832396be015624bd3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_updatecodcomanda1onnirstoc1()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR v_rec IN (SELECT ns1.codnirstoc, i1.codcmdint1 CODCOMANDA1, COALESCE(prod.tip, 0) TIP
                FROM nirstoc1 ns1
                    INNER JOIN nirstoc      root ON  root.codnirstoc    = ns1.codnirstocorig
                    INNER JOIN intrari1     i1   ON  root.codintr1      = i1.codintr1
                    LEFT  JOIN intrprodlink l    ON  i1.codintr1        = l.codintr1
                    LEFT  JOIN cmdprodmat   prod ON  prod.codcmdprodmat = l.codliniecomanda
                WHERE ns1.tipdoc = 7 and  COALESCE(ns1.codcomanda1, 0) = 0
               )
  LOOP
    UPDATE nirstoc1 SET codcomanda1 = CASE WHEN  v_rec.tip = 2 THEN 0 ELSE v_rec.codcomanda1 END WHERE codnirstoc = v_rec.codnirstoc;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_updatenirstoc1</obj_name>
  <obj_hashval>95a936fde90ca4c6f555d8b088eec522</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_updatenirstoc1()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  aRoot        numeric;
  aTipNir      numeric;
  aCodComanda1 numeric;
begin
  DELETE FROM nirstoc1 ns1 WHERE NOT  EXISTS (SELECT ns.codnirstoc FROM nirstoc ns WHERE ns.codnirstoc = ns1.codnirstoc);

  FOR v_rec IN (SELECT ns.codnirstoc FROM nirstoc ns WHERE NOT  EXISTS (SELECT ns1.codnirstoc FROM nirstoc1 ns1 WHERE ns1.codnirstoc = ns.codnirstoc)) LOOP
    aRoot := (SELECT pkg_list_base_utils_GETCODNIRSTOC_ORIG.WME_RESULT FROM pkg_list_base_utils_GETCODNIRSTOC_ORIG(NULL,v_Rec.codnirstoc));

    BEGIN
      SELECT NIR.TIPNIR, COALESCE(i1.codcmdint1, 0)
      INTO aTipNir, aCodComanda1
      FROM NIRSTOC ns
          INNER JOIN nir         ON  nir.codnir  = ns.codnir
          LEFT  JOIN intrari1 i1 ON  i1.codintr1 = ns.codintr1
      WHERE ns.codnirstoc = aRoot;
    EXCEPTION WHEN others THEN
      aTipNir      := 0;
      aCodComanda1 := 0;
    END;

    INSERT INTO nirstoc1(codnirstoc, codnirstocorig, tipdoc, dirty, codcomanda1)
    VALUES(v_Rec.codnirstoc, aRoot, aTipNir, 1, CASE WHEN  aTipNir = 7 THEN aCodComanda1 ELSE 0 END);
  END LOOP;

  UPDATE nirstoc1 SET codnirstocorig = codnirstoc WHERE COALESCE(codnirstocorig, 0) = 0;

  PERFORM PKG_PRETPROD_UpdateCodComanda1OnNirStoc1();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_updatenirstoc1consumuri</obj_name>
  <obj_hashval>e6cbc9667d2640b63eec1dd14c591bc6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_updatenirstoc1consumuri(acodnirstoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aRoot        numeric;
  aTipNir      numeric;
  aCodComanda1 numeric;
  aPret        numeric;
  aProd        numeric;
begin
  DELETE FROM tmp_manevra WHERE codunic = aCodNirStoc;
  INSERT INTO tmp_manevra(codunic)
  SELECT  DISTINCT nsl.codnirstoc
  FROM nirstoc ns
      INNER JOIN intrari1   i1   ON  i1.codintr1      = ns.codintr1
      INNER JOIN cmdprodmat prod ON  prod.codcomanda1 = i1.codcmdint1 and  COALESCE(prod.tip, 0) = 0
      INNER JOIN (SELECT sum(i1.cant) CANT, i1.codcmdint1
                  FROM intrari1 i1 INNER JOIN intrari i ON  i1.codintr = i.codintr
                  WHERE i1.codcmdint1 &gt; 0
                  GROUP BY i1.codcmdint1
                 ) predat ON  predat.codcmdint1    = prod.codcomanda1
      INNER JOIN iesiri1  ies1 ON  ies1.codcmdint1 = prod.codcomanda1
      INNER JOIN iesiri   ies  ON  ies.codies      = ies1.codies
      INNER JOIN livr     l    ON  l.codies        = ies.codies
      INNER JOIN livr1    l1   ON  l1.codies1      = ies1.codies1 and  l.codlivr = l1.codlivr
      INNER JOIN nirstoc  nsl  ON  nsl.codnirstoc  = l1.codnirstoc
      LEFT  JOIN nirstoc1 ns1  ON  ns1.codnirstoc  = l1.codnirstoc
  WHERE COALESCE(ies.anulat, 0) = 0 and  COALESCE(ies.operat, 0) = 1 and  ns.codnirstoc = aCodNirStoc and  COALESCE(ns1.codnirstoc, 0) = 0;

  aRoot := (SELECT pkg_list_base_utils_GETCODNIRSTOC_ORIG.WME_RESULT FROM pkg_list_base_utils_GETCODNIRSTOC_ORIG(NULL,acodnirstoc));
  BEGIN
    SELECT NIR.TIPNIR, COALESCE(i1.codcmdint1, 0), CASE WHEN  i1.codobiect = c1.codobiect THEN 1 ELSE 0 END
    INTO aTipNir, aCodComanda1, aProd
    FROM NIRSTOC ns
    INNER JOIN nir         ON  nir.codnir     = ns.codnir
    LEFT  JOIN intrari1 i1 ON  i1.codintr1    = ns.codintr1
    LEFT  JOIN comanda1 c1 ON  c1.codcomanda1 = i1.codcmdint1
    WHERE ns.codnirstoc = aRoot;
  EXCEPTION WHEN others THEN
    aTipNir      := 0;
    aCodComanda1 := 0;
  END;

  aPret := 0;
  IF  aTipNir &lt;&gt; 7 THEN
    BEGIN
      SELECT COALESCE(pret, 0) - COALESCE(adaos, 0) INTO aPret FROM nirstoc WHERE codnirstoc = aCodNirstoc;
    EXCEPTION WHEN others THEN
      aPret := 0;
    END;
  END IF;

  INSERT INTO nirstoc1(codnirstoc, codnirstocorig, tipdoc, dirty, codcomanda1, pretmat)
  VALUES(acodnirstoc, aRoot, aTipNir, 1, CASE WHEN  aTipNir = 7 and  aProd = 1 THEN aCodComanda1 ELSE 0 END , aPret);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_updatepretns1partial</obj_name>
  <obj_hashval>21a7b21e93a3faf9452bd7acb672af43</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_updatepretns1partial(INOUT wme_result numeric, INOUT cate numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  Ind numeric;
  Rez numeric;
  NrInreg numeric;
  LoopTot numeric;
  LoopInd numeric;
  aPret numeric;
BEGIN
  --Adina 15 septembrie 2020 - inlocuit rownum cu Limit (linia 31)+ InsereazaCopii=&gt;pkg_pretprod_insereazacopii (linia 34)
  Rez := 0;
  SELECT Count(*) INTO LoopTot
  FROM   TMP_BALANTA_STOC tmp
        INNER JOIN nirstoc1 ns1 ON  ns1.codnirstoc = tmp.codobiect
  WHERE ns1.dirty = 1;

  LoopInd := 0;
  PERFORM PKG_GLOBALS_StartEvolutie(1, current_setting('PKG_GLOBALS.USERID', true)::numeric, LoopTot, 'Insereaza copii');
  Ind := 1;
  WHILE  Ind &gt; 0 LOOP
    EXECUTE 'truncate table TMP_MANEVRA2';
    EXECUTE 'truncate table TMP_MANEVRA_LINIICOMENZI';
    Ind := 0;
    FOR v_rec IN (SELECT tmp.CodObiect CODNIRSTOC
                  FROM   TMP_BALANTA_STOC tmp
                        INNER JOIN nirstoc1 ns1 ON  ns1.codnirstoc = tmp.codobiect
                  WHERE ns1.dirty = 1 LIMIT 1000                --and  RowNum &lt; 1001  -- Adina
                 )
    LOOP
      Rez := Rez + pkg_pretprod_insereazacopii(v_rec.codnirstoc, 0, '.', Ind);
      Ind := Ind + 1;
    END LOOP;

    IF  Ind &gt; 0 THEN
      FOR v_rec IN (SELECT X.codnirstoc, NS1.CodComanda1, X.Nivel, NS1.PretMat
                    FROM (SELECT  DISTINCT Tmp.CodComanda1 CODNIRSTOC, Max(tmp.Cant) NIVEL
                          FROM TMP_MANEVRA_LINIICOMENZI tmp
                          WHERE NOT  EXISTS (SELECT t2.codunic FROM tmp_manevra2 t2 WHERE tmp.codcomanda1 = t2.codunic)
                          GROUP BY tmp.CodComanda1
                         ) X
                         INNER JOIN NirStoc1 NS1 ON  NS1.CodNirStoc = X.codnirstoc
                    ORDER BY X.Nivel desc
                   )
      LOOP
        BEGIN
          SELECT COALESCE(NS1.PretMat, 0) * (  1 - NS1.Dirty) INTO aPret
          FROM NirStoc1 NS1
          WHERE NS1.CODNIRSTOC = v_rec.codnirstoc;
        EXCEPTION WHEN others THEN
          aPret := 0;
        END;

        IF  aPret = 0 THEN
          IF  v_rec.CodComanda1 = 0 THEN
            aPret := v_rec.PretMat;
          ELSE
            aPret := (SELECT PKG_PRETPROD_GetPretMat.WME_RESULT FROM PKG_PRETPROD_GetPretMat(NULL,v_rec.CodComanda1));
          END IF;
        END IF;

        IF  v_rec.CodComanda1 &gt; 0 THEN
          UPDATE nirstoc1 SET pretmat = aPret, dirty = 0 WHERE codcomanda1 = v_rec.codcomanda1;
        ELSE
          UPDATE nirstoc1 SET pretmat = aPret, dirty = 0 WHERE codnirstoc = v_rec.codnirstoc;
        END IF;
      END LOOP;

      SELECT LoopTot - Count(*) INTO LoopInd
      FROM   TMP_BALANTA_STOC tmp
            INNER JOIN nirstoc1 ns1 ON  ns1.codnirstoc = tmp.codobiect
      WHERE ns1.dirty = 1;

      PERFORM PKG_GLOBALS_SetEvolutie(1, current_setting('PKG_GLOBALS.USERID', true)::numeric, LoopInd);
    END IF;
  END LOOP;

  UPDATE nirstoc1 ns1 SET pretmat = 0, dirty = 1
  WHERE EXISTS (SELECT t2.codunic FROM tmp_manevra2 t2 WHERE ns1.codnirstoc = t2.codunic);

  WME_Result :=  Rez;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_preturi_calculeazapretreceptie</obj_name>
  <obj_hashval>00a736b4b5dde80aa7d37abc895d2d4b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_preturi_calculeazapretreceptie(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT tipcateg numeric, INOUT pretlei numeric, INOUT apretachiz numeric, INOUT aproctva numeric, INOUT aparitate numeric, INOUT inlei numeric, INOUT rotunjire numeric, INOUT tiptvaneex numeric, INOUT apretmax numeric, INOUT apretinreg numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  PRET numeric := 0.0;
  LASTPRETACHIZ numeric := 0.0;
begin
   IF TIPCATEG = 1 THEN
     IF TIPTVANEEX = 0 THEN PRET := PRETLEI / (1 + aPROCTVA);
                       ELSE PRET := PRETLEI;
     END IF;
   ELSE
     IF TIPCATEG = 2 THEN
       IF TIPTVANEEX = 2 THEN PRET := PRETLEI + (PRETLEI - aPRETACHIZ) * aPROCTVA;
       ELSE
       IF TIPTVANEEX = 1 THEN PRET := PRETLEI * (1 +  aPROCTVA);
       ELSE PRET := PRETLEI;
       END IF;
       END IF;
     ELSE
      IF TIPCATEG = 3 THEN
        IF TIPTVANEEX = 2 THEN PRET := aPRETINREG * (1 + PRETLEI / 100)  + (aPRETINREG * (1 + PRETLEI / 100) - aPRETINREG) * aPROCTVA;
        ELSE
        IF TIPTVANEEX = 1 THEN PRET := aPRETINREG * (1 + PRETLEI / 100) * (1 + aPROCTVA);
        ELSE PRET := aPRETINREG * (1 + PRETLEI / 100);
        END IF;
        END IF;
      ELSE
       IF TIPCATEG = 4 THEN
         IF TIPTVANEEX = 2 THEN PRET := aPRETACHIZ * (1 + PRETLEI / 100)  + (aPRETACHIZ * (1 + PRETLEI / 100) - aPRETACHIZ) * aPROCTVA;
         ELSE
         IF TIPTVANEEX = 1 THEN PRET := aPRETACHIZ * (1 + PRETLEI / 100) * (1 + aPROCTVA);
         ELSE PRET := aPRETACHIZ * (1 + PRETLEI / 100);
         END IF;
         END IF;
       ELSE
        IF TIPCATEG = 5 THEN
          PRET := aPRETMAX + aPRETMAX * PRETLEI/100;
          IF TIPTVANEEX = 0 THEN PRET := PRET / (1 + aPROCTVA);END IF;
        ELSE
         IF TIPCATEG = 10 THEN
           LASTPRETACHIZ := PKG_INTRARI.GETLASTPRETACHIZ(aCODOBIECT);
           IF LASTPRETACHIZ = 0 THEN LASTPRETACHIZ := aPRETACHIZ;
           END IF;
           IF TIPTVANEEX = 2
           THEN PRET := LASTPRETACHIZ * (1 + PRETLEI / 100)  + (LASTPRETACHIZ * (1 + PRETLEI / 100) - aPRETACHIZ) * aPROCTVA;
           ELSE PRET := LASTPRETACHIZ * (1 + PRETLEI / 100) * (1 + aPROCTVA);
           END IF;
         ELSE
           IF TIPCATEG = 6 THEN
             IF TIPTVANEEX = 2 THEN PRET := aPRETINREG * (1 + PRETLEI / 100)  + (aPRETINREG * (1 + PRETLEI / 100) - aPRETINREG) * aPROCTVA;
             ELSE
             IF TIPTVANEEX = 1 THEN PRET := aPRETINREG * (1 + PRETLEI / 100) * (1 + aPROCTVA);
             ELSE PRET := aPRETINREG * (1 + PRETLEI / 100);
             END IF;
             END IF;
           ELSE
           IF TIPCATEG = 7 THEN
             IF TIPTVANEEX = 2 THEN PRET := aPRETACHIZ * (1 + PRETLEI / 100)  + (aPRETACHIZ * (1 + PRETLEI / 100) - aPRETACHIZ) * aPROCTVA;
             ELSE
             IF TIPTVANEEX = 1 THEN PRET := aPRETACHIZ * (1 + PRETLEI / 100) * (1 + aPROCTVA);
             ELSE PRET := aPRETACHIZ * (1 + PRETLEI / 100);
             END IF;
             END IF;
           END IF;
           END IF;
         END IF;
        END IF;
       END IF;
      END IF;
     END IF;
   END IF;
   IF (aPARITATE &lt;&gt; 1)AND(APARITATE &lt;&gt; 0) THEN
     PRET := aPARITATE * PRET;
   END IF;
   IF (PRET &lt;&gt; 0)AND(ROTUNJIRE &lt;&gt; 0) THEN
     PRET := (SELECT PKG_PRETURI_ROTUNJESTE_PRET.WME_RESULT FROM PKG_PRETURI_ROTUNJESTE_PRET(NULL, aCODOBIECT, PRET, INLEI));
   END IF;
   WME_Result := PRET;
   RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_preturi_get_incadrare_adaosm</obj_name>
  <obj_hashval>c8c947df098d43548d35581aadce0f54</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_preturi_get_incadrare_adaosm(dataref character varying, apretridicata numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
  DECLARE
    V_REC RECORD;
    V_REC1 RECORD;
    GASIT      numeric := 0;
    LIMINF     numeric := 0;
    COTAADAOST numeric := 0;
    CODADAOSM  numeric := 0;

    tmpTableCursorName varchar  :='TMP_CURSOR_PG';
    sSelect            varchar;
      sCreateTable     varchar;
  begin
    --Bogdan 04.12.2020
    execute 'drop table if exists ' || tmpTableCursorName;
    sCreateTable := 'CREATE TEMP TABLE '||tmpTableCursorName||' AS ';
    FOR V_REC IN (SELECT * FROM ADAOSM WHERE DATA &lt;= TO_DATE (DATAREF, 'dd.mm.yyyy') ORDER BY DATA) LOOP
      LIMINF := 0;
      FOR V_REC1 IN (SELECT * FROM ADAOSM1 WHERE CODADAOSM = V_REC.CODADAOSM ORDER BY LIMSUP) LOOP
        IF aPRETRIDICATA &gt; LIMINF AND aPRETRIDICATA &lt;= V_REC1.LIMSUP THEN
          GASIT      := 1;
          CODADAOSM  := V_REC1.CODADAOSM1;
          COTAADAOST := V_REC1.COTAADAOST;
        ELSE
          LIMINF := V_REC1.LIMSUP;
        END IF;
        EXIT  WHEN GASIT = 1;
      END LOOP;
      EXIT  WHEN GASIT = 1;
    END LOOP;

    IF GASIT = 1 THEN
      sSelect := ' SELECT '||CODADAOSM||' as CODADAOSM , '||COTAADAOST||' as COTAADAOST' ;
    ELSE
      sSelect := ' SELECT-1 as CODADAOSM, -1 as COTAADAOST' ;
    END IF;

    EXECUTE sCreateTable||sSelect;
  end;
  $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_preturi_get_lista_cat_preturi</obj_name>
  <obj_hashval>5364f7a650f49bf49ddf6e73744ce32a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_preturi_get_lista_cat_preturi(INOUT wme_result refcursor, INOUT acodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMPCURSOR REFCURSOR;
BEGIN
  --Florin 01.02.2023 - sinc. Oracle
  BEGIN
  OPEN TMPCURSOR FOR
    SELECT P.CODCATPRET, N.DEN_CATPRET, P.LEI, P.VALUTA, N.TIP, P.IMPLICIT, P.CODPRETM, M.SIMBOL, P.MONEDA
    FROM PRETM P, NCATPRET N, NMONEDE M
    WHERE P.CODOBIECT = ACODOBIECT AND  COALESCE( P.SUBUNITATEA, 1) = CASE WHEN  (SELECT WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE_DOC(NULL,NULL))=1 THEN 2
                                                                           ELSE  (SELECT WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE_DOC(NULL,NULL))
                                                                      END
      AND  P.CODCATPRET = N.CODCATPRET AND  M.CODMONEDA = COALESCE( P.MONEDA, 0)
    ORDER BY P.CODOBIECT , P.INDEXLOCAL ;
  EXCEPTION WHEN OTHERS THEN
    OPEN TMPCURSOR FOR SELECT -1;
  END;

  WME_Result :=  TMPCURSOR;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_preturi_get_lista_cat_preturi_receptie</obj_name>
  <obj_hashval>bbe4d17cb88419aaa3e15113dbb3136f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_preturi_get_lista_cat_preturi_receptie(INOUT wme_result refcursor, INOUT acodobiect numeric, INOUT acodgest numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMPCURSOR      REFCURSOR;
  CODCATPRETGEST numeric := 0;
  CATEGGEST      numeric := 0;
begin
  BEGIN
    SELECT COALESCE( CODCATPRET, 0) INTO CODCATPRETGEST FROM NGEST WHERE CODGEST = aCODGEST;
  EXCEPTION WHEN OTHERS THEN
    CODCATPRETGEST := 0;
  END;

  IF  CODCATPRETGEST &lt;&gt; 0 THEN
    BEGIN
      SELECT COALESCE( COUNT( *), 0)
      INTO CATEGGEST
      FROM PRETM P
      WHERE P.CODOBIECT = ACODOBIECT AND  COALESCE( P.SUBUNITATEA, 1) = CASE WHEN  (SELECT WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL))=1 THEN 2
                                                                             ELSE  (SELECT WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL))
                                                                        END
        AND  CODCATPRET = CODCATPRETGEST;
    EXCEPTION WHEN OTHERS THEN
      CATEGGEST := 0;
    END;
  END IF;

  BEGIN
    OPEN TMPCURSOR FOR
    SELECT P.CODCATPRET, N.DEN_CATPRET, P.LEI, P.VALUTA, N.TIP,
           (CASE WHEN  CATEGGEST &lt;&gt; 0 AND  P.CODCATPRET = CODCATPRETGEST THEN 1
                 WHEN  CATEGGEST &lt;&gt; 0 AND  P.CODCATPRET &lt;&gt; CODCATPRETGEST THEN 0
                 ELSE P.IMPLICIT
            END )  AS IMPLICIT,
           U.DEN_UM
    FROM PRETM P, NCATPRET N, NARTOBJ O, NART A, NUM U
    WHERE  P.CODOBIECT = ACODOBIECT AND  O.CODOBIECT = ACODOBIECT AND  A.CODARTICOL = O.CODARTICOL AND  U.CODUM = A.UM
      AND  COALESCE( P.SUBUNITATEA, 1) = CASE WHEN  (SELECT WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL))=1 THEN 2
                                              ELSE  (SELECT WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL))
                                         END
      AND  P.CODCATPRET = N.CODCATPRET AND N.TIP IN (1, 2, 3, 4, 5, 6, 7)
    ORDER BY P.CODOBIECT , P.INDEXLOCAL ;
  EXCEPTION WHEN OTHERS THEN
    OPEN TMPCURSOR FOR SELECT -1;
  END;

  WME_Result :=  TMPCURSOR;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_preturi_get_record_pret_articol</obj_name>
  <obj_hashval>ca08b0c739d9f2986916b6ae43872f79</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_preturi_get_record_pret_articol(INOUT wme_result refcursor, INOUT acodobiect numeric, INOUT acatpret numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMPCURSOR REFCURSOR;
begin
  BEGIN
    OPEN TMPCURSOR FOR
    SELECT P.CODCATPRET, P.LEI, P.VALUTA, P.MONEDA, N.TIP,
           (SELECT COALESCE( ROTUNJIRE, 0) FROM NARTOBJ WHERE CODOBIECT = aCODOBIECT) AS ROTLEI,
           (SELECT COALESCE( ROTVALUTA, 0) FROM NARTOBJ WHERE CODOBIECT = aCODOBIECT) AS ROVALUTA
    FROM PRETM P, NCATPRET N
    WHERE P.CODOBIECT = ACODOBIECT AND  COALESCE( P.SUBUNITATEA, 1) = CASE WHEN  (SELECT WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL))=1 THEN 2
                                                                           ELSE  (SELECT WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL))
                                                                      END
      AND  P.CODCATPRET = N.CODCATPRET AND  P.CODCATPRET = ACATPRET
    ORDER BY
      P.CODOBIECT , P.INDEXLOCAL ;
  EXCEPTION WHEN OTHERS THEN
    OPEN TMPCURSOR FOR SELECT -1;
  END;

  WME_Result :=  TMPCURSOR;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_preturi_get_record_pret_articol_umsec</obj_name>
  <obj_hashval>adef286e1a9ed5237d858950fa9974fd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_preturi_get_record_pret_articol_umsec(INOUT wme_result refcursor, INOUT acodobiect numeric, INOUT acatpret numeric, INOUT aumsec numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMPCURSOR REFCURSOR;
begin
  BEGIN
    OPEN TMPCURSOR FOR
    SELECT P.CODCATPRET, P.LEI, P.VALUTA, P.MONEDA, N.TIP,
           (SELECT COALESCE( ROTUNJIRE, 0) FROM NARTOBJ WHERE CODOBIECT = aCODOBIECT) AS ROTLEI,
           (SELECT COALESCE( ROTVALUTA, 0) FROM NARTOBJ WHERE CODOBIECT = aCODOBIECT) AS ROVALUTA,
           PAMB.LEI AS LEIUMSEC, PAMB.VALUTA AS VALUTAUMSEC
    FROM PRETM P, NCATPRET N, NARTAMB AMB, PRETMAMB PAMB
    WHERE P.CODOBIECT = ACODOBIECT AND  COALESCE( P.SUBUNITATEA, 1) = CASE WHEN  (SELECT WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL))=1 THEN 2
                                                                           ELSE  (SELECT WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL))
                                                                      END
      AND  P.CODCATPRET = N.CODCATPRET AND  P.CODCATPRET = ACATPRET AND  PAMB.CODPRETM = P.CODPRETM
      AND  AMB.CODOBIECT = ACODOBIECT AND  AMB.UMSEC = AUMSEC AND  PAMB.CODAMB = AMB.CODAMB
    ORDER BY
      P.CODOBIECT , P.INDEXLOCAL ;
  EXCEPTION WHEN OTHERS THEN
    OPEN TMPCURSOR FOR SELECT -1;
  END;

  WME_Result :=  TMPCURSOR;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_preturi_getcatpretvanzare</obj_name>
  <obj_hashval>951fcaba4ea0e162a26727583c2dbadb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_preturi_getcatpretvanzare(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT acodpart numeric, INOUT needmanualselection numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  CODCAT     numeric := 0;
  CODCATPART numeric:= 0;
  NR         numeric := 0;
BEGIN
  --Florin 01.11.2024 - fixat 63873
  NEEDMANUALSELECTION := 0;

  if aCODPART &lt;&gt; 0 then
    begin
      SELECT coalesce( CODCATEGPRET, 0) INTO CODCAT FROM NPART WHERE CODPART = aCODPART;
    exception
      when others then CODCAT := 0;
    end;

    CODCATPART := CODCAT;
  end if;
  if coalesce(CODCAT, 0) = 0 then
    CODCAT := coalesce( (fnc_GETVALCONSTANTALucru('CPRETVANZ')), '0')::numeric;
  end if;
  if coalesce(CODCAT, 0) = 0 and coalesce(fnc_GETVALCONSTANTALucru('DOARCATPART'), '0') = '1' then
    WME_Result := 0;
    return;
  end if;
  if coalesce(CODCAT, 0) &lt;&gt; 0 then
    SELECT count(*) INTO NR FROM PRETM P
    WHERE CODOBIECT = aCODOBIECT
      and coalesce( P.SUBUNITATEA, 1) = CASE when (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(null, null))= 1 then 2
                                             else (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(null,  null)) end
      and CODCATPRET = CODCAT;

    if NR = 0 then CODCAT := 0; end if;
  end if;
  if COALESCE(CODCAT, 0) = 0 then
    SELECT count(*) INTO NEEDMANUALSELECTION FROM PRETM P
    WHERE CODOBIECT = aCODOBIECT
      and coalesce( P.SUBUNITATEA, 1) = CASE when (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(null, null))= 1 then 2
                                             else (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(null, null)) end ;

    if NEEDMANUALSELECTION = 1 then
      SELECT CODCATPRET INTO CODCAT FROM PRETM P
      WHERE CODOBIECT = aCODOBIECT
        and coalesce( P.SUBUNITATEA, 1) = CASE when (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(null, null))= 1 then 2
                                               else (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(null, null)) end ;

      if CODCATPART &lt;&gt; 0
      then NEEDMANUALSELECTION := 1;
      else NEEDMANUALSELECTION := 0;
      end if;
    end if;
  end if;

  WME_Result := CODCAT;
  return;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_preturi_getcatpretvanzaresubunit</obj_name>
  <obj_hashval>95d805f9bba37c319fc512dbd38f01a3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_preturi_getcatpretvanzaresubunit(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT acodsubunit numeric, INOUT needmanualselection numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  CODCAT double precision := 0;
  NR     double precision := 0;
BEGIN
  --Florin 16.11.2020 - fixat #40811
  NEEDMANUALSELECTION := 0;
  IF  aCODSUBUNIT &lt;&gt; 0 THEN
    BEGIN
      SELECT COALESCE( CODCATPRET, 0) INTO CODCAT FROM NSUBUNIT WHERE CODSUBUNIT = aCODSUBUNIT;
    EXCEPTION WHEN OTHERS THEN
      CODCAT := 0;
    END;
  END IF;

  IF  CODCAT = 0 THEN
    CODCAT := COALESCE(fnc_getvalconstantalucru('CPRETVANZSUBUNIT')::NUMERIC, 0);
  END IF;

  IF  CODCAT &lt;&gt; 0 THEN
    SELECT COUNT( *) INTO NR FROM PRETM P
    WHERE CODOBIECT = aCODOBIECT AND  COALESCE( P.SUBUNITATEA, 1) = CASE WHEN  getsubunitate() = 1 THEN 2 ELSE  getsubunitate() END  AND  CODCATPRET = CODCAT;

    IF  NR = 0 THEN CODCAT := 0; END IF;
  END IF;

  IF  CODCAT = 0 THEN
    SELECT COUNT( *) INTO NEEDMANUALSELECTION FROM PRETM P
    WHERE CODOBIECT = aCODOBIECT AND  COALESCE( P.SUBUNITATEA, 1) = CASE WHEN  getsubunitate() = 1 THEN  2 ELSE  getsubunitate() END ;

    IF  NEEDMANUALSELECTION = 1 THEN
      SELECT CODCATPRET INTO CODCAT FROM PRETM P
      WHERE CODOBIECT = aCODOBIECT AND  COALESCE( P.SUBUNITATEA, 1) = CASE WHEN  getsubunitate() = 1 THEN 2 ELSE  getsubunitate() END ;

      NEEDMANUALSELECTION := 0;
    END IF;
  END IF;

  WME_Result :=  CODCAT;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_preturi_getpret</obj_name>
  <obj_hashval>e96bcfe7c1e550d9b95f7f8d3b0fb4a3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_preturi_getpret(INOUT wme_result numeric, INOUT atip numeric, INOUT acodobiect numeric, INOUT apart numeric, INOUT alocatie numeric, INOUT asubunit numeric, INOUT adataref date)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  pTipPromo numeric := 0;
  pTipContr numeric := 0;
  pTipOfe   numeric := 0;
  pResult   numeric;
begin
  IF aTip IS NULL  OR aCodObiect IS NULL  OR aPart IS NULL  OR aLocatie IS NULL  OR aSubunit IS NULL  OR aDataRef IS NULL THEN
    pResult := NULL;
  ELSE
    IF  aTip = 0 THEN
      pTipPromo := 75;
      pTipContr := 10;
      pTipOfe   := 51;
    ELSIF aTip = 1 THEN
      pTipPromo := 56;
      pTipContr := 27;
      pTipOfe   := 50;
    END IF;

    IF pResult IS NULL THEN
      SELECT MIN( p1.pret)
      INTO pResult
      FROM Promo P
      INNER JOIN Promo1    P1 ON  P1.CodPromo = P.CodPromo
      LEFT  JOIN PromoPart PP ON  PP.CodPromo = P.CodPromo
      LEFT  JOIN PromoSub  PS ON  PS.CodPromo = P.CodPromo
      WHERE  P.Anulat = 0 AND  P.Operat = 1 AND  P.TipPromotie = 1 AND  P.TipDoc = pTipPromo
        AND ((P.TipClasep = 0 AND COALESCE( PP.Partener, P.Partener, 0) IN (0, aPart) AND COALESCE( P.CodLocatie, 0) IN (0, aLocatie))
              OR
             (P.TipClasep = 1 AND COALESCE( PP.CodClaseP, 0) IN (SELECT CodClasa FROM Npart WHERE CodPArt = aPart))
            )
        AND Coalesce( PS.Subunitatea, P.Subunitatea, 1) IN (1, aSubunit) AND  P1.Codobiect = aCodObiect AND  P.DATASTART &lt;= aDataRef AND  P.DATAEND &gt;= aDataRef;
    END IF;

    IF pResult IS NULL THEN
      SELECT MIN( c1.pret * (1 + COALESCE( C1.AdDim, 0) / 100)  * (1 + COALESCE( C1.ProcDisc, 0) / 100) )
      INTO pResult
      FROM Contract C INNER JOIN Contract1 C1 ON  C1.CodContract = C.CodContract
      WHERE  C.Anulat = 0 AND  C.Operat = 1 AND  C.Activ = 1 AND  C.TipDoc = pTipContr
        AND  C.Partener = aPart AND C.CodLocatie IN (0, aLocatie) AND  C.Subunitatea = aSubunit AND  C1.Codobiect = aCodObiect
        AND  COALESCE( C1.CodObiectSec, 0) = 0
        AND  COALESCE( C1.DATASTART, C.DATASTART) &lt;= aDataRef AND  COALESCE( C1.DATASTOP, C.DATASTOP) &gt;= aDataRef;
    END IF;

    IF pResult IS NULL THEN
      SELECT MIN( O1.pret * (  1 + COALESCE( O1.ProcAdaos, 0) / 100)  * (  1 + COALESCE( O1.ProcDiscount, 0) / 100) )
      INTO pResult
      FROM Oferta O INNER JOIN Oferta1 O1 ON  O1.CodOferta = O.CodOferta
      WHERE O.Anulat = 0 AND  O.Operat = 1 AND  O.TipDoc = pTipOfe AND  O.Partener = aPart
        AND O.CodLocatie IN (0, aLocatie) AND  O.Subunitatea = aSubunit AND  O1.Codobiect = aCodObiect AND  O.DATASTART &lt;= aDataRef AND  O.DATAEND &gt;= aDataRef;
    END IF;
  END IF;

  WME_Result :=  pResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_preturi_getpret_intr</obj_name>
  <obj_hashval>9dc9e832ce673cdf0d10a43c098c31e2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_preturi_getpret_intr(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT apart numeric, INOUT alocatie numeric, INOUT asubunit numeric, INOUT adataref character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 07.01.2021 - fixat #42050
WME_Result :=  (SELECT PKG_PRETURI_GETPRET.WME_RESULT FROM PKG_PRETURI_GETPRET(NULL, 0, aCodObiect, aPart, aLocatie, aSubunit, To_Date( aDataRef, 'DD.MM.YYYY')));
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_preturi_getpretreceptie</obj_name>
  <obj_hashval>78c33b30f3bd219764ee230e77d7e253</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_preturi_getpretreceptie(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT acodgest numeric, INOUT apretachiz numeric, INOUT aproctva numeric, INOUT aparitate numeric, INOUT inlei numeric, INOUT rotunjire numeric, INOUT tiptvaneex numeric, INOUT apretmax numeric, INOUT apretinreg numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  CATPRETGEST numeric := 0;
  SUBUNITGEST NUMERIC(20)     := 0;
  PRET numeric := 0;
  TIPCATEG numeric := 0;
  PRETLEI numeric := 0;
  LASTPRETACHIZ numeric := 0;
  SKIPPRETIMPLICIT integer;
BEGIN
  --Florin 01.02.2023 - sinc. Oracle
  --Florin 25.11.2020 - fixat #41254
  IF  aCODGEST &lt;&gt; 0 THEN
    SELECT COALESCE(CODCATPRET, 0), CODSUBUNIT INTO CATPRETGEST, SUBUNITGEST FROM NGEST WHERE CODGEST = aCODGEST;
  END IF;
  SKIPPRETIMPLICIT := COALESCE(fnc_getvalconstantalucru('DOARCATGEST')::integer , 0)::integer;
  IF  CATPRETGEST &lt;&gt; 0 THEN
    BEGIN
      SELECT C.TIP, P.LEI INTO TIPCATEG, PRETLEI FROM PRETM P LEFT JOIN NCATPRET C ON  C.CODCATPRET = P.CODCATPRET
      WHERE  CODOBIECT = aCODOBIECT AND COALESCE(P.SUBUNITATEA, 1) = SUBUNITGEST
        AND P.CODCATPRET = CATPRETGEST;
    EXCEPTION WHEN OTHERS THEN
      TIPCATEG := 0;PRETLEI := 0;
    END;
  END IF;
  IF TIPCATEG = 0 THEN
    IF  SKIPPRETIMPLICIT = 1 THEN
      WME_Result :=  0;
      RETURN;
    ELSE
      BEGIN
        SELECT C.TIP, P.LEI INTO TIPCATEG, PRETLEI FROM PRETM P LEFT JOIN NCATPRET C ON  C.CODCATPRET = P.CODCATPRET
        WHERE CODOBIECT = aCODOBIECT AND  COALESCE( P.SUBUNITATEA, 1) =
          CASE WHEN GETSUBUNITATE() = 1 THEN 2
          ELSE GETSUBUNITATE() END AND  IMPLICIT = 1;
      EXCEPTION WHEN OTHERS THEN
        TIPCATEG := 0;    PRETLEI := 0;
      END;
    END IF;
  END IF;
  PRET := (SELECT PKG_PRETURI_CALCULEAZAPRETRECEPTIE.WME_RESULT FROM PKG_PRETURI_CALCULEAZAPRETRECEPTIE( NULL, aCODOBIECT, TIPCATEG, PRETLEI, aPRETACHIZ, aPROCTVA,
                                                                            aPARITATE, INLEI, ROTUNJIRE, TIPTVANEEX, aPRETMAX, aPRETINREG));
  WME_Result :=  PRET;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_preturi_getpretreceptiedincategorie</obj_name>
  <obj_hashval>3ed48eeb19e65ad134ee1dd0eb0012a1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_preturi_getpretreceptiedincategorie(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT catpretgest numeric, INOUT apretachiz numeric, INOUT aproctva numeric, INOUT aparitate numeric, INOUT inlei numeric, INOUT rotunjire numeric, INOUT tiptvaneex numeric, INOUT apretmax numeric, INOUT apretinreg numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
PRET numeric := 0;
TIPCATEG numeric := 0;
PRETLEI numeric;
BEGIN
  --Florin 25.11.2020 - fixat #41254
IF  CATPRETGEST &lt;&gt; 0
THEN
BEGIN
SELECT C.TIP, COALESCE( P.LEI, 0)
INTO TIPCATEG, PRETLEI
FROM PRETM P
LEFT JOIN NCATPRET C ON  C.CODCATPRET = P.CODCATPRET
WHERE
   CODOBIECT = aCODOBIECT AND  COALESCE( P.SUBUNITATEA, 1) = CASE
WHEN GETSUBUNITATE() = 1 THEN 2
ELSE GETSUBUNITATE()
END  AND  P.CODCATPRET = CATPRETGEST;
EXCEPTION WHEN OTHERS THEN
BEGIN
TIPCATEG := 0;
PRETLEI := 0;
END;
END;
END IF;
IF  TIPCATEG = 0
THEN
BEGIN
SELECT C.TIP, P.LEI
INTO TIPCATEG, PRETLEI
FROM PRETM P
LEFT JOIN NCATPRET C ON  C.CODCATPRET = P.CODCATPRET
WHERE
   CODOBIECT = aCODOBIECT AND  COALESCE( P.SUBUNITATEA, 1) = CASE
WHEN getsubunitate() THEN 2
ELSE getsubunitate()
END AND IMPLICIT = 1;
EXCEPTION WHEN OTHERS THEN
BEGIN
TIPCATEG := 0;
PRETLEI := 0;
END;
END;
END IF;
PRET := (SELECT PKG_PRETURI_CALCULEAZAPRETRECEPTIE.WME_RESULT FROM PKG_PRETURI_CALCULEAZAPRETRECEPTIE(NULL, aCODOBIECT, TIPCATEG, PRETLEI, aPRETACHIZ, aPROCTVA, aPARITATE, INLEI, ROTUNJIRE, TIPTVANEEX, aPRETMAX, aPRETINREG));
WME_Result :=  PRET;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_preturi_gettipcatpret</obj_name>
  <obj_hashval>1dc3c134f12889fa82d7b1fd06112315</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_preturi_gettipcatpret(INOUT wme_result numeric, INOUT acodcatpret numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
aTIP numeric := 0;
begin
BEGIN
SELECT COALESCE( TIP, 0)
INTO aTIP
FROM NCATPRET
WHERE
   CODCATPRET = aCODCATPRET;
EXCEPTION WHEN OTHERS THEN
aTIP := 0;
END;
WME_Result :=  aTIP;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_preturi_rotunjeste_pret</obj_name>
  <obj_hashval>23db232e8502a71c286635145de4e0e0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_preturi_rotunjeste_pret(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT apret numeric, INOUT inlei numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  ROT numeric := 0;
begin
  BEGIN
     IF  INLEI = 1
       THEN  SELECT COALESCE( ROTUNJIRE, 0) INTO ROT FROM NARTOBJ WHERE   CODOBIECT = aCODOBIECT;
       ELSE  SELECT COALESCE( ROTVALUTA, 0) INTO ROT FROM NARTOBJ WHERE   CODOBIECT = aCODOBIECT;
     END IF;
  EXCEPTION WHEN OTHERS THEN
    ROT := 5;
  END;
  WME_Result :=  (SELECT PKG_PRETURI_WMROTOPRET.WME_RESULT FROM PKG_PRETURI_WMROTOPRET(NULL, ROT, aPRET));
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_preturi_wmrotopret</obj_name>
  <obj_hashval>090538767cc0d871466ab578bc3a2aec</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_preturi_wmrotopret(rot numeric, pret numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  P numeric;
BEGIN
  --Adina 07.10.2020
  P :=  CASE ROT
           WHEN 1 THEN ROUND( PRET, 6)
           WHEN 2 THEN ROUND( PRET, 5)
           WHEN 3 THEN ROUND( PRET, 4)
           WHEN 4 THEN ROUND( PRET, 3)
           WHEN 5 THEN ROUND( PRET, 2)
           WHEN 6 THEN ROUND( PRET, 1)
           WHEN 7 THEN ROUND( PRET, 0)
           WHEN 8 THEN ROUND( PRET, 7)
           ELSE ROUND( PRET, 2)
         END ;
  RETURN P;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_preturi_wmrotopret</obj_name>
  <obj_hashval>88976fd939529d915c2b61ef5e317950</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_preturi_wmrotopret(INOUT wme_result numeric, INOUT rot numeric, INOUT pret numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  P numeric;
BEGIN
   P :=  CASE ROT
           WHEN 1 THEN ROUND( PRET, 6)
           WHEN 2 THEN ROUND( PRET, 5)
           WHEN 3 THEN ROUND( PRET, 4)
           WHEN 4 THEN ROUND( PRET, 3)
           WHEN 5 THEN ROUND( PRET, 2)
           WHEN 6 THEN ROUND( PRET, 1)
           WHEN 7 THEN ROUND( PRET, 0)
           WHEN 8 THEN ROUND( PRET, 7)
           ELSE ROUND( PRET, 2)
          END ;
   WME_Result := P;
   RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proc_act_date_actual_proc_date</obj_name>
  <obj_hashval>a31655533c358ff4675b24f5831136ea</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proc_act_date_actual_proc_date()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
null;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proc_act_date_drop_job</obj_name>
  <obj_hashval>ab47efe6071e5cc0162a2709ccc3189f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proc_act_date_drop_job()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
null;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proc_act_date_getvanzari</obj_name>
  <obj_hashval>8b6dc59f02834287c1c2cc1ae4d6bb66</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proc_act_date_getvanzari(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT asubunitatea numeric, INOUT aanluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aRez numeric;
begin
  BEGIN
    SELECT sum(i1.cant)
    INTO aRez
    FROM iesiri1 i1
         INNER JOIN iesiri i ON  i.codies = i1.codies
    WHERE
          i.an * 12 + i.luna = aAnLuna
      and i.tipdoc IN (19, 20, 21, 22)
      and i.anulat = 0
      and COALESCE(i.custodie, 0) = 0;
  EXCEPTION WHEN others THEN
    aRez := 0;
  END;

  WME_Result :=  aRez;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proc_act_date_setgdefaultname</obj_name>
  <obj_hashval>9ff3615c9291ef3a9303dab9f607540c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proc_act_date_setgdefaultname(agdefaultname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PROC_ACT_DATE.gDefaultName',agDefaultName,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proc_act_date_sp_insertrecord</obj_name>
  <obj_hashval>6059cadb32bd7a2727a95fb9774cf6ef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proc_act_date_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
null;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proc_act_date_sp_postrecords</obj_name>
  <obj_hashval>756be126d78bb4063014999d215b0b70</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proc_act_date_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
null;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proc_act_date_updatestocart</obj_name>
  <obj_hashval>ec635e9e090274a57d9b5b5897ea13ec</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proc_act_date_updatestocart()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  N             RECORD;
  V_REC         RECORD;
  aAnLunaMin    NUMERIC :=0;
  aAnLunaCurent numeric;
  aLunaCurent   numeric;
  aAnCurent     numeric;
  Vanz          numeric;
BEGIN
  --Adina 19.04.2021
  BEGIN
    SELECT aninitial * 12 + lunainitiala, anmaxim * 12 + lunamaxima, anmaxim, lunamaxima
    INTO aAnLunaMin, aAnLunaCurent, aAnCurent, aLunaCurent
    FROM firmaluni;
  EXCEPTION WHEN others THEN
    aAnLunaMin := 0;
  END;

  FOR N IN (SELECT OBJ.codobiect, S.CODSUBUNIT SUBUNITATE FROM NARTOBJ OBJ, NSUBUNIT S) LOOP
    INSERT INTO nartobjsubunit (CODS, CODOBIECT, SUBUNITATE)
    VALUES (NEXTVAL('SEQ_NARTOBJSUBUNIT_CODS'), N.CODOBIECT, N.SUBUNITATE) ;
  END LOOP;

  IF  aAnLunaMin = 0 THEN
    return;
  END IF;

  IF  aAnLunaCurent &gt;= 2018 * 12 + 1 THEN
    FOR v_rec IN
    (
    SELECT codobiect, COALESCE(procstocmin, 0) PROCSTOCMIN, COALESCE(procstocmed, 0) PROCSTOCMED, COALESCE(procstocmax, 0) PROCSTOCMAX, subunitate SUBUNITATEA
    FROM nartobjsubunit
    WHERE (codgest IS NULL  or  codgest = 0)
    ORDER BY subunitatea , codobiect
    )
    LOOP
      Vanz := (SELECT pkg_proc_act_date_GetVanzari.wme_result
               FROM pkg_proc_act_date_GetVanzari(NULL,v_rec.codobiect, v_rec.subunitatea, aAnLunaCurent - 12)
              );
      UPDATE nartobjsubunit
      SET
      stocmin = Vanz,
      stocmed = Vanz + v_rec.procstocmed / 100 * Vanz,
      stocmax = Vanz + v_rec.procstocmax / 100 * Vanz
      WHERE codobiect = v_rec.codobiect
       and  subunitate = v_rec.subunitatea
       and (  codgest IS NULL  or  codgest = 0);
    END LOOP;
  ELSE
    EXECUTE 'DO $$
        declare Vanz NUMERIC(20,7);
        begin
          for v_rec in (select codobiect, coalesce(procstocmin,0) procstocmin, coalesce(procstocmed,0) procstocmed, coalesce(procstocmax,0) procstocmax, subunitate subunitatea
                      from nartobjsubunit
                      where (codgest is null or codgest = 0 )
                      order by subunitatea, codobiect
                      ) loop
          begin
            case ' || coalesce(aLunaCurent,'') || '
            when  1 then select coalesce( l1,0) into Vanz from medie_vanz where codobiect = v_rec.codobiect and subunitatea = v_rec.subunitatea;
            when  2 then select coalesce( l2,0) into Vanz from medie_vanz where codobiect = v_rec.codobiect and subunitatea = v_rec.subunitatea;
            when  3 then select coalesce( l3,0) into Vanz from medie_vanz where codobiect = v_rec.codobiect and subunitatea = v_rec.subunitatea;
            when  4 then select coalesce( l4,0) into Vanz from medie_vanz where codobiect = v_rec.codobiect and subunitatea = v_rec.subunitatea;
            when  5 then select coalesce( l5,0) into Vanz from medie_vanz where codobiect = v_rec.codobiect and subunitatea = v_rec.subunitatea;
            when  6 then select coalesce( l6,0) into Vanz from medie_vanz where codobiect = v_rec.codobiect and subunitatea = v_rec.subunitatea;
            when  7 then select coalesce( l7,0) into Vanz from medie_vanz where codobiect = v_rec.codobiect and subunitatea = v_rec.subunitatea;
            when  8 then select coalesce( l8,0) into Vanz from medie_vanz where codobiect = v_rec.codobiect and subunitatea = v_rec.subunitatea;
            when  9 then select coalesce( l9,0) into Vanz from medie_vanz where codobiect = v_rec.codobiect and subunitatea = v_rec.subunitatea;
            when 10 then select coalesce(l10,0) into Vanz from medie_vanz where codobiect = v_rec.codobiect and subunitatea = v_rec.subunitatea;
            when 11 then select coalesce(l11,0) into Vanz from medie_vanz where codobiect = v_rec.codobiect and subunitatea = v_rec.subunitatea;
            when 12 then select coalesce(l12,0) into Vanz from medie_vanz where codobiect = v_rec.codobiect and subunitatea = v_rec.subunitatea;
            end case;
          exception when others then Vanz := 0;
          end;
          update nartobjsubunit set
          stocmin = Vanz,
          stocmed = Vanz + v_rec.procstocmed/100*Vanz,
          stocmax = Vanz + v_rec.procstocmax/100*Vanz
          where codobiect = v_rec.codobiect and subunitate = v_rec.subunitatea and (codgest is null or codgest = 0);
        end loop;
        end $$;';
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_procintretinere_getstarejob</obj_name>
  <obj_hashval>a502c81d0debe252deeb72332cab7c80</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_procintretinere_getstarejob(INOUT wme_result numeric, INOUT den_sched character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  iResult numeric;
begin
  BEGIN
    SELECT CASE WHEN  enabled='TRUE' THEN 1 ELSE  0 END , SCHEDULE_NAME
    INTO iresult, DEN_SCHED
    FROM user_scheduler_jobs
    WHERE job_name = 'ACT_STARE_NIRSER';
  EXCEPTION WHEN others THEN
    iResult   := -1;
    DEN_SCHED := '?';
  END;

  WME_Result :=  iresult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_procintretinere_setjob</obj_name>
  <obj_hashval>e5a142cd91a6a9a2adbb4122c886b8f2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_procintretinere_setjob(asched character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
stareJOB numeric;
S varchar;
begin
STAREJOB := (SELECT PKG_PROCINTRETINERE_GETSTAREJOB.WME_RESULT FROM PKG_PROCINTRETINERE_GETSTAREJOB(NULL, S));
IF  stareJOB = 1
THEN
PERFORM dbms_scheduler.disable( 'ACT_STARE_NIRSER');
END IF;
IF  STAREJOB = 0
THEN
PERFORM dbms_scheduler.enable( 'ACT_STARE_NIRSER');
END IF;
IF  STAREJOB = -1
THEN
PERFORM DBMS_SCHEDULER.create_job( job_name =&gt; 'ACT_STARE_NIRSER', job_type =&gt; 'STORED_PROCEDURE', job_action =&gt; 'PKG_PROCINTRETINERE.UPDATE_NIRSER_DATAPROD', schedule_name =&gt; ASCHED, Auto_drop =&gt; false);
PERFORM dbms_scheduler.enable( 'ACT_STARE_NIRSER');
END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_procintretinere_update_nirser_dataprod</obj_name>
  <obj_hashval>88f96756795ba2acf4c1acf6cc921a5f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_procintretinere_update_nirser_dataprod()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN (SELECT OBJ.CODOBIECT, NS.CODNIRSTOC, OBJ.ZILEVALABIL, OBJ.ZILEDISTRIB
                FROM NARTOBJ OBJ INNER JOIN NIRSTOC NS ON  OBJ.CODOBIECT = NS.CODOBIECT
               )
  LOOP
    UPDATE NIRSER NSER SET NSER.STARE = 1 WHERE NSER.CODNIRSTOC = V_REC.CODNIRSTOC AND  NSER.DATAPROD + V_REC.ZILEDISTRIB &gt;= TO_DATE( CURRENT_TIMESTAMP, 'DD.MM.YYYY');
    UPDATE NIRSER NSER SET NSER.STARE = 2 WHERE NSER.CODNIRSTOC = V_REC.CODNIRSTOC AND  NSER.DATAPROD + V_REC.ZILEVALABIL &gt;= TO_DATE( CURRENT_TIMESTAMP, 'DD.MM.YYYY');
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_actualizeazapretdinmat</obj_name>
  <obj_hashval>5c497052e31c7b9c1d99d3ec432a8d1d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_actualizeazapretdinmat(acodprodcomp numeric, adata character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_XXX RECORD;
  V_TMP RECORD;
  vPret   numeric;
  vPretV  numeric;
  vValMat numeric;
  vBanca  numeric;
begin
  vBanca := (fnc_GetValConstantaLucru ('BancaProdV'))::numeric;
  IF vBanca = 0
    or vBanca IS NULL THEN
    vBanca := (fnc_GetValConstantaLucru ('BancaSitV'))::numeric;
  END IF;

  FOR v_xxx IN (SELECT pc.codprodcomp, pc.codobiect, pc.cant, COALESCE (pc.CoefIndirecte, 0) COEFINDIRECTE, pc.tipreteta, pc.codmoneda
                FROM prodcomp pc
                WHERE pc.CodProdComp = aCodProdComp)
  LOOP
    vValMat := 0;
    FOR v_tmp IN (SELECT mat.cant, COALESCE (mat.pret, 0) PRET, COALESCE (mat.pretv, 0) PRETV
                  FROM prodmat mat
                  WHERE mat.codprodcomp = v_xxx.codprodcomp)
    LOOP
      IF v_xxx.codmoneda &gt; 0 THEN
        vValMat := vValMat + v_tmp.pretv * v_tmp.cant;
      ELSE
        vValMat := vValMat + v_tmp.pret * v_tmp.cant;
      END IF;
    END LOOP;

    IF v_xxx.codmoneda &gt; 0 THEN
      vPretV  := vValMat / v_xxx.cant;
      vPret   := vPretV  * (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA (NULL,v_xxx.CODMONEDA, vBanca, aData));
      vValMat := vValMat * (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA (NULL,v_xxx.CODMONEDA, vBanca, aData));
    ELSE
      vPret  := vValMat / v_xxx.cant;
      vPretV := vPret;
    END IF;

    UPDATE prodcomp
    SET pret = vPret, pretvaluta = vPretV, valmat = vValMat
    WHERE
      codprodcomp = v_xxx.Codprodcomp;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_aduvaloaremanopera</obj_name>
  <obj_hashval>6c584fe92d1fc499bdf1bdd08514fde0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_aduvaloaremanopera(INOUT wme_result numeric, INOUT acodprodcomp numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aVal  numeric;
begin
  --Florin 24.01.2022 - sinc. Oracle (28.12.2021)
  aVal := 0;
  FOR v_rec IN
  (
    SELECT COALESCE(mat.cant, 0) CANT, COALESCE(mat.valman, 0) VALMAN
    FROM prodmat mat
        INNER JOIN prodcomp pc ON  pc.codprodcomp = mat.codprodcomp
        INNER JOIN prodgest pg ON  pc.codprodcomp = pg.codprodcomp and  mat.codprodgest = pg.codprodgest
    WHERE pc.codprodcomp = aCodProdComp and  NOT mat.tip IN (3, 5)
  )
  LOOP
    aVal := aVal + v_rec.cant * v_rec.valman;
  END LOOP;

  FOR v_rec IN
  (
    SELECT COALESCE(man.BPS, 0) BPS, COALESCE(t1.tarif, 0) TARIF, COALESCE(man.tu, 0) TU
    FROM prodman man
        INNER JOIN prodcomp   pc ON  pc.codprodcomp = man.codprodcomp
        INNER JOIN prodgest   pg ON  pc.codprodcomp = pg.codprodcomp and  man.codprodgest = pg.codprodgest
          left  join TARIFEMAN1 T1 ON  t1.codtarif = man.codtarif AND GETANLUNALUCRU() BETWEEN T1.ALStart AND T1.ALStop
    WHERE pc.codprodcomp = aCodProdComp
  )
  LOOP
    IF  v_rec.BPS = 0 THEN
      aVal := aVal + Round((v_rec.Tarif * v_rec.TU / 60)::numeric, 7);
    ELSE
      aVal := aVal + Round((v_rec.Tarif * v_rec.TU / 60 / v_rec.BPS)::numeric, 7);
    END IF;
  END LOOP;

  WME_Result :=  aVal;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_aduvaloareregie</obj_name>
  <obj_hashval>7235f843d45d5f228ff02152c88d6939</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_aduvaloareregie(INOUT wme_result numeric, INOUT acodprodcomp numeric, INOUT avalregieman numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC             RECORD;
  aVal              numeric;
  KTipCoefIndirecte numeric;
  KRegieAntecalcul  numeric;
begin
  --Florin 24.01.2022 - sinc. Oracle (28.12.2021)
  aVal := 0;
  FOR v_rec IN
  (
    SELECT COALESCE(mat.cant, 0) CANT, COALESCE(mat.valregie, 0) VALREGIE
    FROM prodmat mat
        INNER JOIN prodcomp pc ON  pc.codprodcomp = mat.codprodcomp
        INNER JOIN prodgest pg ON  pc.codprodcomp = pg.codprodcomp and  mat.codprodgest = pg.codprodgest
    WHERE pc.codprodcomp = aCodProdComp and  NOT mat.tip IN (3, 5)
  )
  LOOP
    aVal := aVal + v_rec.cant * v_rec.valregie;
  END LOOP;

  IF  current_setting('PKG_PRODCOMP.KTipCoefIndirecte', true)::numeric = 3 and  current_setting('PKG_PRODCOMP.KRegieAntecalcul', true)::numeric = 2 THEN
    FOR v_rec IN (SELECT COALESCE(coefindirecte, 0) COEFINDIRECTE FROM prodcomp WHERE codprodcomp = acodprodcomp) LOOP
      aVal := aVal + v_rec.CoefIndirecte;
    END LOOP;
  ELSE
    FOR v_rec IN
    (
    SELECT COALESCE(pg.coefmat, COALESCE(g.coefcheltmat, 0)) COEFMAT, COALESCE(mat.cant, 0) CANT, COALESCE(mat.pret, 0) PRET, pc.cant LOT
    FROM prodcomp pc
        INNER JOIN prodmat  mat ON  mat.codprodcomp = pc.codprodcomp
        INNER JOIN prodgest pg  ON  pg.codprodcomp  = pc.codprodcomp and  mat.codprodgest = pg.codprodgest
        LEFT  JOIN ngest    g   ON  g.codgest = pg.codgest
    WHERE pc.codprodcomp = aCodProdComp and COALESCE(mat.tip, 3) IN (3, 5)
    )
    LOOP
      aVal := aVal + v_rec.Pret * v_rec.Cant / v_rec.lot * v_rec.CoefMat;
    END LOOP;

    aValRegieMan := 0;
    FOR v_rec IN
    (
    SELECT COALESCE(pg.coefman, COALESCE(g.coefcheltman, 0)) COEFMAN, COALESCE(man.bps, 0) BPS, COALESCE(t1.tarif, 0) TARIF, COALESCE(man.tu, 0) TU
    FROM prodcomp pc
      INNER JOIN prodman    man ON  man.codprodcomp = pc.codprodcomp
      INNER JOIN prodgest   pg  ON  pg.codprodcomp = pc.codprodcomp and  man.codprodgest = pg.codprodgest
      LEFT  JOIN ngest      g   ON  g.codgest = pg.codgest
      left  join TARIFEMAN1 T1  ON t1.codtarif = man.codtarif AND GETANLUNALUCRU() BETWEEN T1.ALStart AND T1.ALStop
    WHERE pc.codprodcomp = aCodProdComp
    )
    LOOP
      IF  v_rec.BPS = 0 THEN
        aVal         := aVal + Round((v_rec.Tarif * v_rec.TU / 60 * v_rec.CoefMan)::numeric, 7);
        aValRegieMan := aValRegieMan + Round((v_rec.Tarif * v_rec.TU / 60 * v_rec.CoefMan)::numeric, 7);
      ELSE
        aVal         := aVal + Round((v_rec.Tarif * v_rec.TU / 60 / v_rec.BPS * v_rec.CoefMan)::numeric, 7);
        aValRegieMan := aValRegieMan + Round((v_rec.Tarif * v_rec.TU / 60 / v_rec.BPS * v_rec.CoefMan)::numeric, 7);
      END IF;
    END LOOP;
  END IF;

  WME_Result :=  aVal;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_armeazatmps</obj_name>
  <obj_hashval>1fbbe5bb6eb6c57ce8de3d73b8bd7f25</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_armeazatmps(acodprodcomp numeric, adinmanevra boolean DEFAULT false)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  AnLunaInceput numeric;
  AnLunaCurent  numeric;
BEGIN
  --Florin 23.05.2023 - sinc. Oracle
  AnLunaInceput := 0;
  AnLunaCurent  := current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric * 12 + current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric;

  DELETE FROM prodcomp_clona;
  DELETE FROM prodman_clona;
  DELETE FROM prodmat_clona;
  DELETE FROM prodrez_clona;
  DELETE FROM tmp_manevra_compusi;

  IF aCodProdComp &gt; 0 THEN
    INSERT INTO prodcomp_clona (codprodcomp, codobiect, pret_v, pret_n)
    SELECT codprodcomp, codobiect, COALESCE (pret, 0) , 0
    FROM prodcomp WHERE CodProdComp = aCodProdComp;

    INSERT INTO prodman_clona (codman, valoare_v, valoare_n)
    SELECT man.codman, COALESCE (man.valoare, 0) , 0
    FROM prodman man INNER JOIN prodcomp pc ON pc.codprodcomp = man.codprodcomp
    WHERE pc.CodProdComp = aCodProdComp;

    INSERT INTO prodmat_clona (codmat, codobiect, pret_v, pret_n, codprodcomp)
    select distinct mat.codmat, mat.codobiect, nvl(mat.pret,0), 0, mat.codprodcomp
    FROM prodmat mat INNER JOIN prodcomp pc ON pc.codprodcomp = mat.codprodcomp
    WHERE pc.CodProdComp = aCodProdComp;

    INSERT INTO prodrez_clona (codrez, codprodcomp, pret_v, pret_n)
    SELECT rez.codrez, rez.codprodcomp, COALESCE (rez.pret, 0) , 0
    FROM prodrez rez INNER JOIN prodcomp pc ON pc.codprodcomp = rez.codprodcomp
    WHERE pc.codprodcomp::numeric = aCodProdComp and pc.tipreteta = 2;
  ELSE
    IF aDinManevra THEN
      INSERT INTO prodcomp_clona (codprodcomp, codobiect, pret_v, pret_n)
      SELECT pc.codprodcomp, pc.codobiect, COALESCE (pc.pret, 0) , 0
      FROM prodcomp pc
      WHERE
        COALESCE (pc.cant, 0) &lt;&gt; 0
        and COALESCE (pc.inactiv, 0) = 0
        and COALESCE (pc.invizibila, 0) = 0
        and EXISTS (SELECT tmp.valoare FROM tmp_manevra_liste tmp WHERE filtru = 'CODPRODCOMP' and tmp.valoare::numeric= pc.codprodcomp);

      INSERT INTO tmp_manevra_compusi (codobiect, pret)
      SELECT  DISTINCT codobiect, 0 FROM prodcomp_clona;

      INSERT INTO prodman_clona (codman, valoare_v, valoare_n)
      SELECT man.codman, COALESCE (man.valoare, 0) , 0
      FROM prodman man INNER JOIN prodcomp pc ON pc.codprodcomp = man.codprodcomp
      WHERE
        pc.cant &lt;&gt; 0
        and COALESCE (pc.inactiv, 0) = 0
        and COALESCE (pc.invizibila, 0) = 0
        and EXISTS (SELECT tmp.valoare FROM tmp_manevra_liste tmp WHERE filtru = 'CODPRODCOMP' and tmp.valoare::numeric = pc.codprodcomp);

      INSERT INTO prodmat_clona (codmat, codobiect, pret_v, pret_n, codprodcomp)
      SELECT mat.codmat, mat.codobiect, COALESCE (mat.pret, 0) , 0, mat.codprodcomp
      FROM prodmat mat INNER JOIN prodcomp pc ON pc.codprodcomp = mat.codprodcomp
      WHERE
        pc.cant &lt;&gt; 0
        and COALESCE (pc.inactiv, 0) = 0
        and COALESCE (pc.invizibila, 0) = 0
        and EXISTS (SELECT tmp.valoare FROM tmp_manevra_liste tmp WHERE filtru = 'CODPRODCOMP' and tmp.valoare::numeric = pc.codprodcomp);

      INSERT INTO prodrez_clona (codrez, codprodcomp, pret_v, pret_n)
      SELECT rez.codrez, rez.codprodcomp, COALESCE (rez.pret, 0) , 0
      FROM prodrez rez INNER JOIN prodcomp pc ON pc.codprodcomp = rez.codprodcomp
      WHERE
        pc.tipreteta = 2
        and EXISTS (SELECT tmp.valoare FROM tmp_manevra_liste tmp WHERE filtru = 'CODPRODCOMP' and tmp.valoare::numeric = pc.codprodcomp);
    ELSE
      INSERT INTO prodcomp_clona (codprodcomp, codobiect, pret_v, pret_n)
      SELECT pc.codprodcomp, pc.codobiect, COALESCE (pc.pret, 0) , 0
      FROM prodcomp pc
      WHERE
        COALESCE (pc.cant, 0) &lt;&gt; 0
        and COALESCE (pc.inactiv, 0) = 0
        and COALESCE (pc.invizibila, 0) = 0
        and Extract(Year from pc.Data) * 12 + Extract(month from pc.Data) &lt;= AnLunaCurent;

      INSERT INTO tmp_manevra_compusi (codobiect, pret)
      SELECT  DISTINCT codobiect, 0 FROM prodcomp_clona;

      INSERT INTO prodman_clona (codman, valoare_v, valoare_n)
      SELECT man.codman, COALESCE (man.valoare, 0) , 0
      FROM prodman man INNER JOIN prodcomp pc ON pc.codprodcomp = man.codprodcomp
      WHERE
        pc.cant &lt;&gt; 0
        and COALESCE (pc.inactiv, 0) = 0
        and COALESCE (pc.invizibila, 0) = 0
        and Extract (Year FROM pc.Data) * 12 + Extract (month FROM pc.Data) &lt;= AnLunaCurent;

      INSERT INTO prodmat_clona (codmat, codobiect, pret_v, pret_n, codprodcomp)
      SELECT mat.codmat, mat.codobiect, COALESCE (mat.pret, 0) , 0, mat.codprodcomp
      FROM prodmat mat INNER JOIN prodcomp pc ON pc.codprodcomp = mat.codprodcomp
      WHERE
        pc.cant &lt;&gt; 0
        and COALESCE (pc.inactiv, 0) = 0
        and COALESCE (pc.invizibila, 0) = 0
        and Extract (Year FROM pc.Data) * 12 + Extract (month FROM pc.Data) &lt;= AnLunaCurent;

      INSERT INTO prodrez_clona (codrez, codprodcomp, pret_v, pret_n)
      SELECT rez.codrez, rez.codprodcomp, COALESCE (rez.pret, 0) , 0
      FROM prodrez rez INNER JOIN prodcomp pc ON pc.codprodcomp = rez.codprodcomp
      WHERE
        pc.tipreteta = 2
        and Extract (Year FROM pc.Data) * 12 + Extract (month FROM pc.Data) &lt;= AnLunaCurent;
    END IF;
  END IF;

  IF current_setting ('PKG_PRODCOMP.DoCommit', true) THEN
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_baga_man_nou</obj_name>
  <obj_hashval>4e1fa8c964a3238775799baedb5e7ee6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_baga_man_nou(INOUT wme_result numeric, INOUT acodprodcomp numeric, INOUT anrop numeric, INOUT acodop numeric, INOUT acodloc numeric, INOUT acodtarif numeric, INOUT atu numeric, INOUT avaloare numeric, INOUT acodprodgest numeric, INOUT adsv numeric, INOUT abps numeric, INOUT atpi numeric, INOUT adetalii numeric, INOUT afix numeric, INOUT anivel numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  vCod      numeric;
  vDenumire varchar;
BEGIN
  --Florin 23.03.2021 - pkg_userfirme_postlogcucommit
  BEGIN
    SELECT denumire INTO vDenumire FROM noper WHERE codop = aCodOp;
  EXCEPTION WHEN others THEN
    vDenumire := '';
  END;

  FOR v_rec IN
  (
    SELECT COALESCE(pg.coefman, g.coefcheltman) COEF, pc.tippret, pc.codprodcomp, pc.data, 'OBJ:' || coalesce(obj.denumire,'') || ' (' || coalesce(pc.CODPRODCOMP::varchar ,'') || ') - adaug op.(' || coalesce(vdenumire,'') || ')' DOC
    FROM prodgest pg
        INNER JOIN ngest    g   ON  pg.codgest = g.codgest
        INNER JOIN prodcomp pc  ON  pg.codprodcomp = pc.codprodcomp
        INNER JOIN nartobj  obj ON  obj.codobiect  = pc.codobiect
    WHERE pc.codprodcomp = aCodProdComp and  pg.codprodgest = aCodProdGest
  )
  LOOP
    SELECT NEXTVAL('SEQ_PRODMAN_CODMAN') INTO vCod;

    INSERT INTO prodman(codman, codprodcomp, nrop, codop, codloc, codtarif, tu, valoare, codprodgest, dsv, bps, tpi, Detalii, Fix, Nivel)
    VALUES(vCod, aCodprodcomp, aNrop, aCodop, aCodloc, aCodtarif, aTu, aValoare, aCodprodgest, aDsv, aBps, aTpi, aDetalii, aFix, aNivel);

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_PRODCOMP.CT_MONITOR', true)))
    THEN
      PERFORM pkg_userfirme_postlogcucommit('PRODCOMP', current_setting('PKG_GLOBALS.USERNAME', true), 'M', v_rec.codprodcomp, current_setting('PKG_GLOBALS.FIRMANAME', true), current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, v_rec.Data, v_rec.Doc, null, current_setting('PKG_GLOBALS.EXE_VERSION', true));
    END IF;

    EXIT ;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_baga_mat_nou</obj_name>
  <obj_hashval>d4d122efd65441629c5a9dfcb5381efa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_baga_mat_nou(INOUT wme_result numeric, INOUT acodprodcomp numeric, INOUT acodobiect numeric, INOUT acant numeric, INOUT apret numeric, INOUT ad1 numeric, INOUT ad2 numeric, INOUT ad3 numeric, INOUT aindexlocal numeric, INOUT acantum1 numeric, INOUT acodprodgest numeric, INOUT atip numeric, INOUT apretorig numeric, INOUT avaloare numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  V_TMP     RECORD;
  vCod      numeric;
  aLot      numeric;
  vDenumire varchar;
BEGIN
  --Florin 23.01.2021 - pkg_userfirme_postlogcucommit
  BEGIN
    SELECT denumire INTO vDenumire FROM nartobj WHERE codobiect = aCodObiect;
  EXCEPTION WHEN others THEN
    vDenumire := '';
  END;

  IF  aTip = 1 THEN
    FOR v_rec IN
    (
    SELECT COALESCE(pg.coefmat, g.coefcheltmat) COEF, pc.tippret, pc.codprodcomp, pc.data, 'OBJ:' || coalesce(prod.denumire,'') || ' (' || coalesce(pc.CODPRODCOMP::varchar ,'') || ') - adaug mat.(' || coalesce(vdenumire,'') || ')' DOC
    FROM prodgest pg
        INNER JOIN ngest    g    ON  pg.codgest = g.codgest
        INNER JOIN prodcomp pc   ON  pg.codprodcomp = pc.codprodcomp
        INNER JOIN nartobj  prod ON  prod.codobiect = pc.codobiect
    WHERE pc.codprodcomp = aCodProdComp and  pg.codprodgest = aCodProdGest
    )
    LOOP
      SELECT NEXTVAL('SEQ_PRODMAT_CODMAT') INTO vCod;

      INSERT INTO prodmat(codmat, codprodcomp, codobiect, cant, pret, d1, d2, d3, indexlocal, cantum1, codprodgest, tip, pretorig, valoare)
      VALUES(vCod, aCodprodcomp, aCodobiect, aCant, aPret, aD1, aD2, aD3, aIndexlocal, aCantum1, aCodprodgest, 3, aPretorig, aValoare);

      BEGIN
        SELECT cant INTO aLot FROM prodcomp WHERE codprodcomp = aCodProdComp;
      EXCEPTION WHEN others THEN
        aLot := 1;
      END;

      IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_PRODCOMP.CT_MONITOR', true)))
      THEN
        PERFORM pkg_userfirme_postlogcucommit('PRODCOMP', current_setting('PKG_GLOBALS.USERNAME', true), 'M', v_rec.codprodcomp, current_setting('PKG_GLOBALS.FIRMANAME', true), current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, v_rec.Data, v_rec.Doc, null, current_setting('PKG_GLOBALS.EXE_VERSION', true));
      END IF;

      FOR v_tmp IN
      (
      SELECT pn.CODPROIECTNOD, pn.CODPROIECT, pn.CANT, pn.NODORIGINAL, pn.POZITIE, pn.CODRETETA, pn.TIP, pn.CODOBIECT, pn.INDEXPARINTE, pn.CODPRODMAT, pn.NIVEL, pn.ORDINE, COALESCE(pnm.maxpoz, 1) MAXPOZ, 'Adaug mat. (' || coalesce(pn.codproiectnod::varchar ,'') || ') - ' || coalesce(vDenumire,'') DOC, p.dataproiect
      FROM proiectnod pn
          INNER JOIN proiect p ON  p.codproiect = pn.codproiect
          LEFT  JOIN (SELECT max(pozitie) + 1 MAXPOZ, nodoriginal FROM proiectnod GROUP BY nodoriginal) pnm ON  pnm.nodoriginal = pn.codproiectnod
      WHERE pn.codreteta = aCodProdComp
      )
      LOOP
        INSERT INTO proiectnod(codproiectnod, codproiect, cant, nodoriginal, pozitie, codreteta, tip, codobiect, indexparinte, codprodmat, nivel, ordine)
        VALUES(NEXTVAL('SEQ_PROIECTNOD_CODPROIECTNOD'), v_tmp.codproiect, v_tmp.cant / aLot * acant, v_tmp.codproiectnod, v_tmp.maxpoz, 0, 3, acodobiect, coalesce(v_tmp.indexparinte,'') || '.' || coalesce(to_char(v_tmp.maxpoz, '00'),''), vCod, v_tmp.nivel + 1, 0);

        IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, 'MON_42'))
        THEN
          PERFORM pkg_userfirme_postlogcucommit('PROIECT', current_setting('PKG_GLOBALS.USERNAME', true), 'M', v_tmp.codproiect, current_setting('PKG_GLOBALS.FIRMANAME', true), current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, v_tmp.DataProiect, v_tmp.Doc, null, current_setting('PKG_GLOBALS.EXE_VERSION', true));
        END IF;
      END LOOP;

      EXIT ;
    END LOOP;
  ELSE
    FOR v_rec IN
    (
    SELECT COALESCE(pg.coefmat, g.coefcheltmat) COEF, pc.tippret, pc.codprodcomp, pc.data, 'OBJ:' || coalesce(prod.denumire,'') || ' (' || coalesce(pc.CODPRODCOMP::varchar ,'') || ') - adaug rez.(' || coalesce(vdenumire,'') || ')' DOC
    FROM prodgest pg
        INNER JOIN ngest    g    ON  pg.codgest = g.codgest
        INNER JOIN prodcomp pc   ON  pg.codprodcomp = pc.codprodcomp
        INNER JOIN nartobj  prod ON  prod.codobiect = pc.codobiect
    WHERE pc.codprodcomp = aCodProdComp and  pg.codprodgest = aCodProdGest
    )
    LOOP
      SELECT NEXTVAL('SEQ_PRODREZ_CODREZ') INTO vCod;

      INSERT INTO prodrez(codrez, codprodcomp, codobiect, cant, pret, d1, d2, d3, indexlocal, reziduu, cantum1, codprodgest)
      VALUES(vCod, aCodprodcomp, aCodobiect, aCant, aPret, aD1, aD2, aD3, aIndexlocal, 0, aCantum1, aCodprodgest);

      IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_PRODCOMP.CT_MONITOR', true)))
      THEN
        PERFORM pkg_userfirme_postlogcucommit('PRODCOMP', current_setting('PKG_GLOBALS.USERNAME', true), 'M', v_rec.codprodcomp, current_setting('PKG_GLOBALS.FIRMANAME', true), current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, v_rec.Data, v_rec.Doc, null, current_setting('PKG_GLOBALS.EXE_VERSION', true));
      END IF;

      EXIT ;
    END LOOP;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_bagamateriale</obj_name>
  <obj_hashval>76db4bd90ea6204b2fd111a1ff9825b0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_bagamateriale(acodproiect numeric, acodobiect numeric, acant numeric, acodprodcomp numeric, anivel numeric, acodoriginal numeric, aindex character varying, acodprodus numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_rec record;
begin
  --Florin 11.08.2025 - sinc. Oracle
  for v_rec in (select mat.codobiect, mat.tip, case when nvl(mat.tip,3) &lt;= 2 then nvl(pc.codprodcomp,0) else 0 end codprodcomp,
                       aCant/(CASE WHEN nvl(prod.cant,0) = 0 then 1 ELSE prod.cant END)*mat.cant cant,
                       aIndex||'.'||LPAD(to_char(IndexLocal), 2, '0') Idx,
                       mat.codmat, mat.indexlocal, o.denumire
                from prodmat mat
                     inner join prodcomp prod on prod.codprodcomp = mat.codprodcomp
                     inner join nartobj o on o.codobiect = mat.codobiect
                     left  join prodcomp pc   on pc.codobiect     = mat.codobiect and pc.implicit = 1
                where mat.codprodcomp = aCodProdComp
                order by mat.indexlocal
               ) loop
    insert into tmp_proiectnod(codproiect,cant,nodoriginal,pozitie,codreteta,codobiect,indexparinte,codprodmat,nivel,denumire,necesar, proiectant)
    values (aCodProiect, v_rec.cant, aCodProdComp, v_rec.indexlocal, v_rec.codprodcomp, v_rec.codobiect, v_rec.idx, v_rec.codmat, aNivel+1, LPAD(v_rec.denumire,
      Length(v_rec.denumire) + (aNivel+1)*2, ' '), v_rec.cant, v_rec.codobiect);
    if v_rec.CodProdComp &gt; 0 then
      PERFORM pkg_prodcomp_BagaMateriale_BagaMateriale(acodproiect, v_rec.CodObiect, v_rec.Cant, v_Rec.CodProdComp, aNivel+1, acodprodcomp, v_rec.idx, aCodProdus);
    end if;
  end loop;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_calcandgetpretref</obj_name>
  <obj_hashval>8a8edb45bf5142675e0c8436de1efbf3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_calcandgetpretref(INOUT wme_result numeric, INOUT acodprodcomp numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aValMat      numeric;
  aValMan      numeric;
  aValRegie    numeric;
  aPret        numeric;
  aValRegieMan numeric;
BEGIN
  --Florin current_timestamp -&gt; current_date::varchar

  --Bogdan 08.12.2020 to_char(current_date )
  aPret := 0;
  FOR v_rec IN (SELECT cant, COALESCE (tippret, 1) TIPPRET FROM prodcomp WHERE codprodcomp = acodprodcomp and cant &gt; 0) LOOP
    IF v_rec.TipPret = 1 THEN
      aValMat   := (SELECT PKG_PRODCOMP_AduValoareMateriale.WME_RESULT FROM PKG_PRODCOMP_AduValoareMateriale (NULL,aCodProdComp));
      aValMan   := (SELECT PKG_PRODCOMP_AduValoareManopera.WME_RESULT FROM PKG_PRODCOMP_AduValoareManopera (NULL,aCodProdComp));
      aValRegie := (SELECT PKG_PRODCOMP_AduValoareRegie.WME_RESULT FROM PKG_PRODCOMP_AduValoareRegie (NULL,aCodProdComp, aValRegieMan));
      aPret := aValMat / v_rec.Cant + aValMan + aValRegie;

      UPDATE prodcomp
      SET
      pret       = apret,
      pretvaluta =
                  CASE
                    WHEN COALESCE (codmoneda, 0) = 0 THEN apret
                    ELSE apret / (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT
                                  FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA ( NULL,COALESCE (codmoneda, 0) ,
                                                                              CASE WHEN (fnc_GetValConstantaLucru ('BancaProdV'))::NUMERIC = 0 THEN (fnc_GetValConstantaLucru ('BancaSitV'))::numeric
                                                                                   ELSE (fnc_GetValConstantaLucru ('BancaProdV'))::numeric
                                                                              END , to_char(CURRENT_DATE,'dd.mm.yyyy')))
                  END ,
      valmat      = aValMat,
      valman      = aValMan,
      valregie    = aValRegie,
      valregieMan = aValRegieMan,
      valag       = ag / 100 * (avalman + avalregieman)
      WHERE
        codprodcomp = aCodProdcomp;

      UPDATE prodcomp
      SET totpretfix = COALESCE (Pret, 0) + COALESCE (CoefIndirecte, 0) + COALESCE (ValAG, 0) , totpretcoef = COALESCE (Pret, 0) * (1.0 + COALESCE (CoefIndirecte, 0))
      WHERE
        codprodcomp = acodprodcomp;

      UPDATE prodcomp
      SET valprofit = COALESCE (Profit, 0) / 100 * COALESCE (TotPretFix, 0)
      WHERE
        codprodcomp = acodprodcomp;

      UPDATE prodcomp
      SET pretfinal = COALESCE (ValProfit, 0) + COALESCE (TotPretFix, 0)
      WHERE
        codprodcomp = acodprodcomp;

      UPDATE prodcomp
      SET
      TotPretFixV = TotPretFix /
        CASE
          WHEN COALESCE (codmoneda, 0) = 0 THEN 1
          ELSE (  SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT
                  FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA (NULL,COALESCE (codmoneda, 0) ,
                                                    CASE WHEN (fnc_GetValConstantaLucru ('BancaProdV'))::NUMERIC = 0 THEN (fnc_GetValConstantaLucru ('BancaSitV'))::numeric
                                                         ELSE (fnc_GetValConstantaLucru ('BancaProdV'))::numeric
                                                    END , to_char(CURRENT_DATE,'dd.mm.yyyy')))
        END ,
      TotPretCoefV = TotPretCoef /
        CASE
          WHEN COALESCE (codmoneda, 0) = 0 THEN 1
          ELSE (  SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT
                  FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA (NULL,COALESCE (codmoneda, 0) ,
                                                    CASE WHEN (fnc_GetValConstantaLucru ('BancaProdV'))::NUMERIC = 0 THEN (fnc_GetValConstantaLucru ('BancaSitV'))::numeric
                                                         ELSE (fnc_GetValConstantaLucru ('BancaProdV'))::numeric
                                                    END , to_char(CURRENT_DATE,'dd.mm.yyyy')))
        END ,
      PretFinalV = PretFinal /
        CASE
          WHEN COALESCE (codmoneda, 0) = 0 THEN 1
          ELSE (  SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT
                  FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA (NULL,COALESCE (codmoneda, 0) ,
                                                    CASE WHEN (fnc_GetValConstantaLucru ('BancaProdV'))::NUMERIC = 0 THEN (fnc_GetValConstantaLucru ('BancaSitV'))::numeric
                                                         ELSE (fnc_GetValConstantaLucru ('BancaProdV'))::numeric
                                                    END , to_char(CURRENT_DATE,'dd.mm.yyyy')))
        END
      WHERE
        codprodcomp = acodprodcomp;
    ELSE
      aValMat := (SELECT PKG_PRODCOMP_AduValoareMateriale.WME_RESULT FROM PKG_PRODCOMP_AduValoareMateriale (NULL,aCodProdComp));
      aPret   := aValMat / v_rec.Cant;

      UPDATE prodcomp
      SET
      pret = apret, pretvaluta =
        CASE
          WHEN COALESCE (codmoneda, 0) = 0 THEN apret
          ELSE apret / (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT
                        FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA (NULL,codmoneda,
                                                    CASE WHEN (fnc_GetValConstantaLucru ('BancaProdV'))::NUMERIC = 0 THEN (fnc_GetValConstantaLucru ('BancaSitV'))::numeric
                                                         ELSE (fnc_GetValConstantaLucru ('BancaProdV'))::numeric
                                                    END , to_char(CURRENT_DATE,'dd.mm.yyyy')))
        END , valmat = aValMat
      WHERE
        codprodcomp = aCodProdcomp;
    END IF;
  END LOOP;

  WME_Result := aPret;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_cloneazareteta</obj_name>
  <obj_hashval>68be532b608469f245fa4e2a3b2319dc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_cloneazareteta(INOUT wme_result numeric, INOUT acodprodcomp numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCod numeric;
begin
  PERFORM PKG_PRODCOMP_Set_Do_Commit(False);
  DELETE FROM tmp_prodcomp;
  DELETE FROM tmp_prodmat;
  DELETE FROM tmp_prodrez;
  DELETE FROM tmp_proiecte;
  DELETE FROM tmp_prodgest;
  DELETE FROM tmp_prodman;
  DELETE FROM tmp_prodsdv;
  DELETE FROM tmp_prodmas;
  DELETE FROM tmp_prodmatechiv;
  DELETE FROM tmp_prodnorme;
  DELETE FROM tmp_normemat;
  PERFORM PKG_PRODCOMP_SP_GOTORECORD(aCodProdComp);
  PERFORM PKG_PRODCOMP_SP_POSTRECORDS(1, aCod);
  PERFORM PKG_PRODCOMP_Set_Do_Commit(True);
  WME_Result :=  aCod;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_corectiecmdprodmat</obj_name>
  <obj_hashval>620aed34c2df1ea59db021d681da4e0c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_corectiecmdprodmat()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR v_rec IN
  (
    SELECT round((c1.cantacceptat / pc.cant * mat.cantmat)::numeric, 5) CANTNOU, cmdr.cant, cmdr.codcmdprodmat
    FROM comanda1 c1
    INNER JOIN prodcomp   pc      ON  pc.codprodcomp = c1.codreteta
    INNER JOIN (SELECT sum(cant) CANTMAT, codobiect, codcomanda1 FROM cmdprodmat GROUP BY codobiect, codcomanda1
               )          cmdmat  ON  cmdmat.codcomanda1 = c1.codcomanda1
    INNER JOIN (SELECT sum(cant) CANTMAT, codobiect, codprodcomp FROM prodmat GROUP BY codobiect, codprodcomp
               )          mat     ON  mat.codprodcomp = c1.codreteta and  cmdmat.codobiect = mat.codobiect
    INNER JOIN (SELECT count(*) NR, codobiect, codcomanda1 FROM cmdprodmat GROUP BY codobiect, codcomanda1
               )          catemat ON  catemat.codcomanda1 = c1.codcomanda1 and  catemat.codobiect = cmdmat.codobiect
    INNER JOIN cmdprodmat cmdr    ON  cmdr.codcomanda1 = c1.codcomanda1 and  cmdr.codobiect = cmdmat.codobiect
    WHERE
       round((cmdmat.cantmat)::numeric, 5) &lt;&gt; round((c1.cantacceptat / pc.cant * mat.cantmat)::numeric, 5) and  catemat.nr = 1
  )
  LOOP
    UPDATE cmdprodmat
    SET
    rest = rest + v_rec.cantnou - v_rec.cant,
    cant = v_rec.cantnou
    WHERE
     codcmdprodmat = v_rec.codcmdprodmat;
  END LOOP;

  UPDATE iesprodlink l SET cant = (SELECT i1.cant FROM iesiri1 i1 WHERE l.codies1 = i1.codies1);

  UPDATE cmdprodmat cmd
  SET
  rest = cant - (SELECT sum(l.cant) FROM iesprodlink l WHERE l.codcmdprodmat = cmd.codcmdprodmat)
  WHERE cmd.tip = 1;

  UPDATE cmdprodmat prod
  SET
  rest = cant - (SELECT sum(l.cant) FROM intrprodlink l WHERE l.codliniecomanda = prod.codcmdprodmat)
  WHERE prod.tip = 0;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_corectiematduplinproj</obj_name>
  <obj_hashval>dfeab4dba0a5387b3b29fa929bab050f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_corectiematduplinproj()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  V_TMP RECORD;
  nrMatRet  numeric;
  nrMatProj numeric;
begin
  FOR v_rec IN
  (
    SELECT par.codproiectnod NODORIGINAL, mat.codprodcomp, mat.codmat, mat.codobiect, mat.cant * par.cant / pc.cant CANT, mat.cant CANTRET
    FROM prodmat mat
    INNER JOIN prodcomp   pc  ON  mat.codprodcomp = pc.codprodcomp
    INNER JOIN proiectnod par ON  mat.codprodcomp = par.codreteta
    LEFT  JOIN proiectnod nod ON  par.codproiectnod = nod.nodoriginal and  mat.codmat = nod.codprodmat
    WHERE COALESCE(nod.codproiectnod, 0) = 0
  )
  LOOP
    SELECT count(*) INTO nrMatRet  FROM prodmat    WHERE codprodcomp = v_rec.codprodcomp and  codobiect = v_rec.codobiect and  cant = v_rec.cantret;
    SELECT count(*) INTO nrMatProj FROM proiectnod WHERE nodoriginal = v_rec.nodoriginal and  codobiect = v_rec.codobiect and  cant = v_rec.cant;

    IF  nrMatProj = nrMatRet THEN
      FOR v_tmp IN
      (
        SELECT nodord.codproiectnod, matord.codmat
        FROM (SELECT codmat, ROW_NUMBER() ORDINE FROM prodmat WHERE codobiect = v_rec.codobiect and  cant = v_rec.cantret and  codprodcomp = v_rec.codprodcomp
             ) matord
        INNER JOIN (SELECT codproiectnod, ROW_NUMBER() ORDINE FROM proiectnod WHERE codobiect = v_rec.codobiect and  cant = v_rec.cant and  nodoriginal = v_rec.nodoriginal
                   ) nodord ON  matord.ordine = nodord.ordine
      )
      LOOP
        UPDATE proiectnod SET codprodmat = v_tmp.codmat WHERE codproiectnod = v_tmp.codproiectnod;
      END LOOP;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_corectiematduplinprojbycod</obj_name>
  <obj_hashval>440ebff36b422fcdbe504ebc5f066fe3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_corectiematduplinprojbycod(acodproiect numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  V_TMP RECORD;
  nrMatRet  numeric;
  nrMatProj numeric;
begin
  FOR v_rec IN
  (
  SELECT par.codproiectnod NODORIGINAL, mat.codprodcomp, mat.codmat, mat.codobiect, mat.cant * par.cant / pc.cant CANT, mat.cant CANTRET
  FROM prodmat mat
      INNER JOIN prodcomp   pc  ON  mat.codprodcomp = pc.codprodcomp
      INNER JOIN proiectnod par ON  mat.codprodcomp = par.codreteta
      LEFT  JOIN proiectnod nod ON  par.codproiectnod = nod.nodoriginal and  mat.codmat = nod.codprodmat
  WHERE COALESCE(nod.codproiectnod, 0) = 0 and  par.codproiect = aCodProiect
  )
  LOOP
    SELECT count(*) INTO nrMatRet  FROM prodmat    WHERE codprodcomp = v_rec.codprodcomp and  codobiect = v_rec.codobiect and  cant = v_rec.cantret;
    SELECT count(*) INTO nrMatProj FROM proiectnod WHERE nodoriginal = v_rec.nodoriginal and  codobiect = v_rec.codobiect and  cant = v_rec.cant;

    IF  nrMatProj = nrMatRet THEN
      FOR v_tmp IN
      (
        SELECT nodord.codproiectnod, matord.codmat
        FROM (SELECT codmat, ROW_NUMBER() ORDINE FROM prodmat WHERE codobiect = v_rec.codobiect and  cant = v_rec.cantret and  codprodcomp = v_rec.codprodcomp
             ) matord
        INNER JOIN (SELECT codproiectnod, ROW_NUMBER() ORDINE FROM proiectnod WHERE codobiect = v_rec.codobiect and  cant = v_rec.cant and  nodoriginal = v_rec.nodoriginal
                   ) nodord ON  matord.ordine = nodord.ordine
      )
      LOOP
        UPDATE proiectnod SET codprodmat = v_tmp.codmat WHERE codproiectnod = v_tmp.codproiectnod;
      END LOOP;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_curataextreme</obj_name>
  <obj_hashval>0b80df4041f38261c6469fc67c8419f8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_curataextreme(amarja numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TipPret numeric;
begin
  IF  aMarja &gt; 0 THEN
    PERFORM PKG_ProdComp_SeteazaStare(aMarja);
  END IF;

  DELETE FROM tmp_manevra_preturi_Detalii WHERE Stare = 2;

  TipPret := (fnc_GetValConstantaLucru('TipEvaluarePret'))::numeric;
  IF  TipPret &gt; 3 or  TipPret &lt; 1 THEN
    TipPret := 2;
  END IF;

  IF  TipPret = 1 THEN
    UPDATE tmp_manevra_preturi p
    SET
    pret = (SELECT max(COALESCE(pret, 0)) FROM tmp_manevra_preturi_Detalii WHERE codobiect = p.codobiect GROUP BY codobiect)
    WHERE COALESCE(p.Stare, 0) &lt; 3;
  ELSE
    IF  TipPret = 3 THEN
      UPDATE tmp_manevra_preturi p
      SET
      pret = (SELECT min(COALESCE(pret, 0)) FROM tmp_manevra_preturi_Detalii WHERE codobiect = p.codobiect GROUP BY codobiect)
      WHERE COALESCE(p.Stare, 0) &lt; 3;
    ELSE
      UPDATE tmp_manevra_preturi p
      SET
      pret = (SELECT avg(COALESCE(pret, 0)) FROM tmp_manevra_preturi_Detalii WHERE codobiect = p.codobiect GROUP BY codobiect)
      WHERE COALESCE(p.Stare, 0) &lt; 3;
    END IF;
  END IF;

  PERFORM PKG_PRODCOMP_SeteazaStare(aMarja);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_docommit</obj_name>
  <obj_hashval>6c0d213715e64496e749369cd64cb4d8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_docommit(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PRODCOMP.DoCommit', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := true;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_doverif</obj_name>
  <obj_hashval>bf45c39649e2b788dc07ca66ef05295f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_doverif()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  aCount numeric;
  aPret  numeric;
begin
  DELETE FROM tmp_atentionari;

  UPDATE prodcomp SET generic = 0, implicit = 0 WHERE inactiv = 1;
  UPDATE prodcomp SET generic = 0, implicit = 0 WHERE ascuns = 1;

  FOR v_rec IN (SELECT pc.codobiect, count(*)
                FROM prodcomp pc
                WHERE COALESCE(pc.ascuns, 0) = 0 and  COALESCE(pc.inactiv, 0) = 0 and  pc.generic = 1 and  pc.codprodcomp &gt;= 100
                GROUP BY pc.codobiect HAVING count(*) &gt; 1
               )
  LOOP
    INSERT INTO tmp_atentionari(tip, camp1, camp2)
    SELECT 4, codprodcomp, codobiect FROM prodcomp WHERE codobiect = v_rec.codobiect and  COALESCE(ascuns, 0) = 0 and  COALESCE(inactiv, 0) = 0 and  generic = 1;
  END LOOP;

  FOR v_rec IN (SELECT pc.codobiect, count(*)
                FROM prodcomp pc
                WHERE COALESCE(pc.ascuns, 0) = 0 and  COALESCE(pc.inactiv, 0) = 0 and  pc.implicit = 1 and  pc.codprodcomp &gt;= 100
                GROUP BY pc.codobiect HAVING count(*) &gt; 1
               )
  LOOP
    INSERT INTO tmp_atentionari(tip, camp1, camp2)
    SELECT 5, codprodcomp, codobiect FROM prodcomp WHERE codobiect = v_rec.codobiect and  COALESCE(ascuns, 0) = 0 and  COALESCE(inactiv, 0) = 0 and  implicit = 1;
  END LOOP;

  FOR v_rec IN (SELECT  DISTINCT pc.codobiect
                FROM prodcomp pc
                WHERE NOT  EXISTS (SELECT p.codprodcomp FROM prodcomp p
                                   WHERE p.codobiect = pc.codobiect and  COALESCE(p.ascuns, 0) = 0 and  p.generic = 1 and  COALESCE(inactiv, 0) = 0
                                  )
                   and  COALESCE(pc.ascuns, 0) = 0 and  COALESCE(pc.inactiv, 0) = 0 and  pc.codprodcomp &gt;= 100
               )
  LOOP
    INSERT INTO tmp_atentionari(tip, camp1, camp2)
    SELECT 6, codprodcomp, codobiect FROM prodcomp WHERE codobiect = v_rec.codobiect and  COALESCE(ascuns, 0) = 0 and  COALESCE(inactiv, 0) = 0;
  END LOOP;

  FOR v_rec IN (SELECT  DISTINCT pc.codobiect
                FROM prodcomp pc
                WHERE NOT  EXISTS (SELECT p.codprodcomp FROM prodcomp p
                                   WHERE p.codobiect = pc.codobiect and  COALESCE(p.ascuns, 0) = 0 and  p.implicit = 1 and  COALESCE(inactiv, 0) = 0
                                  )
                   and  COALESCE(pc.ascuns, 0) = 0 and  COALESCE(pc.inactiv, 0) = 0 and  pc.codprodcomp &gt;= 100
               )
  LOOP
    INSERT INTO tmp_atentionari(tip, camp1, camp2)
    SELECT 7, codprodcomp, codobiect FROM prodcomp WHERE codobiect = v_rec.codobiect and  COALESCE(ascuns, 0) = 0 and  COALESCE(inactiv, 0) = 0;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_genprjimport</obj_name>
  <obj_hashval>5a06b91b7c60470b09d6da3ebb419957</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_genprjimport()
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  aCodProiect numeric(20);
  aCount numeric(20);
  aActiv numeric(1);
  aFinalizat numeric(1);
  v_rec record;
BEGIN
  --Florin 28.03.2022
  for v_rec in (
    select tmp.valoare codprodcomp
    from tmp_manevra_liste tmp
    where tmp.filtru = 'CODPRODCOMP'
  ) loop
    aActiv := 1;
    aFinalizat := aActiv;
    aCodProiect := pkg_proiect_GENPRJFROMRETETA(v_rec.CodProdComp, 1);
    select count(*) into aCount from proiectnod where codproiect = aCodProiect and tip &lt; 3 and codreteta = 0;
    if aCount &gt; 0 then
      aActiv := 0;
      aFinalizat := 0;
    end if;
    update proiect set Activ = aActiv, Finalizat = aFinalizat where codproiect = aCodProiect;
  end loop;
end;
 $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getct_monitor</obj_name>
  <obj_hashval>2fa0760eb72f1d6dff68bf593fd23e08</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PRODCOMP.CT_MONITOR', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_37';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getdocommit</obj_name>
  <obj_hashval>3741fb6bf7fe4aa35650411fa0d22e7b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getdocommit(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PRODCOMP.DoCommit', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := true;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getkregieantecalcul</obj_name>
  <obj_hashval>9c3d1c2a80d86e0154cd1e21c4ea5636</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getkregieantecalcul(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PRODCOMP.KRegieAntecalcul', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getktippret</obj_name>
  <obj_hashval>af335f7914efe6dcee78bfada6d75590</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getktippret(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PRODCOMP.KTipPret', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getmasas</obj_name>
  <obj_hashval>c4d4c8fe09c2796d8a02f0de10454733</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getmasas(INOUT wme_result numeric, acodobiect numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_rec record;
  iResult numeric;
  aCount  numeric;
begin
  begin
  select coalesce(masa,0) into iResult from nartobj where codobiect = acodobiect;
  exception when others then iResult := 0;
  end;

  select count(*) into acount from prodcomp where codobiect = aCodObiect;
  if acount &gt; 1 then
    select count(*) into acount from prodcomp where codobiect = aCodObiect and implicit = 1;
    if acount = 1 then
      for v_rec in (select m.codobiect, o.masa, m.tip, m.cant
                    from prodcomp pc
                         inner join prodmat m on pc.codprodcomp = m.codprodcomp
                         inner join nartobj o on o.codobiect = m.codobiect
                    where pc.codobiect = acodobiect and pc.implicit = 1) loop
        if v_rec.tip &lt; 3 then
          iResult := iResult + v_rec.cant * (SELECT PKG_PRODCOMP_GETMASAS.WME_RESULT FROM PKG_PRODCOMP_GETMASAS (NULL,ACODOBIECT));
        else
          iResult := iResult + v_rec.cant * v_rec.masa;
        end if;
      end loop;
    elseif acount = 0 then
      select count(*) into acount from prodcomp where codobiect = aCodObiect and generic = 1;
      if acount = 1 then
        for v_rec in (select m.codobiect, o.masa, m.tip, m.cant
                      from prodcomp pc
                           inner join prodmat m on pc.codprodcomp = m.codprodcomp
                           inner join nartobj o on o.codobiect = m.codobiect
                      where pc.codobiect = acodobiect and pc.generic = 1) loop
          if v_rec.tip &lt; 3 then
            iResult := iResult + v_rec.cant * (SELECT PKG_PRODCOMP_GETMASAS.WME_RESULT FROM PKG_PRODCOMP_GETMASAS (NULL,ACODOBIECT));
          else
            iResult := iResult + v_rec.cant * v_rec.masa;
          end if;
        end loop;
      end if;
    end if;
  elseif acount = 1 then
    iResult := 0;
    for v_rec in (select m.codobiect, o.masa, m.tip, m.cant
                  from prodcomp pc
                       inner join prodmat m on pc.codprodcomp = m.codprodcomp
                       inner join nartobj o on o.codobiect = m.codobiect
                  where pc.codobiect = acodobiect) loop
      if v_rec.tip &lt; 3 then
        iResult := iResult + v_rec.cant * (SELECT PKG_PRODCOMP_GETMASAS.WME_RESULT FROM PKG_PRODCOMP_GETMASAS (NULL,ACODOBIECT));
      else
        iResult := iResult + v_rec.cant * v_rec.masa;
      end if;
    end loop;
  else
    select coalesce(masa,0) into iresult from nartobj where codobiect = acodobiect;
  end if;

  WME_Result :=  COALESCE(iResult, 0);
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getpretdinretete</obj_name>
  <obj_hashval>81420861b31126260434062b79b966a0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getpretdinretete(INOUT wme_result numeric, INOUT acodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCountI numeric;
  vPret   numeric;
begin
  SELECT count(codprodcomp)
  INTO aCountI
  FROM prodcomp
  WHERE codobiect = acodobiect and  generic = 1 and  COALESCE(invizibila, 0) = 0 and  COALESCE(inactiv, 0) = 0 and  COALESCE(cant, 0) &gt; 0;

  IF  aCountI &gt; 0 THEN
    SELECT sum(pret * cant) / sum(cant)
    INTO vPret
    FROM prodcomp
    WHERE codobiect = acodobiect and  generic = 1 and  COALESCE(inactiv, 0) = 0 and  COALESCE(cant, 0) &gt; 0 and  COALESCE(invizibila, 0) = 0;
  ELSE
    SELECT count(codprodcomp)
    INTO aCountI
    FROM prodcomp
    WHERE codobiect = acodobiect and  COALESCE(inactiv, 0) = 0 and  COALESCE(cant, 0) &gt; 0 and  COALESCE(invizibila, 0) = 0;

    IF  aCountI &gt; 0 THEN
      SELECT sum(pret * cant) / sum(cant)
      INTO vPret
      FROM prodcomp
      WHERE codobiect = acodobiect and  COALESCE(invizibila, 0) = 0 and  COALESCE(inactiv, 0) = 0 and  COALESCE(cant, 0) &gt; 0;
    END IF;
  END IF;

  WME_Result :=  vPret;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getpretfromcompusi</obj_name>
  <obj_hashval>105fa8e8e349178551d3db4cab6f50c1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getpretfromcompusi(INOUT wme_result numeric, INOUT acodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCount numeric;
  vPret  numeric;
begin
  vPret := 0;
  SELECT count(*) INTO aCount FROM tmp_manevra_compusi WHERE codobiect = aCodObiect;

  IF  aCount &gt; 0 THEN
    SELECT COALESCE(pret, 0) INTO vPret FROM tmp_manevra_compusi WHERE codobiect = acodobiect limit 1;
  END IF;

  WME_Result :=  vPret;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getpretfromstoc</obj_name>
  <obj_hashval>ee46bfb546a557082f92214f96be060b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getpretfromstoc(INOUT wme_result numeric, INOUT acodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCount numeric;
  vPret  numeric;
begin
  vPret := 0;
  SELECT count(*) INTO aCount FROM tmp_manevra_preturi WHERE codobiect = aCodObiect;

  IF aCount &gt; 0 THEN
    SELECT COALESCE (tmpr.pret, 0) INTO vPret FROM tmp_manevra_preturi tmpr WHERE tmpr.codobiect = acodobiect limit 1;
  END IF;

  WME_Result := vPret;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getpreturi0</obj_name>
  <obj_hashval>a92c1f835902933926f9c65f9ebafccd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getpreturi0(anlunadela numeric, anlunapanala numeric, acodprodcomp numeric, amarja numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 02.05.2022 54056 : Antecalcul - afisare Codintern/CodExtern Materiale
  PERFORM PKG_PRODCOMP_GetPreturi(AnLunaDeLa, AnLunaPanaLa, aCodProdComp, aMarja,NULL);

  UPDATE tmp_manevra_preturi SET pret = 0;

  DELETE FROM tmp_manevra_preturi_Detalii;

  INSERT INTO tmp_manevra_preturi_Detalii(codobiect, codarticol, pret, obj_codextern, obj_codintern)
                            SELECT codobiect, codarticol, pret, obj_codextern, obj_codintern FROM tmp_manevra_preturi;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getpreturioferta</obj_name>
  <obj_hashval>8d1a172037cce3c39a43ff0e448bd973</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getpreturioferta(retgenerica boolean DEFAULT false)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aPret numeric;
begin
  FOR v_rec IN (SELECT * FROM tmp_manevra_preturi WHERE COALESCE(pret, 0) = 0) LOOP
    aPret := (SELECT pkg_oferta_GetPretMediuOferte.WME_RESULT FROM pkg_oferta_GetPretMediuOferte(NULL,v_Rec.Codobiect, v_rec.codarticol, retgenerica, v_rec.codatribut, current_setting('PKG_PRODCOMP.vModGenerice', true)::numeric));
    IF  aPret &lt;&gt; 0 THEN
      UPDATE tmp_manevra_preturi
      SET
      pret  = aPret,
      Stare = 4
      WHERE codobiect = v_rec.codobiect;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getregiefromcompusi</obj_name>
  <obj_hashval>37f167cd98671f22e02e89d326d867ea</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getregiefromcompusi(INOUT wme_result numeric, INOUT acodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCount numeric;
  vRegie numeric;
begin
  vRegie := 0;
  SELECT count(*) INTO aCount FROM tmp_manevra_compusi WHERE codobiect = aCodObiect;
  IF  aCount &gt; 0 THEN
    SELECT COALESCE(regie, 0) INTO vRegie FROM tmp_manevra_compusi WHERE codobiect = acodobiect limit 1;
  END IF;

  WME_Result :=  vRegie;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getvalmanfromcompusi</obj_name>
  <obj_hashval>356548d45a2927583556d05a973f7e34</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getvalmanfromcompusi(INOUT wme_result numeric, INOUT acodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCount  numeric;
  vValman numeric;
begin
  vValman := 0;
  SELECT count(*) INTO aCount FROM tmp_manevra_compusi WHERE codobiect = aCodObiect;
  IF  aCount &gt; 0 THEN
    SELECT COALESCE(valman, 0) INTO vValman FROM tmp_manevra_compusi WHERE codobiect = acodobiect limit 1;
  END IF;

  WME_Result :=  vValman;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getvalmatfromcompusi</obj_name>
  <obj_hashval>c287be4145d8e0f6573c075a437494c5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getvalmatfromcompusi(INOUT wme_result numeric, INOUT acodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCount  numeric;
  vValmat numeric;
begin
  vValmat := 0;
  SELECT count(*) INTO aCount FROM tmp_manevra_compusi WHERE codobiect = aCodObiect;
  IF  aCount &gt; 0 THEN
    SELECT COALESCE(valmat, 0) INTO vValmat FROM tmp_manevra_compusi WHERE codobiect = acodobiect limit 1;
  END IF;

  WME_Result :=  vValmat;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getvaloareman</obj_name>
  <obj_hashval>c3077e295e29a0b010ad5af40f49bfce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getvaloareman(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT tippret numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC1  RECORD;
  V_REC   RECORD;
  V_TMP   RECORD;
  aCount  numeric;
  aCount1 numeric;
  aCount2 numeric;
  man     numeric;
  vValman numeric;
  ManMax  numeric;
  ManMin  numeric;
begin
  --Laura 26.01.2022 - sinc. Oracle (28.12.2021)
  --Bogdan 08.12.2020
  SELECT count (pc.codprodcomp) INTO aCount
  FROM prodcomp_clona pcc INNER JOIN prodcomp pc ON pc.codprodcomp = pcc.codprodcomp
  WHERE pc.codobiect = aCodObiect;

  IF aCount = 0 THEN
    WME_Result := (SELECT ProcInner.WME_RESULT FROM pkg_prodcomp_GetValoareManDinDerivate (NULL,aCodObiect, TipPret) as ProcInner);
    RETURN;
  END IF;

  SELECT count (valoare) INTO aCount1 FROM tmp_manevra_liste WHERE valoare::numeric = aCodObiect;

  IF aCount1 = 0 THEN
    INSERT INTO tmp_manevra_liste (valoare) VALUES (aCodObiect);
  ELSE
    man := (SELECT PKG_PRODCOMP_GetValManFromCompusi.WME_RESULT FROM PKG_PRODCOMP_GetValManFromCompusi (NULL,aCodObiect));
    IF Man &gt; 0 THEN
      WME_Result := man;
      RETURN;
    END IF;
  END IF;

  SELECT count (pc.codprodcomp) INTO aCount2
  FROM prodcomp_clona pcc INNER JOIN prodcomp pc ON pcc.codprodcomp = pc.codprodcomp
  WHERE pc.codobiect = aCodObiect and pc.generic = 1;

  IF aCount2 &gt; 0 THEN
    man := 0;
    FOR v_rec1 IN (SELECT pc.codprodcomp, pc.cant
                   FROM prodcomp_clona pcc INNER JOIN prodcomp pc ON pcc.codprodcomp = pc.codprodcomp
                   WHERE pc.codobiect = aCodObiect and pc.generic = 1)
    LOOP
      FOR v_rec IN (SELECT codprodgest FROM prodgest WHERE codprodcomp = v_Rec1.codprodcomp) LOOP
        vValman := 0;
        FOR v_tmp IN (SELECT round ( ( (t1.tarif * man.tu) / 60 / CASE WHEN COALESCE (man.bps, 1) = 0 THEN 1 ELSE COALESCE (man.bps, 1) END) ::numeric, 7) VALOARE
                      FROM prodman  man
                        LEFT JOIN TARIFEMAN1 T1 ON t1.codtarif = man.codtarif AND getANLUNALUCRU() BETWEEN T1.ALStart AND T1.ALStop
                          where man.codprodcomp = v_rec1.codprodcomp and man.codprodgest = v_Rec.Codprodgest) loop
          vValman := vValman + v_tmp.valoare;
        END LOOP;

        FOR v_tmp IN (SELECT mat.codobiect, mat.cant, COALESCE (mat.tip, 3) TIP
                      FROM prodmat          mat
                        INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                        LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                      WHERE
                        mat.codprodcomp = v_rec1.codprodcomp
                        and pg.codprodgest = v_rec.codprodgest
                        and COALESCE (mat.tip, 3) &lt; 3)
        LOOP
          vValman := vValman + v_tmp.cant / v_Rec1.Cant * (SELECT ProcInner.WME_RESULT FROM PKG_PRODCOMP_GetValoareMan (NULL,v_tmp.codobiect, TipPret) as ProcInner);
        END LOOP;
        man := man + vValman;
      END LOOP;
    END LOOP;

    UPDATE tmp_manevra_compusi SET valman = man / aCount2 WHERE codobiect = aCodObiect;

    WME_Result := man / aCount2;
    RETURN;
  ELSE
    man := 0;
    IF TipPret = 1 THEN
      ManMax := 0;
      FOR v_rec1 IN (SELECT pc.codprodcomp, pc.cant
                     FROM prodcomp pc INNER JOIN prodcomp pcc ON pc.codprodcomp = pcc.codprodcomp
                     WHERE pc.codobiect = aCodObiect)
      LOOP
        FOR v_rec IN (SELECT codprodgest FROM prodgest WHERE codprodcomp = v_Rec1.codprodcomp) LOOP
          vValman := 0;
          FOR v_tmp IN (SELECT round ( ( (t1.tarif * man.tu) / 60 / CASE WHEN COALESCE (man.bps, 1) = 0 THEN 1 ELSE COALESCE (man.bps, 1) END) ::numeric, 7) VALOARE
                        FROM prodman man
                          LEFT JOIN TARIFEMAN1 T1 ON t1.codtarif = man.codtarif AND getANLUNALUCRU() BETWEEN T1.ALStart AND T1.ALStop
                            where man.codprodcomp = v_rec1.codprodcomp and man.codprodgest = v_Rec.Codprodgest) loop
            vValman := vValman + v_tmp.valoare;
          END LOOP;

          FOR v_tmp IN (SELECT mat.codobiect, mat.cant, COALESCE (mat.tip, 3) TIP
                        FROM prodmat          mat
                          INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                          LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                        WHERE
                          mat.codprodcomp = v_rec1.codprodcomp
                          and pg.codprodgest = v_rec.codprodgest
                          and COALESCE (mat.tip, 3) &lt; 3)
          LOOP
            vValman := vValman + v_tmp.cant / v_Rec1.cant * (SELECT ProcInn.WME_RESULT FROM PKG_PRODCOMP_GetValoareMan (NULL,v_tmp.codobiect, TipPret) as ProcInn);
          END LOOP;

          man := man + vValman;
          IF man &gt; ManMax THEN
            ManMax := man;
          END IF;
        END LOOP;
      END LOOP;

      UPDATE tmp_manevra_compusi SET ValMan = ManMax WHERE codobiect = aCodObiect;

      WME_Result := ManMax;
      RETURN;
    ELSE
      IF TipPret = 3 THEN
        FOR v_rec1 IN (SELECT pc.codprodcomp, pc.cant
                       FROM prodcomp pc INNER JOIN prodcomp pcc ON pc.codprodcomp = pcc.codprodcomp
                       WHERE pc.codobiect = aCodObiect)
        LOOP
          ManMin := 0;
          FOR v_rec IN (SELECT codprodgest FROM prodgest WHERE codprodcomp = v_Rec1.codprodcomp) LOOP
            VValman := 0;
            FOR v_tmp IN (SELECT round ( ( (t1.tarif * man.tu) / 60 / CASE WHEN COALESCE (man.bps, 1) = 0 THEN 1 ELSE COALESCE (man.bps, 1) END) ::numeric, 7) VALOARE
                          FROM prodman man
                            LEFT JOIN TARIFEMAN1 T1 ON t1.codtarif = man.codtarif AND getANLUNALUCRU() BETWEEN T1.ALStart AND T1.ALStop
                            where man.codprodcomp = v_rec1.codprodcomp and man.codprodgest = v_Rec.Codprodgest) loop
              vValman := vValman + v_tmp.valoare;
            END LOOP;

            FOR v_tmp IN (SELECT mat.codobiect, mat.cant, COALESCE (mat.tip, 3) TIP
                          FROM prodmat          mat
                            INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                            LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                          WHERE
                            mat.codprodcomp = v_rec1.codprodcomp
                            and pg.codprodgest = v_rec.codprodgest
                            and COALESCE (mat.tip, 3) &lt; 3)
            LOOP
              vValman := vValman + v_tmp.cant / v_rec1.cant * (SELECT ProcInner.WME_RESULT FROM PKG_PRODCOMP_GetValoareMan (NULL,v_tmp.codobiect, TipPret) as ProcInner);
            END LOOP;

            man := man + vValman;
            IF man &lt; ManMin THEN
              ManMin := man;
            END IF;
          END LOOP;
        END LOOP;

        UPDATE tmp_manevra_compusi SET ValMan = ManMin WHERE codobiect = aCodObiect;

        WME_Result := ManMin;
        RETURN;
      ELSE
        FOR v_rec1 IN (SELECT pc.codprodcomp, pc.cant
                       FROM prodcomp pc INNER JOIN prodcomp pcc ON pc.codprodcomp = pcc.codprodcomp
                       WHERE pc.codobiect = aCodObiect)
        LOOP
          FOR v_rec IN (SELECT codprodgest FROM prodgest WHERE codprodcomp = v_Rec1.codprodcomp) LOOP
            vValman := 0;
            FOR v_tmp IN (SELECT round ( ( (t1.tarif * man.tu) / 60 / CASE WHEN COALESCE (man.bps, 1) = 0 THEN 1 ELSE COALESCE (man.bps, 1) END) ::numeric, 7) VALOARE
                          FROM prodman man
                            LEFT JOIN TARIFEMAN1 T1 ON t1.codtarif = man.codtarif AND getANLUNALUCRU() BETWEEN T1.ALStart AND T1.ALStop
                            where man.codprodcomp = v_rec1.codprodcomp and man.codprodgest = v_Rec.Codprodgest) loop
              vValman := vValman + v_tmp.valoare;
            END LOOP;

            FOR v_tmp IN (SELECT mat.codobiect, mat.cant, COALESCE (mat.tip, 3) TIP
                          FROM prodmat          mat
                            INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                            LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                          WHERE
                            mat.codprodcomp = v_rec1.codprodcomp
                            and pg.codprodgest = v_rec.codprodgest
                            and COALESCE (mat.tip, 3) &lt; 3)
            LOOP
              vValman := vValman + v_tmp.cant / v_rec1.cant * (SELECT ProcInner.WME_RESULT FROM PKG_PRODCOMP_GetValoareMan (NULL,v_tmp.codobiect, TipPret) as ProcInner);
            END LOOP;
            man := man + vValman;
          END LOOP;
        END LOOP;

        UPDATE tmp_manevra_compusi SET ValMan = man / aCount WHERE codobiect = aCodObiect;

        WME_Result := man / aCount;
        RETURN;
      END IF;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getvaloaremandinderivate</obj_name>
  <obj_hashval>c2ed2be46c3ac798d9cd9c09fec40677</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getvaloaremandinderivate(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT tippret numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC1      RECORD;
  V_REC       RECORD;
  V_TMP       RECORD;
  aCount      numeric;
  aCount1     numeric;
  aCount2     numeric;
  man         numeric;
  vValman     numeric;
  ManMax      numeric;
  ManMin      numeric;
  aCodArticol numeric;
BEGIN
  --Florin 18.12.2024 - sinc. Oracle
  --Florin 05.11.2024 - fixat 63861
  --Laura 26.01.2022 - sinc. Oracle (28.12.2021)
  SELECT codarticol INTO aCodArticol FROM nartobj WHERE codobiect = aCodObiect;

  IF  (SELECT pkg_nom_articol_getcodobiectgeneric.WME_RESULT FROM pkg_nom_articol_getcodobiectgeneric(NULL,aCodArticol)) &lt;&gt; aCodObiect
  THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  SELECT count(pc.codprodcomp) INTO aCount
  FROM prodcomp_clona pcc
      INNER JOIN prodcomp pc ON  pc.codprodcomp = pcc.codprodcomp
      INNER JOIN nartobj obj ON  obj.codobiect = pc.codobiect
  WHERE obj.codarticol = aCodArticol and  obj.codobiect &lt;&gt; aCodObiect;

  IF  aCount = 0 THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  SELECT count(valoare) INTO aCount1 FROM tmp_manevra_liste WHERE valoare::NUMERIC = aCodObiect;
  IF  aCount1 = 0 THEN
    INSERT INTO tmp_manevra_liste(valoare) VALUES(aCodObiect);
  ELSE
    man := (SELECT PKG_PRODCOMP_GetValManFromCompusi.WME_RESULT FROM PKG_PRODCOMP_GetValManFromCompusi(NULL,aCodObiect));
    IF  Man &gt; 0 THEN
      WME_Result :=  man;
      RETURN;
    END IF;
  END IF;

  SELECT count(pc.codprodcomp)
  INTO aCount2
  FROM prodcomp_clona pcc
      INNER JOIN prodcomp pc ON  pcc.codprodcomp = pc.codprodcomp
      INNER JOIN nartobj obj ON  obj.codobiect = pc.codobiect
  WHERE obj.codarticol = aCodArticol and  obj.codobiect &lt;&gt; aCodObiect and  pc.generic = 1;

  IF  aCount2 &gt; 0 THEN
    man := 0;
    FOR v_rec1 IN
    (
    SELECT pc.codprodcomp, pc.cant
    FROM prodcomp_clona pcc
        INNER JOIN prodcomp pc ON  pcc.codprodcomp = pc.codprodcomp
        INNER JOIN nartobj obj ON  obj.codobiect = pc.codobiect
    WHERE obj.codarticol = aCodArticol and  obj.codobiect &lt;&gt; aCodObiect and  pc.generic = 1
    )
    LOOP
      FOR v_rec IN (SELECT codprodgest FROM prodgest WHERE codprodcomp = v_Rec1.codprodcomp) LOOP
        vValman := 0;
        FOR v_tmp IN (SELECT round(((  t1.tarif * man.tu)  / 60 / CASE WHEN  COALESCE(man.bps, 1)=0 THEN 1 ELSE  COALESCE(man.bps, 1) END )::numeric, 7) VALOARE
                      FROM prodman man
                        LEFT JOIN TARIFEMAN1 T1 ON t1.codtarif = man.codtarif AND getANLUNALUCRU() BETWEEN T1.ALStart AND T1.ALStop
                        where man.codprodcomp = v_rec1.codprodcomp and man.codprodgest = v_Rec.Codprodgest) loop
          vValman := vValman + v_tmp.valoare;
        END LOOP;

        FOR v_tmp IN
        (
        SELECT mat.codobiect, mat.cant, COALESCE(mat.tip, 3) TIP
        FROM prodmat mat
            INNER JOIN prodgest pg ON  mat.codprodgest = pg.codprodgest
            LEFT  JOIN ngest ng ON  ng.codgest = pg.codgest
        WHERE  mat.codprodcomp = v_rec1.codprodcomp and  pg.codprodgest = v_rec.codprodgest and  COALESCE(mat.tip, 3) &lt; 3
        )
        LOOP
          vValman := vValman + v_tmp.cant / v_Rec1.Cant * (SELECT PKG_PRODCOMP_GetValoareMan.WME_RESULT FROM PKG_PRODCOMP_GetValoareMan(NULL,v_tmp.codobiect, TipPret));
        END LOOP;

        man := man + vValman;
      END LOOP;
    END LOOP;

    UPDATE tmp_manevra_compusi SET valman = man / aCount2 WHERE codobiect = aCodObiect;

    WME_Result :=  man / aCount2;
    RETURN;
  ELSE
    man := 0;
    IF  TipPret = 1 THEN
      ManMax := 0;
      FOR v_rec1 IN
      (
      SELECT pc.codprodcomp, pc.cant
      FROM prodcomp pc
          INNER JOIN prodcomp pcc ON  pc.codprodcomp = pcc.codprodcomp
          INNER JOIN nartobj obj ON  obj.codobiect = pc.codobiect
      WHERE obj.codarticol = aCodArticol and  obj.codobiect &lt;&gt; aCodObiect
      )
      LOOP
        FOR v_rec IN (SELECT codprodgest FROM prodgest WHERE codprodcomp = v_Rec1.codprodcomp) LOOP
          vValman := 0;
          FOR v_tmp IN (SELECT round(((  t1.tarif * man.tu)  / 60 / CASE WHEN  COALESCE(man.bps, 1)=0 THEN 1 ELSE  COALESCE(man.bps, 1) END )::numeric, 7) VALOARE
                        FROM prodman man
                          LEFT JOIN TARIFEMAN1 T1 ON t1.codtarif = man.codtarif AND getANLUNALUCRU() BETWEEN T1.ALStart AND T1.ALStop
                          where man.codprodcomp = v_rec1.codprodcomp and man.codprodgest = v_Rec.Codprodgest) loop
            vValman := vValman + v_tmp.valoare;
          END LOOP;

          FOR v_tmp IN
          (
          SELECT mat.codobiect, mat.cant, COALESCE(mat.tip, 3) TIP
          FROM prodmat mat
          INNER JOIN prodgest pg ON  mat.codprodgest = pg.codprodgest
          LEFT  JOIN ngest ng ON  ng.codgest = pg.codgest
          WHERE mat.codprodcomp = v_rec1.codprodcomp and  pg.codprodgest = v_rec.codprodgest and  COALESCE(mat.tip, 3) &lt; 3
          )
          LOOP
            vValman := vValman + v_tmp.cant / v_Rec1.cant * (SELECT PKG_PRODCOMP_GetValoareMan.WME_RESULT FROM PKG_PRODCOMP_GetValoareMan(NULL,v_tmp.codobiect, TipPret));
          END LOOP;

          man := man + vValman;
          IF  man &gt; ManMax THEN
            ManMax := man;
          END IF;
        END LOOP;
      END LOOP;

      UPDATE tmp_manevra_compusi SET ValMan = ManMax WHERE codobiect = aCodObiect;

      WME_Result :=  ManMax;
      RETURN;
    ELSE
      IF  TipPret = 3 THEN
        FOR v_rec1 IN
        (
        SELECT pc.codprodcomp, pc.cant
        FROM prodcomp pc
        INNER JOIN prodcomp pcc ON  pc.codprodcomp = pcc.codprodcomp
        INNER JOIN nartobj obj ON  obj.codobiect = pc.codobiect
        WHERE obj.codarticol = aCodArticol and  obj.codobiect &lt;&gt; aCodObiect
        )
        LOOP
          ManMin := 0;
          FOR v_rec IN (SELECT codprodgest FROM prodgest WHERE codprodcomp = v_Rec1.codprodcomp) LOOP
            vValman := 0;
            FOR v_tmp IN (SELECT round(((  t1.tarif * man.tu)  / 60 / CASE WHEN  COALESCE(man.bps, 1)=0 THEN 1 ELSE  COALESCE(man.bps, 1) END )::numeric, 7) VALOARE
                          FROM prodman man
                          LEFT JOIN TARIFEMAN1 T1 ON t1.codtarif = man.codtarif AND getANLUNALUCRU() BETWEEN T1.ALStart AND T1.ALStop
                          where man.codprodcomp = v_rec1.codprodcomp and man.codprodgest = v_Rec.Codprodgest) loop
              vValman := vValman + v_tmp.valoare;
            END LOOP;

            FOR v_tmp IN
            (
            SELECT mat.codobiect, mat.cant, COALESCE(mat.tip, 3) TIP
            FROM prodmat mat
            INNER JOIN prodgest pg ON  mat.codprodgest = pg.codprodgest
            LEFT JOIN ngest ng ON  ng.codgest = pg.codgest
            WHERE mat.codprodcomp = v_rec1.codprodcomp and  pg.codprodgest = v_rec.codprodgest and  COALESCE(mat.tip, 3) &lt; 3
            )
            LOOP
              vValman := vValman + v_tmp.cant / v_rec1.cant * (SELECT PKG_PRODCOMP_GetValoareMan.WME_RESULT FROM PKG_PRODCOMP_GetValoareMan(NULL,v_tmp.codobiect, TipPret));
            END LOOP;

            man := man + vValman;
            IF  man &lt; ManMin THEN
              ManMin := man;
            END IF;
          END LOOP;
        END LOOP;

        UPDATE tmp_manevra_compusi SET ValMan = ManMin WHERE codobiect = aCodObiect;

        WME_Result :=  ManMin;
        RETURN;
      ELSE
        FOR v_rec1 IN
        (
        SELECT pc.codprodcomp, pc.cant
        FROM prodcomp pc
        INNER JOIN prodcomp pcc ON  pc.codprodcomp = pcc.codprodcomp
        INNER JOIN nartobj obj ON  obj.codobiect = pc.codobiect
        WHERE obj.codarticol = aCodArticol and  obj.codobiect &lt;&gt; aCodObiect
        )
        LOOP
          vValman := 0;
          FOR v_rec IN (SELECT codprodgest FROM prodgest WHERE codprodcomp = v_Rec1.codprodcomp) LOOP
            FOR v_tmp IN (SELECT round(((  t1.tarif * man.tu)  / 60 / CASE WHEN  COALESCE(man.bps, 1)=0 THEN 1 ELSE  COALESCE(man.bps, 1) END )::numeric, 7) VALOARE
                          FROM prodman man
                          LEFT JOIN TARIFEMAN1 T1 ON t1.codtarif = man.codtarif AND getANLUNALUCRU() BETWEEN T1.ALStart AND T1.ALStop
                          WHERE man.codprodcomp = v_rec1.codprodcomp
                         )
            LOOP
              vValman := vValman + v_tmp.valoare;
            END LOOP;

            FOR v_tmp IN
            (
            SELECT mat.codobiect, mat.cant, COALESCE(mat.tip, 3) TIP
            FROM prodmat mat
            INNER JOIN prodgest pg ON  mat.codprodgest = pg.codprodgest
            LEFT JOIN ngest ng ON  ng.codgest = pg.codgest
            WHERE
               mat.codprodcomp = v_rec1.codprodcomp and  pg.codprodgest = v_rec.codprodgest and  COALESCE(mat.tip, 3) &lt; 3
            )
            LOOP
              vValman := vValman + v_tmp.cant / v_rec1.cant * (SELECT PKG_PRODCOMP_GetValoareMan.WME_RESULT FROM PKG_PRODCOMP_GetValoareMan(NULL,v_tmp.codobiect, TipPret));
            END LOOP;
            man := man + vValman;
          END LOOP;
        END LOOP;

        UPDATE tmp_manevra_compusi SET ValMan = man / aCount WHERE codobiect = aCodObiect;

        WME_Result :=  man / aCount;
        RETURN;
      END IF;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getvaloaremat</obj_name>
  <obj_hashval>6364cdbb32608940ce9a15cc99837592</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getvaloaremat(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT tippret numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC1  RECORD;
  V_REC   RECORD;
  V_TMP   RECORD;
  aCount  numeric;
  aCount1 numeric;
  aCount2 numeric;
  vValmat numeric;
  mat     numeric;
  MatMax  numeric;
  MatMin  numeric;
BEGIN
  --Florin 18.12.2024 - sinc. Oracle
  SELECT count (pc.codprodcomp)
  INTO aCount
  FROM prodcomp_clona pcc INNER JOIN prodcomp pc ON pc.codprodcomp = pcc.codprodcomp
  WHERE pc.codobiect = aCodObiect;

  IF aCount = 0 THEN
    WME_Result := (SELECT pkg_prodcomp_GetValoareMatDinDerivate.WME_RESULT FROM pkg_prodcomp_GetValoareMatDinDerivate (NULL,aCodObiect, TipPret));
    RETURN;
  END IF;

  SELECT count (valoare) INTO aCount1 FROM tmp_manevra_liste WHERE valoare::numeric = aCodObiect;

  IF aCount1 = 0 THEN
    INSERT INTO tmp_manevra_liste (valoare) VALUES (aCodObiect);
  ELSE
    mat := (SELECT PKG_PRODCOMP_GetValMatFromCompusi.WME_RESULT FROM PKG_PRODCOMP_GetValMatFromCompusi (NULL,aCodObiect));
    IF mat &gt; 0 THEN
      WME_Result := mat;
      RETURN;
    END IF;
  END IF;

  SELECT count (pc.codprodcomp)
  INTO aCount2
  FROM prodcomp_clona pcc INNER JOIN prodcomp pc ON pcc.codprodcomp = pc.codprodcomp
  WHERE pc.codobiect = aCodObiect and pc.generic = 1;

  IF aCount2 &gt; 0 THEN
    mat := 0;
    FOR v_rec1 IN (SELECT pc.codprodcomp, pc.cant
                   FROM prodcomp_clona pcc INNER JOIN prodcomp pc ON pcc.codprodcomp = pc.codprodcomp
                   WHERE pc.codobiect = aCodObiect and pc.generic = 1)
    LOOP
      FOR v_rec IN (SELECT codprodgest FROM prodgest WHERE codprodcomp = v_Rec1.codprodcomp) LOOP
        vValmat := 0;
        FOR v_tmp IN (SELECT mat.codobiect, mat.cant, mat.pret, COALESCE (pg.coefmat, ng.coefcheltmat) COEFCHELTMAT,
                             CASE WHEN COALESCE (mat.tip, 3) IN (3, 5) THEN 0 ELSE 1 END SEMIFABRICAT
                      FROM prodmat          mat
                        INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                        LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                      WHERE
                        mat.codprodcomp = v_rec1.codprodcomp
                        and pg.codprodgest = v_rec.codprodgest
                        and (COALESCE (mat.tip, 3) &lt; 4 or mat.tip = 5))
        LOOP
          IF v_tmp.Semifabricat = 1 THEN
            vValmat := vValmat + v_tmp.cant * (SELECT ProcInner.WME_RESULT FROM PKG_PRODCOMP_GetValoareMat (NULL,v_tmp.codobiect, TipPret) as ProcInner);
          ELSE
            vValmat := vValmat + v_tmp.cant * (SELECT PKG_PRODCOMP_GetPretFromStoc.WME_RESULT FROM PKG_PRODCOMP_GetPretFromStoc (NULL,v_tmp.codobiect));
          END IF;
        END LOOP;
        vValmat := vValmat / v_Rec1.cant;
        mat    := mat    + vValmat;
      END LOOP;
    END LOOP;

    UPDATE tmp_manevra_compusi SET valmat = mat / aCount2 WHERE codobiect = aCodObiect;

    WME_Result := mat / aCount2;
    RETURN;
  ELSE
    mat := 0;
    IF TipPret = 1 THEN
      MatMax := 0;
      FOR v_rec1 IN (SELECT pc.codprodcomp, pcc.cant
                     FROM prodcomp_clona pc INNER JOIN prodcomp pcc ON pc.codprodcomp = pcc.codprodcomp
                     WHERE pc.codobiect = aCodObiect)
      LOOP
        FOR v_rec IN (SELECT codprodgest FROM prodgest WHERE codprodcomp = v_Rec1.codprodcomp) LOOP
          vValmat := 0;
          FOR v_tmp IN (SELECT mat.codobiect, COALESCE (pg.coefmat, COALESCE (ng.coefcheltmat, 0)) COEFCHELTMAT, mat.cant, mat.pret,
                               CASE WHEN COALESCE (mat.tip, 3) IN (3, 5) THEN 0 ELSE 1 END SEMIFABRICAT
                        FROM prodmat          mat
                          INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                          LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                        WHERE
                          mat.codprodcomp = v_rec1.codprodcomp
                          and pg.codprodgest = v_rec.codprodgest
                          and (COALESCE (mat.tip, 3) &lt; 4 or mat.tip = 5))
          LOOP
            IF v_tmp.Semifabricat = 1 THEN
              vValmat := vValmat + v_tmp.cant * (SELECT ProcInner.WME_RESULT FROM PKG_PRODCOMP_GetValoareMat (NULL,v_tmp.codobiect, TipPret) as ProcInner);
            ELSE
              vValmat := vValmat + v_tmp.cant * (SELECT PKG_PRODCOMP_GetPretFromStoc.WME_RESULT FROM PKG_PRODCOMP_GetPretFromStoc (NULL,v_tmp.codobiect));
            END IF;
          END LOOP;
          vValmat := vValmat / v_Rec1.cant;
          mat    := mat    + vValmat;
          IF mat &gt; MatMax THEN
            MatMax := mat;
          END IF;
        END LOOP;
      END LOOP;

      UPDATE tmp_manevra_compusi SET pret = MatMax WHERE codobiect = aCodObiect;

      WME_Result := MatMax;
      RETURN;
    ELSE
      IF TipPret = 3 THEN
        MatMin := 0;
        mat    := 0;
        FOR v_rec1 IN (SELECT pc.codprodcomp, pcc.cant
                       FROM prodcomp pc INNER JOIN prodcomp pcc ON pc.codprodcomp = pcc.codprodcomp
                       WHERE pc.codobiect = aCodObiect)
        LOOP
          FOR v_rec IN (SELECT codprodgest FROM prodgest WHERE codprodcomp = v_Rec1.codprodcomp) LOOP
            vValmat := 0;
            FOR v_tmp IN (SELECT mat.codobiect, COALESCE (pg.coefmat, COALESCE (ng.coefcheltmat, 0)) COEFCHELTMAT, mat.cant, mat.pret,
                                 CASE WHEN COALESCE (mat.tip, 3) IN (3, 5) THEN 0 ELSE 1 END SEMIFABRICAT
                          FROM prodmat          mat
                            INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                            LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                          WHERE
                            mat.codprodcomp = v_rec1.codprodcomp
                            and pg.codprodgest = v_rec.codprodgest
                            and (COALESCE (mat.tip, 3) &lt; 4 or mat.tip = 5))
            LOOP
              IF v_tmp.Semifabricat = 1 THEN
                vValmat := vValmat + v_tmp.cant * (SELECT ProcInner.WME_RESULT FROM PKG_PRODCOMP_GetValoareMat (NULL,v_tmp.codobiect, TipPret) as ProcInner);
              ELSE
                vValmat := vValmat + v_tmp.cant * (SELECT PKG_PRODCOMP_GetPretFromStoc.WME_RESULT FROM PKG_PRODCOMP_GetPretFromStoc (NULL,v_tmp.codobiect));
              END IF;
            END LOOP;
            vValmat := vValmat / v_Rec1.cant;
            mat    := mat    + vValmat;
            IF mat &lt; MatMin THEN
              MatMin := mat;
            END IF;
          END LOOP;
        END LOOP;

        UPDATE tmp_manevra_compusi SET pret = MatMin WHERE codobiect = aCodObiect;

        WME_Result := MatMin;
        RETURN;
      ELSE
        mat := 0;
        FOR v_rec1 IN (SELECT pc.codprodcomp, pcc.cant
                       FROM prodcomp_clona pc INNER JOIN prodcomp pcc ON pc.codprodcomp = pcc.codprodcomp
                       WHERE pc.codobiect = aCodObiect)
        LOOP
          FOR v_rec IN (SELECT codprodgest FROM prodgest WHERE codprodcomp = v_Rec1.codprodcomp) LOOP
            vValmat := 0;
            FOR v_tmp IN (SELECT mat.codobiect, COALESCE (pg.coefmat, COALESCE (ng.coefcheltmat, 0)) COEFCHELTMAT, mat.cant, mat.pret,
                                 CASE WHEN COALESCE (mat.tip, 3) IN (3, 5) THEN 0 ELSE 1 END SEMIFABRICAT
                          FROM prodmat          mat
                            INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                            LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                          WHERE
                            mat.codprodcomp = v_rec1.codprodcomp
                            and pg.codprodgest = v_rec.codprodgest
                            and (COALESCE (mat.tip, 3) &lt; 4 or mat.tip = 5))
            LOOP
              IF v_tmp.Semifabricat = 1 THEN
                vValmat := vValmat + v_tmp.cant * (SELECT ProcInner.WME_RESULT FROM PKG_PRODCOMP_GetValoareMat (NULL,v_tmp.codobiect, TipPret) as ProcInner);
              ELSE
                vValmat := vValmat + v_tmp.cant * (SELECT PKG_PRODCOMP_GetPretFromStoc.WME_RESULT FROM PKG_PRODCOMP_GetPretFromStoc (NULL,v_tmp.codobiect));
              END IF;
            END LOOP;
            vValmat := vValmat / v_Rec1.cant;
            mat    := mat    + vValmat;
          END LOOP;
        END LOOP;

        UPDATE tmp_manevra_compusi SET pret = mat / aCount WHERE codobiect = aCodObiect;

        WME_Result := mat / aCount;
        RETURN;
      END IF;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getvaloarematdinderivate</obj_name>
  <obj_hashval>180777eea28129dc01bde7ac495c7d46</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getvaloarematdinderivate(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT tippret numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC1      RECORD;
  V_REC       RECORD;
  V_TMP       RECORD;
  aCount      numeric;
  aCount1     numeric;
  aCount2     numeric;
  vValmat     numeric;
  mat         numeric;
  MatMax      numeric;
  MatMin      numeric;
  aCodArticol numeric;
BEGIN
  --Florin 18.12.2024 - sinc. Oracle
  --Florin 05.11.2024 - fixat 63861
  SELECT codarticol INTO aCodArticol FROM nartobj WHERE codobiect = aCodObiect;

  IF  (SELECT pkg_nom_articol_getcodobiectgeneric.WME_RESULT FROM pkg_nom_articol_getcodobiectgeneric(NULL,aCodArticol)) &lt;&gt; aCodObiect
  THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  SELECT count(pc.codprodcomp)
  INTO aCount
  FROM prodcomp_clona pcc
      INNER JOIN prodcomp pc ON  pc.codprodcomp = pcc.codprodcomp
      INNER JOIN nartobj obj ON  obj.codobiect  = pc.codobiect
  WHERE obj.codarticol = aCodArticol and  obj.codobiect &lt;&gt; aCodObiect;

  IF  aCount = 0 THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  SELECT count(valoare) INTO aCount1 FROM tmp_manevra_liste WHERE valoare::NUMERIC = aCodObiect;

  IF  aCount1 = 0 THEN
    INSERT INTO tmp_manevra_liste(valoare) VALUES(aCodObiect);
  ELSE
    mat := (SELECT PKG_PRODCOMP_GetValMatFromCompusi.WME_RESULT FROM PKG_PRODCOMP_GetValMatFromCompusi(NULL,aCodObiect));
    IF  mat &gt; 0 THEN
      WME_Result :=  mat;
      RETURN;
    END IF;
  END IF;

  SELECT count(pc.codprodcomp)
  INTO aCount2
  FROM prodcomp_clona pcc
      INNER JOIN prodcomp pc ON  pc.codprodcomp = pcc.codprodcomp
      INNER JOIN nartobj obj ON  obj.codobiect  = pc.codobiect
  WHERE obj.codarticol = aCodArticol and  obj.codobiect &lt;&gt; aCodObiect and  pc.generic = 1;

  IF  aCount2 &gt; 0 THEN
    mat := 0;
    FOR v_rec1 IN (SELECT pc.codprodcomp, pc.cant
                   FROM prodcomp_clona pcc
                      INNER JOIN prodcomp pc ON  pc.codprodcomp = pcc.codprodcomp
                      INNER JOIN nartobj obj ON  obj.codobiect  = pc.codobiect
                   WHERE obj.codarticol = aCodArticol and  obj.codobiect &lt;&gt; aCodObiect and  pc.generic = 1
                  )
    LOOP
      FOR v_rec IN (SELECT codprodgest FROM prodgest WHERE codprodcomp = v_Rec1.codprodcomp) LOOP
        vValmat := 0;
        FOR v_tmp IN (SELECT mat.codobiect, mat.cant, mat.pret, COALESCE(pg.coefmat, ng.coefcheltmat) COEFCHELTMAT,
                             CASE WHEN COALESCE(mat.tip, 3) IN (3, 5) THEN 0 ELSE 1 END  SEMIFABRICAT
                      FROM prodmat mat
                          INNER JOIN prodgest pg ON  mat.codprodgest = pg.codprodgest
                          LEFT  JOIN ngest    ng ON  ng.codgest = pg.codgest
                      WHERE mat.codprodcomp = v_rec1.codprodcomp and  pg.codprodgest = v_rec.codprodgest and (COALESCE(mat.tip, 3) &lt; 4 or  mat.tip = 5)
                      )
        LOOP
          IF  v_tmp.Semifabricat = 1 THEN
            vValmat := vValmat + v_tmp.cant * (SELECT PKG_PRODCOMP_GetValoareMat.WME_RESULT FROM PKG_PRODCOMP_GetValoareMat(NULL,v_tmp.codobiect, TipPret));
          ELSE
            vValmat := vValmat + v_tmp.cant * (SELECT PKG_PRODCOMP_GetPretFromStoc.WME_RESULT FROM PKG_PRODCOMP_GetPretFromStoc(NULL,v_tmp.codobiect));
          END IF;
        END LOOP;

        vValmat := vValmat / v_Rec1.cant;
        mat     := mat + vValmat;
      END LOOP;
    END LOOP;

    UPDATE tmp_manevra_compusi SET valmat = mat / aCount2 WHERE codobiect = aCodObiect;

    WME_Result :=  mat / aCount2;
    RETURN;
  ELSE
    mat := 0;
    IF  TipPret = 1 THEN
      MatMax := 0;
      FOR v_rec1 IN (SELECT pc.codprodcomp, pc.cant
                     FROM prodcomp pc INNER JOIN nartobj obj ON  obj.codobiect = pc.codobiect
                     WHERE obj.codarticol = aCodArticol and  obj.codobiect &lt;&gt; aCodObiect
                    )
      LOOP
        FOR v_rec IN (SELECT codprodgest FROM prodgest WHERE codprodcomp = v_Rec1.codprodcomp) LOOP
          vValmat := 0;
          FOR v_tmp IN (SELECT mat.codobiect, COALESCE(pg.coefmat, COALESCE(ng.coefcheltmat, 0)) COEFCHELTMAT, mat.cant, mat.pret,
                               CASE WHEN COALESCE(mat.tip, 3) IN (3, 5) THEN 0 ELSE 1 END  SEMIFABRICAT
                        FROM prodmat mat
                            INNER JOIN prodgest pg ON  mat.codprodgest = pg.codprodgest
                            LEFT  JOIN ngest    ng ON  ng.codgest = pg.codgest
                        WHERE mat.codprodcomp = v_rec1.codprodcomp and  pg.codprodgest = v_rec.codprodgest and (COALESCE(mat.tip, 3) &lt; 4 or  mat.tip = 5)
                        )
          LOOP
            IF  v_tmp.Semifabricat = 1 THEN
              vValmat := vValmat + v_tmp.cant * (SELECT PKG_PRODCOMP_GetValoareMat.WME_RESULT FROM PKG_PRODCOMP_GetValoareMat(NULL,v_tmp.codobiect, TipPret));
            ELSE
              vValmat := vValmat + v_tmp.cant * (SELECT PKG_PRODCOMP_GetPretFromStoc.WME_RESULT FROM PKG_PRODCOMP_GetPretFromStoc(NULL,v_tmp.codobiect));
            END IF;
          END LOOP;

          vValmat := vValmat / v_Rec1.cant;
          mat     := mat + vValmat;

          IF  mat &gt; MatMax THEN
            MatMax := mat;
          END IF;
        END LOOP;
      END LOOP;

      UPDATE tmp_manevra_compusi SET pret = MatMax WHERE codobiect = aCodObiect;

      WME_Result :=  MatMax;
      RETURN;
    ELSE
      IF  TipPret = 3 THEN
        MatMin := 0;
        mat    := 0;

        FOR v_rec1 IN (SELECT pc.codprodcomp, pc.cant
                       FROM prodcomp pc INNER JOIN nartobj obj ON  obj.codobiect = pc.codobiect
                       WHERE obj.codarticol = aCodArticol and  obj.codobiect &lt;&gt; aCodObiect
                      )
        LOOP
          FOR v_rec IN (SELECT codprodgest FROM prodgest WHERE codprodcomp = v_Rec1.codprodcomp) LOOP
            vValmat := 0;
            FOR v_tmp IN (SELECT mat.codobiect, COALESCE(pg.coefmat, COALESCE(ng.coefcheltmat, 0)) COEFCHELTMAT, mat.cant, mat.pret,
                                 CASE WHEN COALESCE(mat.tip, 3) IN (3, 5) THEN 0 ELSE 1 END  SEMIFABRICAT
                          FROM prodmat mat
                              INNER JOIN prodgest pg ON  mat.codprodgest = pg.codprodgest
                              LEFT  JOIN ngest    ng ON  ng.codgest = pg.codgest
                          WHERE mat.codprodcomp = v_rec1.codprodcomp and  pg.codprodgest = v_rec.codprodgest and (COALESCE(mat.tip, 3) &lt; 4 or  mat.tip = 5)
            )
            LOOP
              IF  v_tmp.Semifabricat = 1 THEN
                vValmat := vValmat + v_tmp.cant * (SELECT PKG_PRODCOMP_GetValoareMat.WME_RESULT FROM PKG_PRODCOMP_GetValoareMat(NULL,v_tmp.codobiect, TipPret));
              ELSE
                vValmat := vValmat + v_tmp.cant * (SELECT PKG_PRODCOMP_GetPretFromStoc.WME_RESULT FROM PKG_PRODCOMP_GetPretFromStoc(NULL,v_tmp.codobiect));
              END IF;
            END LOOP;

            vValmat := vValmat / v_Rec1.cant;
            mat     := mat + vValmat;

            IF  mat &lt; MatMin THEN
              MatMin := mat;
            END IF;
          END LOOP;
        END LOOP;

        UPDATE tmp_manevra_compusi SET pret = MatMin WHERE codobiect = aCodObiect;

        WME_Result :=  MatMin;
        RETURN;
      ELSE
        mat := 0;
        FOR v_rec1 IN (SELECT pc.codprodcomp, pc.cant
                       FROM prodcomp pc INNER JOIN nartobj obj ON  obj.codobiect = pc.codobiect
                       WHERE obj.codarticol = aCodArticol and  obj.codobiect &lt;&gt; aCodObiect
                      )
        LOOP
          FOR v_rec IN (SELECT codprodgest FROM prodgest WHERE codprodcomp = v_Rec1.codprodcomp) LOOP
            vValmat := 0;
            FOR v_tmp IN (SELECT mat.codobiect, COALESCE(pg.coefmat, COALESCE(ng.coefcheltmat, 0)) COEFCHELTMAT, mat.cant, mat.pret,
                                 CASE WHEN COALESCE(mat.tip, 3) IN (3, 5) THEN 0 ELSE 1 END  SEMIFABRICAT
                          FROM prodmat mat
                          INNER JOIN prodgest pg ON  mat.codprodgest = pg.codprodgest
                          LEFT  JOIN ngest    ng ON  ng.codgest = pg.codgest
                          WHERE mat.codprodcomp = v_rec1.codprodcomp and  pg.codprodgest = v_rec.codprodgest and (COALESCE(mat.tip, 3) &lt; 4 or  mat.tip = 5)
                          )
            LOOP
              IF  v_tmp.Semifabricat = 1 THEN
                vValmat := vValmat + v_tmp.cant * (SELECT PKG_PRODCOMP_GetValoareMat.WME_RESULT FROM PKG_PRODCOMP_GetValoareMat(NULL,v_tmp.codobiect, TipPret));
              ELSE
                vValmat := vValmat + v_tmp.cant * (SELECT PKG_PRODCOMP_GetPretFromStoc.WME_RESULT FROM PKG_PRODCOMP_GetPretFromStoc(NULL,v_tmp.codobiect));
              END IF;
            END LOOP;

            vValmat := vValmat / v_Rec1.cant;
            mat     := mat + vValmat;
          END LOOP;
        END LOOP;

        UPDATE tmp_manevra_compusi SET pret = mat / aCount WHERE codobiect = aCodObiect;

        WME_Result :=  mat / aCount;
        RETURN;
      END IF;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getvdatastart</obj_name>
  <obj_hashval>5a4266c2d8f642663845f054e8100d7b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getvdatastart(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PRODCOMP.vDataStart', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getvdatastop</obj_name>
  <obj_hashval>681f9b145037d2fea96b80f33d4271fc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getvdatastop(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PRODCOMP.vDataStop', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getvmodgenerice</obj_name>
  <obj_hashval>ec686a5ee197df300227f4c113db1ea5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getvmodgenerice(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PRODCOMP.vModGenerice', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getvtipfiltru</obj_name>
  <obj_hashval>2dfaac67bc328a612e3cb6fd8f9e71c1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getvtipfiltru(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PRODCOMP.vTipFiltru', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getvtippretdin</obj_name>
  <obj_hashval>e055c928527ce05af478aae1631b688e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getvtippretdin(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PRODCOMP.vTipPretDin', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_inlocmat</obj_name>
  <obj_hashval>a483abee412e76bd466a57109c0cd73c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_inlocmat(artnou numeric, artvechi numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Florin 23.03.2021 - pkg_userfirme_postlogcucommit
  DELETE FROM tmp_manevra_liste WHERE filtru = 'CODPRODCOMP' or  filtru = 'CODPROIECT';

  FOR v_rec IN
  (
    WITH
    nu AS
    (
      SELECT pn.codproiectnod
      FROM prodmat mat
          INNER JOIN proiectnod pn ON  pn.codprodmat  = mat.codmat
          INNER JOIN proiect    p  ON  p.codproiect   = pn.codproiect
          INNER JOIN comanda1   c1 ON  c1.codproiect  = p.codproiect
          INNER JOIN cmdlink    l  ON  c1.codcomanda1 = l.codliniecomanda
      WHERE mat.codobiect = artvechi
      union ALL
      SELECT pn.codproiectnod
      FROM livr1 l1
        INNER JOIN livr       l   ON  l1.codlivr    = l.codlivr
        INNER JOIN proiectnod pn  ON  l1.codproiect = pn.codproiect
        INNER JOIN prodmat    mat ON  mat.codmat    = pn.codprodmat
      WHERE COALESCE(l.anulat, 0) = 0 and  l.operat = 1 and  mat.codobiect = artvechi
    )
    SELECT pn.codproiectnod, pn.codproiect, 'Inloc.mat. (' || coalesce(pn.codproiectnod::varchar ,'') || ')' DOC, p.dataproiect
    FROM proiectnod pn
        INNER JOIN proiect p   ON  p.codproiect = pn.codproiect
        INNER JOIN prodmat mat ON  mat.codmat   = pn.codprodmat
    WHERE mat.codobiect = artvechi and  NOT pn.codproiectnod IN (SELECT codproiectnod FROM nu)
  )
  LOOP
    INSERT INTO tmp_manevra_liste(filtru, valoare) VALUES('CODPROIECT', v_rec.codproiect);

    UPDATE proiectnod SET codobiect = artnou WHERE codobiect = artvechi and  codproiectnod = v_rec.codproiectnod;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, 'MON_42'))
    THEN
      PERFORM pkg_userfirme_postlogcucommit('PROIECT', current_setting('PKG_GLOBALS.USERNAME', true), 'M', v_rec.codproiect, current_setting('PKG_GLOBALS.FIRMANAME', true), current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, v_rec.DataProiect, v_rec.Doc, null, current_setting('PKG_GLOBALS.EXE_VERSION', true));
    END IF;
  END LOOP;

  UPDATE normemat SET codobiect = artnou WHERE codobiect = artvechi and  COALESCE(codmat, 0) = 0;

  FOR v_rec IN
  (
    WITH
    nu AS
    (
      SELECT mat.codmat
      FROM prodmat mat
          INNER JOIN proiectnod pn ON  pn.codprodmat  = mat.codmat
          INNER JOIN proiect    p  ON  p.codproiect   = pn.codproiect
          INNER JOIN comanda1   c1 ON  c1.codproiect  = p.codproiect
          INNER JOIN cmdlink    l  ON  c1.codcomanda1 = l.codliniecomanda
      WHERE mat.codobiect = artvechi
      union ALL
      SELECT mat.codmat
      FROM livr1 l1
          INNER JOIN livr       l   ON  l1.codlivr    = l.codlivr
          INNER JOIN proiectnod pn  ON  l1.codproiect = pn.codproiect
          INNER JOIN prodmat    mat ON  mat.codmat    = pn.codprodmat
      WHERE COALESCE(l.anulat, 0) = 0 and  l.operat = 1 and  mat.codobiect = artvechi
    )
    SELECT mat.codmat, mat.codprodcomp, pc.data, 'OBJ:' || coalesce(obj.denumire,'') || ' (' || coalesce(mat.CODPRODCOMP::varchar ,'') || ') - inloc.mat.(' || coalesce(mat.codmat::varchar ,'') || ')' DOC
    FROM prodmat mat
        INNER JOIN prodcomp pc ON  mat.codprodcomp = pc.codprodcomp
        INNER JOIN nartobj obj ON  obj.codobiect   = pc.codobiect
    WHERE mat.codobiect = artvechi and  NOT mat.codmat IN (SELECT codmat FROM nu)
  )
  LOOP
    UPDATE prodmat  SET codobiect = artnou WHERE codobiect = artvechi and  codmat = v_rec.codmat;
    UPDATE normemat SET codobiect = artnou WHERE codmat = v_rec.codmat and  codobiect = artvechi;

    INSERT INTO tmp_manevra_liste(filtru, valoare) VALUES('CODPRODCOMP', v_rec.codprodcomp);

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_PRODCOMP.CT_MONITOR', true)))
    THEN
      PERFORM pkg_userfirme_postlogcucommit('PRODCOMP', current_setting('PKG_GLOBALS.USERNAME', true), 'M', v_rec.codprodcomp, current_setting('PKG_GLOBALS.FIRMANAME', true), current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, v_rec.Data, v_rec.Doc, null, current_setting('PKG_GLOBALS.EXE_VERSION', true));
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_kregieantecalcul</obj_name>
  <obj_hashval>f1ae3e8bdd856c99d8abf9bdcd2b9668</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_kregieantecalcul(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PRODCOMP.KRegieAntecalcul', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_ktipcoefindirecte</obj_name>
  <obj_hashval>9a57926e0d389437dbb8b336d1c44234</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_ktipcoefindirecte(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PRODCOMP.KTipCoefIndirecte', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_ktippret</obj_name>
  <obj_hashval>8ee1c79baaa4a5d580bffb4d324ebe41</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_ktippret(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PRODCOMP.KTipPret', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_loadpreturi</obj_name>
  <obj_hashval>4b84ec03e377f3ff3b3bb5274fdaeb4f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_loadpreturi(modul numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 02.05.2022 54056 : Antecalcul - afisare Codintern/CodExtern Materiale
  IF  modul = 1 THEN
    DELETE FROM tmp_manevra_preturi;
    DELETE FROM tmp_manevra_preturi_Detalii;
    DELETE FROM prodcomp_clona;
    DELETE FROM prodman_clona;
    DELETE FROM prodmat_clona;

    INSERT INTO Tmp_Manevra_Preturi(CODOBIECT, PRET, STARE, DENUMIRE, Den_Claseas, CodArticol, CodAtribut, OBJ_CODEXTERN, OBJ_CODINTERN)
    (
    SELECT m.codobiect, m.PRET, m.STARE, o.DENUMIRE, nclaseas.den_claseas, m.codarticol, m.codatribut, O.CODEXTERN, O.CODINTERN
    FROM Manevra_Preturi m
        INNER JOIN NArtObj o ON  o.CodObiect       = m.CodObiect
        INNER JOIN nart      ON  o.codarticol      = nart.codarticol
        LEFT  JOIN nclaseas  ON  nart.clasastatist = nclaseas.codclaseas
    );

    INSERT INTO tmp_manevra_preturi_Detalii  (SELECT * FROM Manevra_Preturi_D);
    INSERT INTO prodcomp_clona               SELECT * FROM manevra_prodcomp_clona;
    INSERT INTO prodman_clona                SELECT * FROM manevra_prodman_clona;
    INSERT INTO prodmat_clona                SELECT * FROM manevra_prodmat_clona;
  ELSE
    DELETE FROM tmp_manevra_preturi;
    DELETE FROM tmp_manevra_preturi_Detalii;
    DELETE FROM prodcomp_clona;
    DELETE FROM prodman_clona;
    DELETE FROM prodmat_clona;

    INSERT INTO Tmp_Manevra_Preturi(CODOBIECT, PRET, STARE, DENUMIRE, Den_Claseas, Codarticol, Codatribut, OBJ_CODEXTERN, OBJ_CODINTERN)
    (
    SELECT m.codobiect, m.PRET, m.STARE, o.DENUMIRE, nclaseas.den_claseas, m.CodArticol, m.CodAtribut, O.CODEXTERN, O.CODINTERN
    FROM Manevra_Preturi_p m
    INNER JOIN NArtObj o ON  o.CodObiect       = m.CodObiect
    INNER JOIN nart      ON  o.codarticol      = nart.codarticol
    LEFT  JOIN nclaseas  ON  nart.clasastatist = nclaseas.codclaseas
    );

    INSERT INTO tmp_manevra_preturi_Detalii (SELECT * FROM Manevra_Preturi_D_P);
    INSERT INTO prodcomp_clona               SELECT * FROM manevra_prodcomp_clona_p;
    INSERT INTO prodman_clona                SELECT * FROM manevra_prodman_clona_p;
    INSERT INTO prodmat_clona                SELECT * FROM manevra_prodmat_clona_p;
  END IF;

  IF current_setting('PKG_PRODCOMP.DoCommit', true) THEN
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_makeoferta</obj_name>
  <obj_hashval>9d75737c8ef864b90fb6b69253934697</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_makeoferta()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  aCod    numeric;
  Inserez boolean;
begin
  Inserez := False;
  SELECT NEXTVAL('SEQ_OFERTA_CODOFERTA') INTO aCod;

  FOR v_rec IN
  (
    SELECT tmp.*, num1.codum1
    FROM tmp_manevra_preturi tmp
        INNER JOIN nartobj obj ON  tmp.codobiect  = obj.codobiect
        INNER JOIN nart    art ON  art.codarticol = obj.codarticol
        INNER JOIN num1        ON  num1.codum     = art.um and  COALESCE(num1.secundara, 0) = 0
    WHERE tmp.stare = 3
  )
  LOOP
    IF  (SELECT pkg_oferta_ExistaOfertaValabila.WME_RESULT FROM pkg_oferta_ExistaOfertaValabila(NULL,v_rec.codobiect)) = 0
    THEN
      IF  NOT Inserez THEN
        Inserez := True;
      END IF;

      INSERT INTO oferta1(codoferta1, codoferta, codobiect, cantmin, UMSec)
      VALUES(NEXTVAL('SEQ_OFERTA1_CODOFERTA1'), aCod, v_rec.codobiect, 1, v_rec.codum1);
    END IF;
  END LOOP;

  IF Inserez THEN
    INSERT INTO oferta(codoferta, tipdoc, operat, nrdoc, datastart, dataend, toatesubunit, anulat, blocat)
    VALUES(aCod, 51, 1, 0, to_date(to_char(CURRENT_TIMESTAMP, 'DD.MM.YYYY'), 'DD.MM.YYYY'), to_date('31.12.2050', 'DD.MM.YYYY'), 1, 0, 0);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_pregatestestructura</obj_name>
  <obj_hashval>bc459e939c2cad9b189d7714c58e17f6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_pregatestestructura()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_rec record;
  cCls numeric(10);
  cClsS numeric(10);
  cProd numeric(10);
begin
  --Florin 11.08.2025 - sinc. Oracle
  select count(*) into cCls from tmp_manevra_liste where filtru = 'CODCLASEA';
  select count(*) into cClsS from tmp_manevra_liste where filtru = 'CODCLASEAS';
  select count(*) into cProd from tmp_manevra_liste where filtru = 'CODPRODUS';
  DELETE FROM TMP_STOCREAL;
  DELETE FROM TMP_PROIECTNOD;
  INSERT INTO TMP_STOCREAL(CODOBIECT,CANT)
  SELECT NS.CODOBIECT, SUM(NS.REST)
  FROM NIRSTOC NS
       INNER JOIN NIR ON NIR.CODNIR = NS.CODNIR
       INNER JOIN NGEST G ON G.CODGEST = NIR.GEST
  WHERE NS.REST &gt; 0 AND G.TIP &lt;&gt; 4
  GROUP BY NS.CODOBIECT;
  for v_rec in (select PC.CODPRODCOMP,
                       PC.CODOBIECT,
                       PC.CANT,
                       PC.IMPLICIT,
                       PC.DESCRIERE,
                       o.denumire
                from prodcomp pc
                     inner join nartobj o on o.codobiect = pc.codobiect
                     inner join nart a on a.codarticol = o.codarticol
                where (cCls = 0 or a.clasa in (select tmp.valoare from tmp_manevra_liste tmp where filtru = 'CODCLASEA')) and
                      (cProd = 0 or o.codobiect in (select tmp.valoare from tmp_manevra_liste tmp where filtru = 'CODPRODUS')) and
                      (cClsS = 0 or a.clasastatist in (select tmp.valoare from tmp_manevra_liste tmp where filtru = 'CODCLASEAS')) and
                      pc.implicit = 1
               ) loop
    insert into tmp_proiectnod(codproiect,cant,nodoriginal,pozitie,codreteta,codobiect,indexparinte,codprodmat,nivel,denumire,necesar, proiectant)
    values (v_rec.codprodcomp, v_rec.cant, 0, 1, v_rec.codprodcomp, v_rec.codobiect, '00', 0, 0, v_rec.denumire, v_rec.cant, v_rec.codobiect);
    PERFORM pkg_prodcomp_BagaMateriale(v_rec.codprodcomp, v_rec.CodObiect, v_rec.Cant, v_Rec.CodProdComp, 0, 0, '00', v_rec.codobiect);
  end loop;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_prjfexists</obj_name>
  <obj_hashval>1217ba48f6c0a0bff37aa4a66695beb8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_prjfexists(INOUT wme_result numeric, INOUT acodprodcomp numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCount numeric;
BEGIN
  --Florin 05.12.2023 - sinc. Oracle
  SELECT count(c1.codcomanda1)
  INTO aCount
  FROM proiectnod pn INNER JOIN comanda1 c1 ON  pn.codproiect = c1.codproiect
  WHERE pn.codreteta = aCodProdComp;
  if acount = 0 THEN
    SELECT distinct count(l1.codlivr1) into aCount
    from proiectnod pn
    inner join livr1 l1 on pn.codproiect = l1.codproiect
    where pn.codreteta = aCodProdComp;
  END IF;

  WME_Result :=  aCount;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_propagafisa</obj_name>
  <obj_hashval>97cbac7e6e2aa7a8943a20ed05eba4ab</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_propagafisa(acodprodcomp numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  V_MAS RECORD;
begin
  IF  current_setting('PKG_PRODCOMP.vAllRet', true)::numeric &gt; 0 THEN
    FOR v_rec IN (SELECT codprodcomp FROM prodcomp WHERE codprodcomp &lt;&gt; aCodProdComp) LOOP
      BEGIN
        PERFORM pkg_prodcomp_SP_LOCKRECORD(v_rec.codprodcomp);
        DELETE FROM prodmas WHERE codprodcomp = v_rec.codprodcomp;

        FOR v_mas IN (SELECT * FROM prodmas WHERE codprodcomp = aCodProdComp) LOOP
          INSERT INTO prodmas(CODPRODMAS, CODPRODCOMP, DESCRIERE, FRECVENTA, METODA, CODOBIECT, INDEXLOCAL)
          VALUES(NEXTVAL('SEQ_PRODMAS_CODPRODMAS'), v_rec.codprodcomp, v_mas.descriere, v_mas.FRECVENTA, v_mas.METODA, v_mas.CODOBIECT, v_mas.INDEXLOCAL);
        END LOOP;
      EXCEPTION WHEN others THEN
        null;
      END;
    END LOOP;
  ELSE
    FOR v_rec IN (SELECT codprodcomp FROM tmp_prodcomp_man WHERE codprodcomp &lt;&gt; aCodProdComp) LOOP
      BEGIN
        PERFORM pkg_prodcomp_SP_LOCKRECORD(v_rec.codprodcomp);
        DELETE FROM prodmas WHERE codprodcomp = v_rec.codprodcomp;

        FOR v_mas IN (SELECT * FROM prodmas WHERE codprodcomp = aCodProdComp) LOOP
          INSERT INTO prodmas(CODPRODMAS, CODPRODCOMP, DESCRIERE, FRECVENTA, METODA, CODOBIECT, INDEXLOCAL)
          VALUES(NEXTVAL('SEQ_PRODMAS_CODPRODMAS'), v_rec.codprodcomp, v_mas.descriere, v_mas.FRECVENTA, v_mas.METODA, v_mas.CODOBIECT, v_mas.INDEXLOCAL);
        END LOOP;
      EXCEPTION WHEN others THEN
        null;
      END;
    END LOOP;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_propagagant</obj_name>
  <obj_hashval>17313528ef2cefb0f93b3de522655a73</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_propagagant(acodprodcomp numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Adina 07.07.2021 - sinc.Oracle
  FOR v_Rec IN (SELECT man.decalaj, man.incepere, manu.codman
                FROM prodman man
                  INNER JOIN prodcomp pc   ON  pc.codprodcomp   = man.codprodcomp
                  INNER JOIN prodman  manu ON  manu.codprodcomp = pc.codutilizare and
                                               man.nrop         = manu.nrop       and
                                               man.nrop         = manu.nrop       and
                                               man.codop        = manu.codop      and
                                               man.codloc       = manu.codloc     and
                                               man.codtarif     = manu.codtarif
                WHERE pc.codprodcomp = acodprodcomp
               )
  LOOP
    UPDATE prodman
    SET
      decalaj  = v_rec.decalaj,
      incepere = v_rec.incepere
    WHERE
     codman = v_rec.codman;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_propagaparitatecantinadancime</obj_name>
  <obj_hashval>f5893f63851edfbeecdefa99808e6ddb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_propagaparitatecantinadancime(acodmat numeric, aparitate numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR v_rec IN (SELECT codproiectnod FROM proiectnod WHERE codprodmat = aCodMat and  Tip = 1) LOOP
    PERFORM PKG_PRODCOMP_UpdateCantCuParitate(v_rec.codproiectnod, aParitate);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_savepreturi</obj_name>
  <obj_hashval>21a7571326970e60c2a8903cb665a686</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_savepreturi(modul numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  IF  modul = 1 THEN
    DELETE FROM manevra_preturi;
    DELETE FROM manevra_preturi_d;
    DELETE FROM manevra_prodcomp_clona;
    DELETE FROM manevra_prodman_clona;
    DELETE FROM manevra_prodmat_clona;

    INSERT INTO manevra_Preturi(CODOBIECT, PRET, STARE, CodArticol, CodAtribut)
    (SELECT codobiect, PRET, STARE, CodArticol, CodAtribut FROM Tmp_Manevra_Preturi);

    INSERT INTO Manevra_Preturi_D     (SELECT * FROM tmp_manevra_preturi_Detalii);
    INSERT INTO manevra_prodcomp_clona SELECT * FROM prodcomp_clona;
    INSERT INTO manevra_prodman_clona  SELECT * FROM prodman_clona;
    INSERT INTO manevra_prodmat_clona  SELECT * FROM prodmat_clona;
  ELSE
    DELETE FROM manevra_preturi_p;
    DELETE FROM manevra_preturi_d_p;
    DELETE FROM manevra_prodcomp_clona_p;
    DELETE FROM manevra_prodman_clona_p;
    DELETE FROM manevra_prodmat_clona_p;

    INSERT INTO manevra_Preturi_p(CODOBIECT, PRET, STARE, CodArticol, CodAtribut)
    (SELECT codobiect, PRET, STARE, CodArticol, CodAtribut FROM Tmp_Manevra_Preturi);

    INSERT INTO Manevra_Preturi_D_p     (SELECT * FROM tmp_manevra_preturi_Detalii);
    INSERT INTO manevra_prodcomp_clona_p SELECT * FROM prodcomp_clona;
    INSERT INTO manevra_prodman_clona_p  SELECT * FROM prodman_clona;
    INSERT INTO manevra_prodmat_clona_p  SELECT * FROM prodmat_clona;
  END IF;

  IF current_setting('PKG_PRODCOMP.DoCommit', true) THEN
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_set_do_commit</obj_name>
  <obj_hashval>e51b3a12196927769e08cfb2efb60b88</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_set_do_commit(adocommit boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PRODCOMP.DoCommit',(aDoCommit)::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_set_mat_echivalat</obj_name>
  <obj_hashval>cc5cf935a530cfb24bf06c35347a641e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_set_mat_echivalat(acodmat numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PRODCOMP.vCodMat',(aCodMat)::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_setct_monitor</obj_name>
  <obj_hashval>4f5f0b36555028dec4d18feef865d1e0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PRODCOMP.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_setdocommit</obj_name>
  <obj_hashval>d8128ddebdb49498e999c0679e2741e6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_setdocommit(adocommit boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PRODCOMP.DoCommit',aDoCommit,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_setduratainretete</obj_name>
  <obj_hashval>7708c59a3e0eb41fa5093e49d982f3ba</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_setduratainretete()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 16.05.2022 - sin. Oracle (13.05.2022)
  UPDATE prodcomp p
  SET
    durata = (select max(coalesce(p.cant,0)*coalesce(m.tu,0)+coalesce(m.incepere,0))
     from prodman m
     where m.codprodcomp = p.codprodcomp)
    where exists (select valoare from tmp_manevra_liste where valoare = p.codprodcomp and filtru = 'CODPRODCOMP');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_seteazastare</obj_name>
  <obj_hashval>5661eeb891085e50f15e2621e9c47059</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_seteazastare(amarja numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC    RECORD;
  V_REC_D  RECORD;
  ValMarja numeric;
  PretRef  numeric;
  CateRef  numeric;
  aCate    numeric;
  Marja    numeric;
begin
  Marja := aMarja / 100;
  UPDATE tmp_manevra_preturi_Detalii SET stare = 3 WHERE COALESCE(Pret, 0) = 0;
  UPDATE tmp_manevra_preturi SET stare = 3 WHERE COALESCE(Pret, 0) = 0 and  COALESCE(stare, 0) &lt;&gt; 4;
  UPDATE tmp_manevra_preturi SET stare = 1 WHERE COALESCE(Stare, 0) &lt; 3;

  FOR v_rec IN (SELECT * FROM tmp_manevra_preturi WHERE COALESCE(Stare, 0) &lt; 3) LOOP
    FOR v_rec_D IN (SELECT * FROM tmp_manevra_preturi_Detalii WHERE CodObiect = v_rec.CodObiect and  COALESCE(Stare, 0) &lt;&gt; 3)
    LOOP
      PretRef  := -1;
      CateRef  := 99999999999;
      ValMarja := v_rec_d.Pret * Marja;

      BEGIN
        SELECT Count(*)
        INTO aCate
        FROM tmp_manevra_preturi_Detalii
        WHERE CodObiect = v_rec_d.CodObiect and  Stare &lt;&gt; 3 and  Abs(v_rec_d.Pret - Pret) &gt; ValMarja;
      EXCEPTION WHEN OTHERS THEN
        aCate := -1;
      END;

      IF  aCate &lt;&gt; -1 and  aCate &lt; CateRef THEN
        CateRef := aCate;
        PretRef := v_rec_d.Pret;
      END IF;
    END LOOP;

    IF  PretRef &lt;&gt; -1 THEN
      ValMarja := PretRef * Marja;
      UPDATE tmp_manevra_preturi_Detalii
      SET Stare = CASE WHEN  PretRef - Pret = 0 THEN 4
                       WHEN  Abs(PretRef - Pret) &gt; ValMarja THEN 2
                       ELSE 1
                  END
      WHERE CodObiect = v_rec.CodObiect and  COALESCE(Stare, 0) &lt;&gt; 3;
    END IF;
  END LOOP;

  UPDATE tmp_manevra_preturi p
  SET
  Stare = 2
  WHERE
   COALESCE(p.Stare, 0) &lt;&gt; 4
   and  EXISTS (SELECT CodObiect FROM tmp_manevra_preturi_Detalii WHERE CodObiect = p.CodObiect and  Stare = 2);

  IF current_setting('PKG_PRODCOMP.DoCommit', true) THEN
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_setlucrucugenerice</obj_name>
  <obj_hashval>b9ebcb5bb95814b08a229e658f771a66</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_setlucrucugenerice(amod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PRODCOMP.vModGenerice',(aMod)::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_setparams</obj_name>
  <obj_hashval>b34b3476c452b0bbe028ad64fca76240</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_setparams(aallret numeric, afromimport numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 01.03.2022 - sinc. Oracle
  perform set_config('PKG_PRODCOMP.vAllRet'     , (aAllRet)    ::varchar,false);
  perform set_config('PKG_PRODCOMP.vFromImport', (aFromImport)::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_setparamst</obj_name>
  <obj_hashval>5ba686306d6b9d43acc38a264e020a0c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_setparamst(atipfiltru numeric, adatastart character varying, adatastop character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_PRODCOMP.vTipFiltru',(aTipFiltru)::varchar,false);
  perform set_config('PKG_PRODCOMP.vDataStart',(aDataStart)::varchar,false);
  perform set_config('PKG_PRODCOMP.vDataStop' ,(aDataStop )::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_settippretdin</obj_name>
  <obj_hashval>b8ba4d8ce3a3a2692daf2d104cba8dcf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_settippretdin(atippretdin numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PRODCOMP.vTipPretDin',(aTipPretDin)::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_setvallret</obj_name>
  <obj_hashval>bfcd143ae0cad3cc706b1cad7884c17c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_setvallret(avallret numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PRODCOMP.vAllRet',avAllRet::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_setvcodmat</obj_name>
  <obj_hashval>d39c69527507b299a98d5ae5bd290769</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_setvcodmat(avcodmat numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PRODCOMP.vCodMat',avCodMat::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_setvmodgenerice</obj_name>
  <obj_hashval>2c87070a6b3bb422802031724dee02d7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_setvmodgenerice(avmodgenerice numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PRODCOMP.vModGenerice',avModGenerice::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_setvtippretdin</obj_name>
  <obj_hashval>774f704110378f086fb52dc51c5e55f7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_setvtippretdin(avtippretdin numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PRODCOMP.vTipPretDin',avTipPretDin::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_sp_deleterecord</obj_name>
  <obj_hashval>607316de2db7c6a57df745659f656d5a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCodProiect numeric;
  vCodObiect  numeric;
  aDataDoc    date;
  aDoc        varchar;
BEGIN
  --Florin 18.08.2023 - sinc. Oracle
  --Florin 01.06.2023 - monitor
  --Adina 18.08.2021 - sinc.Oracle din 18.08.2021
  --Florin 23.01.2021 - pkg_userfirme_postlogcucommit
  perform pkg_prodcomp_setct_monitor('MON_37');
  PERFORM PKG_PRODCOMP_SP_LOCKRECORD(RecId);
  PERFORM PKG_CFGTABLES_EXT_DELETERECORD(recId, 504);

  SELECT DATA, 'OBJ:'||OBJ.DENUMIRE||' VER:'||P.OBS||' ('||RecId||')'
  INTO aDATADOC, ADOC
  FROM PRODCOMP P LEFT JOIN NARTOBJ OBJ ON P.CODOBIECT = OBJ.CODOBIECT
  WHERE P.CODPRODCOMP = RecId;

  IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_PRODCOMP.CT_MONITOR', true)))
  THEN
    PERFORM pkg_userfirme_postlogcucommit('PRODCOMP', current_setting('PKG_GLOBALS.USERNAME', true), 'S', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, aDataDoc, aDoc, null, current_setting('PKG_GLOBALS.EXE_VERSION', true));
  END IF;

  SELECT CodObiect INTO vCodObiect FROM prodcomp WHERE codprodcomp = recid;

  BEGIN
    SELECT P.CodProiect
    INTO vCodProiect
    FROM proiectnod PN INNER JOIN proiect P ON  PN.CODPROIECT = P.CODPROIECT
    WHERE PN.NODORIGINAL = 0 and  PN.CODRETETA = RecId and  PN.CODOBIECT = vCodObiect and  P.Invizibila = 1;
  EXCEPTION WHEN no_data_found THEN
    vCodProiect := 0;
  END;

  IF  vCodProiect &gt; 0 THEN
    DELETE FROM PROIECTNOD WHERE CodProiect = vCodProiect;
    DELETE FROM PROIECT    WHERE CodProiect = vCodProiect;
  END IF;

  DELETE FROM PRODMATECHIV WHERE CodProdComp = RecId;
  DELETE FROM PRODSDV      WHERE CodProdComp = RecId;
  DELETE FROM PRODMAN      WHERE CodProdComp = RecId;
  DELETE FROM PRODMAT      WHERE CodProdComp = RecId;
  DELETE FROM PRODREZ      WHERE CodProdComp = RecId;
  DELETE FROM PRODMAS      WHERE CodProdComp = RecId;
  DELETE FROM PRODGEST     WHERE CodProdComp = RecId;
  DELETE FROM NORMEMAT     WHERE CODPRODCOMP = RECID;
  DELETE FROM PRODNORME    WHERE CODPRODCOMP = RECID;
  DELETE FROM PRODCOMP     WHERE CodProdComp = RecId;

  PERFORM NotifyModif(2, RecId, 'PRODCOMP');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_sp_insertrecord</obj_name>
  <obj_hashval>c4a1a7a6e2e2d6b99e4ea37f5f0393b5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 18.08.2023 - sinc. Oracle
  INSERT INTO TMP_PRODCOMP(Codprodcomp, tipreteta) VALUES(0, 1);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(504);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_sp_lockrecord</obj_name>
  <obj_hashval>8ac809bca1ba6e47c175f24be699d63a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMP numeric := 0;
begin
  SELECT CodProdComp INTO Tmp FROM PRODCOMP WHERE CodProdComp = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_sterge_man</obj_name>
  <obj_hashval>57b0aba3d27df32dd5f94659280f1ef6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_sterge_man(acodman numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Florin 23.03.2021 - pkg_userfirme_postlogcucommit
  FOR v_rec IN
  (
  SELECT man.codman, man.codprodcomp, pc.data, 'OBJ:' || coalesce(obj.denumire,'') || ' (' || coalesce(man.CODPRODCOMP::varchar ,'') || ') - sterg.op.(' || coalesce(op.denumire,'') || ')' DOC
  FROM prodman man
      INNER JOIN prodcomp pc ON  pc.codprodcomp = man.codprodcomp
      INNER JOIN nartobj obj ON  obj.codobiect  = pc.codobiect
      INNER JOIN noper    op ON  man.codop      = op.codop
  WHERE man.codman = aCodMan
  )
  LOOP
    DELETE FROM prodman WHERE codman = v_rec.CodMan;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_PRODCOMP.CT_MONITOR', true)))
    THEN
      PERFORM pkg_userfirme_postlogcucommit('PRODCOMP', current_setting('PKG_GLOBALS.USERNAME', true), 'M', v_rec.codprodcomp, current_setting('PKG_GLOBALS.FIRMANAME', true), current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, v_rec.Data, v_rec.Doc, null, current_setting('PKG_GLOBALS.EXE_VERSION', true));
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_sterge_mat</obj_name>
  <obj_hashval>5f155117fc3b61cfd22579a71c0d9a43</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_sterge_mat(acodmat numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Florin 23.03.2021 - pkg_userfirme_postlogcucommit
  FOR v_rec IN
  (
  SELECT mat.codmat, mat.codprodcomp, pc.data, 'OBJ:' || coalesce(prod.denumire,'') || ' (' || coalesce(mat.CODPRODCOMP::varchar ,'') || ') - sterg.mat.(' || coalesce(obj.denumire,'') || ')' DOC
  FROM prodmat mat
      INNER JOIN prodcomp pc   ON  pc.codprodcomp = mat.codprodcomp
      INNER JOIN nartobj  prod ON  prod.codobiect = pc.codobiect
      INNER JOIN nartobj  obj  ON  obj.codobiect  = mat.codobiect
  WHERE mat.codmat = aCodMat
  )
  LOOP
    DELETE FROM prodmat WHERE codmat = v_rec.CodMat;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_PRODCOMP.CT_MONITOR', true)))
    THEN
      PERFORM pkg_userfirme_postlogcucommit('PRODCOMP', current_setting('PKG_GLOBALS.USERNAME', true), 'M', v_rec.codprodcomp, current_setting('PKG_GLOBALS.FIRMANAME', true), current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, v_rec.Data, v_rec.Doc, null, current_setting('PKG_GLOBALS.EXE_VERSION', true));
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_stergeretetasiproiect</obj_name>
  <obj_hashval>e72006dfa7f4ad579209c690183bf0df</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_stergeretetasiproiect(acodprodcomp numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  PERFORM pkg_prodcomp_SP_DELETERECORD(aCodProdComp);

  FOR v_rec IN (SELECT codproiect FROM proiectnod WHERE codreteta = aCodProdComp and  COALESCE(nodoriginal, 0) = 0) LOOP
    PERFORM pkg_proiect_SP_DELETERECORD(v_rec.codproiect);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_testretete</obj_name>
  <obj_hashval>106185ff5cb1843f6a1515e7beb57fb4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_testretete()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  aCount numeric;
  aPret  numeric;
begin
  FOR v_rec IN
  (
  SELECT pc.codprodcomp, mat.codmat, mat.codobiect MATERIAL, COALESCE(mat.tip, 3) TIP, pc.codobiect, COALESCE(mat.pret, 0) PRET
  FROM prodcomp_clona pcc
      INNER JOIN prodcomp pc ON  pcc.codprodcomp = pc.codprodcomp
      INNER JOIN prodmat mat ON  mat.codprodcomp = pc.codprodcomp
  WHERE pc.cant &lt;&gt; 0 and  COALESCE(pc.inactiv, 0) = 0 and  COALESCE(pc.invizibila, 0) = 0
  )
  LOOP
    IF (v_rec.tip = 1)  or (v_rec.tip = 2) THEN
      SELECT count(*)
      INTO aCount
      FROM prodcomp_clona pcc INNER JOIN prodcomp pc ON  pcc.codprodcomp = pc.codprodcomp
      WHERE pc.codobiect = v_Rec.material;

      IF  aCount = 0 THEN
        INSERT INTO tmp_atentionari(tip, camp1, camp2, camp3, camp4)
        VALUES(1, v_Rec.codprodcomp, v_rec.codobiect, v_rec.codmat, v_rec.material);
      END IF;
    ELSE
      SELECT count(*)
      INTO aCount
      FROM prodcomp_clona pcc INNER JOIN prodcomp pc ON  pcc.codprodcomp = pc.codprodcomp
      WHERE pc.codobiect = v_Rec.material;

      IF  aCount &gt; 0 THEN
        INSERT INTO tmp_atentionari(tip, camp1, camp2, camp3, camp4)
        VALUES(2, v_Rec.codprodcomp, v_rec.codobiect, v_rec.codmat, v_rec.material);
      END IF;

      aPret := (SELECT PKG_PRODCOMP_GetpretFromStoc.WME_RESULT FROM PKG_PRODCOMP_GetpretFromStoc(NULL,v_rec.material));
      IF  aPret = 0.0 THEN
        IF  v_rec.pret = 0 and  v_rec.tip &lt;&gt; 4 THEN
          INSERT INTO tmp_atentionari(tip, camp1, camp2, camp3, camp4)
          VALUES(3, v_Rec.codprodcomp, v_rec.codobiect, v_rec.codmat, v_rec.material);
        END IF;
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_updatedaterete</obj_name>
  <obj_hashval>0245f72479829ce44b9ed8eb122f6c2f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_updatedaterete()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aBanca character varying;
  aConst numeric(20);
BEGIN
  --Florin 14.03.2023 - sinc. Oracle (13.03.2023)
  --Florin current_timestamp -&gt; current_date::varchar, aBanca::numeric
  --Florin 08.01.2021 - nvl -&gt; coalesce
  aBanca := fnc_GetValConstantaLucru ('BancaProdV');
  IF fnc_GetValConstantaLucru ('BancaProdV') = '0' THEN
    aBanca := fnc_GetValConstantaLucru ('BancaSitV');
  END IF;
  aConst := fnc_GetValConstantaLucru('AntecalculCuZero')::numeric;
  FOR v_rec in (select c.*, COALESCE(pc.codmoneda,0) codmoneda, coalesce(m.adddim,0) adddim, coalesce(m.adddim_transp,0) adddim_transp
                from prodmat_clona c
                     inner join prodcomp pc on pc.codprodcomp = c.codprodcomp
                     inner join prodmat  m  on m.codmat       = c.codmat
               )
  LOOP
    update prodmat
    set
    pretorig = v_rec.pret_n,
    pret     = v_rec.pret_n,
    valmat   = v_rec.valmat,
    valman   = v_Rec.valman,
    valregie = v_Rec.valregie
    where codmat = v_rec.codmat;

    if v_rec.adddim &lt;&gt; 0 or v_rec.adddim_transp &lt;&gt; 0 then
      update prodmat set pret = PretOrig + PretOrig * v_rec.AddDim /100 + PretOrig * v_rec.AddDim_transp /100 where codmat = v_rec.codmat;
    end if;

    update prodmat set valoare = pret * cant where codmat = v_rec.codmat;

    IF v_rec.codmoneda &gt; 0 THEN
      UPDATE prodmat
      SET
      pretv = pret / (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT
                      FROM   PKG_LIST_BASE_UTILS_GETCURSREFERINTA (NULL,v_rec.codmoneda, aBanca::numeric, to_char(CURRENT_DATE,'dd.mm.yyyy')))
      WHERE
        codmat = v_rec.codmat;
    ELSE
      UPDATE prodmat SET pretv = pret WHERE codmat = v_rec.codmat;
    END IF;
  END LOOP;

  FOR v_rec IN (SELECT cl.*, pc.tipreteta, pc.cant, COALESCE (pc.coefindirecte, 0) COEFINDIRECTE,
                       COALESCE (pc.ag, 0) AG, COALESCE (pc.profit, 0) PROFIT
                FROM prodcomp_clona cl INNER JOIN prodcomp pc ON pc.codprodcomp = cl.codprodcomp
  ) LOOP
  if (v_rec.pret_n is null) THEN
    insert into x(test) values('valoare nula la pret pentru reteta:'||v_rec.codprodcomp||' - constata(AntecalculCuZero) cu valoare:'||aConst);
    ELSE
      if (v_rec.pret_n = 0) THEN
        insert into x(test) values('valoare zero la pret pentru reteta:'||v_rec.codprodcomp||' - constata(AntecalculCuZero) cu valoare:'||aConst);
      ELSE
    UPDATE prodcomp
    SET
    pret        = v_rec.pret_n, pretvaluta = v_rec.pret_n / (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA (NULL,COALESCE (codmoneda, 0) , aBanca::numeric, to_char(CURRENT_DATE,'dd.mm.yyyy'))) ,
    valmat      = v_rec.valmat,
    valman      = v_rec.valman,
    valregie    = v_Rec.valregie,
    valregieman = v_rec.valregieman
    WHERE
      codprodcomp = v_rec.codprodcomp;

    UPDATE prodcomp
    SET ValAG = v_rec.AG / 100 * (valman + valregieman)
    WHERE
      codprodcomp = v_rec.codprodcomp;

    UPDATE prodcomp
    SET TotPretFix = Pret + v_rec.CoefIndirecte + ValAG, TotPretCoef = Pret * (1.0 + v_rec.CoefIndirecte)
    WHERE
      codprodcomp = v_rec.codprodcomp;

    UPDATE prodcomp
    SET TotPretFixV  = TotPretFix  / (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA (NULL,COALESCE (codmoneda, 0) , aBanca::numeric, to_char(CURRENT_DATE,'dd.mm.yyyy'))) ,
        TotPretCoefV = TotPretCoef / (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA (NULL,COALESCE (codmoneda, 0) , aBanca::numeric, to_char(CURRENT_DATE,'dd.mm.yyyy')))
    WHERE
      codprodcomp = v_rec.codprodcomp;

    UPDATE prodcomp SET ValProfit = v_rec.profit / 100 * TotPretFix WHERE codprodcomp = v_rec.codprodcomp;

    UPDATE prodcomp
    SET
    ValProfitV = ValProfit / (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA (NULL,COALESCE (codmoneda, 0) , aBanca::numeric, to_char(CURRENT_DATE,'dd.mm.yyyy')))
    WHERE
      codprodcomp = v_rec.codprodcomp;

    UPDATE prodcomp
    SET
    PretFinal  = ValProfit + TotPretFix,
    PretFinalV = (ValProfit + TotPretFix) / (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA (NULL,COALESCE (codmoneda, 0) , aBanca::numeric, to_char(CURRENT_DATE,'dd.mm.yyyy')))
    WHERE
      codprodcomp = v_rec.codprodcomp;
    END IF;
  END IF;
  END LOOP;

  FOR v_rec IN (SELECT * FROM prodrez_clona) LOOP
    UPDATE prodrez SET pret = v_rec.pret_n WHERE codrez = v_rec.codrez;
  END LOOP;

  IF current_setting ('PKG_PRODCOMP.DoCommit', true) THEN
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_updategeneric</obj_name>
  <obj_hashval>859c127ab7fe3c4ebf1ea6ff48c72ddc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_updategeneric(INOUT wme_result boolean, INOUT acodprodcomp numeric, INOUT ageneric numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  Done BOOLEAN;
begin
  BEGIN
    UPDATE prodcomp SET generic = aGeneric WHERE codprodcomp = aCodProdComp;

    Done := True;
  EXCEPTION WHEN others THEN
    Done := False;
  END;

  WME_Result :=  Done;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_updateimplicit</obj_name>
  <obj_hashval>011cb453e5068742a27383ad4724e81d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_updateimplicit(INOUT wme_result boolean, INOUT acodprodcomp numeric, INOUT aimplicit numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  Done BOOLEAN;
begin
  BEGIN
    UPDATE prodcomp SET implicit = aImplicit WHERE codprodcomp = aCodProdComp;

    Done := True;
  EXCEPTION WHEN others THEN
    Done := False;
  END;

  WME_Result :=  Done;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_updatemanall</obj_name>
  <obj_hashval>13f30f9bab05cedd7740ebf833c4c483</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_updatemanall(acodprodcomp numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  aCount numeric;
begin
  FOR v_rec IN (SELECT pc.codprodcomp, pg.codprodgest
                FROM prodcomp pc INNER JOIN prodgest pg ON  pc.codprodcomp = pg.codprodcomp
               )
  LOOP
    SELECT count(*) INTO aCount FROM prodgest WHERE codprodcomp = v_rec.codprodcomp;
    IF  aCount = 1 THEN
      DELETE FROM prodman WHERE codprodcomp = v_rec.codprodcomp and  codprodgest = v_rec.codprodgest;

      INSERT INTO prodman(codman, codprodcomp, nrop, codop, codloc, codtarif, tu, valoare, codprodgest, indexlocal, dsv, bps, tpi, obs, Detalii, Fix, Nivel)
      SELECT NEXTVAL('SEQ_PRODMAN_CODMAN'), v_rec.codprodcomp, nrop, codop, codloc, codtarif, tu, valoare, v_rec.codprodgest, indexlocal, dsv, bps, tpi, obs, Detalii, Fix, Nivel
      FROM prodman WHERE codprodcomp = aCodProdComp;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_updatemasa</obj_name>
  <obj_hashval>95b569eae8cf1e1802d37ff19c11bdf3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_updatemasa()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  V_TMP  RECORD;
  V_OBJ  RECORD;
  aMasa  numeric;
  acount numeric;
begin
  for V_OBJ in (select distinct CODOBIECT from PRODCOMP where CODOBIECT &gt; 0) LOOP
  select count(*) into acount from prodcomp where codobiect = v_obj.codobiect;
  if acount = 1 then
    for v_rec in (
        select codprodcomp, cant, codobiect
        from prodcomp
        where codobiect = v_obj.codobiect
      ) loop
        Amasa := 0;
        for v_tmp in (
          select coalesce(o.masa,0) masa, m.tip, m.cant, m.codobiect
          from prodmat m
               inner join nartobj o on o.codobiect = m.codobiect
          where m.codprodcomp = v_rec.codprodcomp
        ) loop
          if v_tmp.tip &lt; 3 then
            amasa := amasa + v_tmp.cant * (SELECT PKG_PRODCOMP_GETMASAS.WME_RESULT FROM PKG_PRODCOMP_GETMASAS (NULL,v_tmp.CODOBIECT));
          else
            amasa := amasa + v_tmp.cant * coalesce(v_tmp.masa,0);
          end if;
        end loop;
        update nartobj set masa = coalesce(amasa,0)/v_rec.cant where codobiect = v_rec.codobiect;
    end loop;
  else
    select count(*) into acount from prodcomp where codobiect = v_obj.codobiect and implicit = 1;
    if acount = 1 then
      for v_rec in (
          select codprodcomp, cant, codobiect
          from prodcomp
          where codobiect = v_obj.codobiect and implicit = 1
        ) loop
          Amasa := 0;
          for v_tmp in (
            select coalesce(o.masa,0) masa, m.tip, m.cant, m.codobiect
            from prodmat m
                 inner join nartobj o on o.codobiect = m.codobiect
            where m.codprodcomp = v_rec.codprodcomp
          ) loop
            if v_tmp.tip &lt; 3 then
              amasa := amasa + v_tmp.cant * (SELECT PKG_PRODCOMP_GETMASAS.WME_RESULT FROM PKG_PRODCOMP_GETMASAS (NULL,v_tmp.CODOBIECT));
            else
              amasa := amasa + v_tmp.cant * coalesce(v_tmp.masa,0);
            end if;
          end loop;
          update nartobj set masa = coalesce(amasa,0)/v_rec.cant where codobiect = v_rec.codobiect;
      end loop;
    else
      select count(*) into acount from prodcomp where codobiect = v_obj.codobiect and generic = 1;
      for v_rec in (
          select codprodcomp, cant, codobiect
          from prodcomp
          where codobiect = v_obj.codobiect and generic = 1
        ) loop
          Amasa := 0;
          for v_tmp in (
            select coalesce(o.masa,0) masa, m.tip, m.cant, m.codobiect
            from prodmat m
                 inner join nartobj o on o.codobiect = m.codobiect
            where m.codprodcomp = v_rec.codprodcomp
          ) loop
            if v_tmp.tip &lt; 3 then
              amasa := amasa + v_tmp.cant * (SELECT PKG_PRODCOMP_GETMASAS.WME_RESULT FROM PKG_PRODCOMP_GETMASAS (NULL,v_tmp.CODOBIECT));
            else
              amasa := amasa + v_tmp.cant * coalesce(v_tmp.masa,0);
            end if;
          end loop;
          update nartobj set masa = coalesce(amasa,0)/v_rec.cant where codobiect = v_rec.codobiect;
      end loop;
    end if;
  end if;
end loop;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_updatenartobj1</obj_name>
  <obj_hashval>f16a4e20cee0eaf3b89ad537cfd403ff</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_updatenartobj1(atip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  vValMat   numeric;
  vValMan   numeric;
  vValRegie numeric;
BEGIN
  --Adina 12.03.2021 - prc_al_refresh
  FOR v_rec IN (SELECT obj1.*
                FROM nartobj1 obj1
                     INNER JOIN (SELECT  DISTINCT codobiect FROM TMP_PCArt_Pret) pcc ON  pcc.codobiect = obj1.codobiect
                WHERE getanlucru()*12+getlunalucru() BETWEEN obj1.alstart AND obj1.alstop
                ORDER BY obj1.codobiect
               )
  LOOP
    IF v_Rec.anstart * 12 + v_Rec.lunastart &lt;&gt; getanlucru()*12+getlunalucru() THEN
      INSERT INTO nartobj1(codobiect1, codobiect, pretmaximal, procadaosmaximal, adaosla, anstart, lunastart, tippretmax, compensat, tipcompensare, grupa, uplift, codmoneda, puncte, umiditate, corpuri_straine, incoltit, hectolitrica, gluten, fuzaritate, cadere, deformare, sticlozitate, sparturi, punctesectie, tippret)
      VALUES(NEXTVAL('SEQ_NARTOBJ1_CODOBIECT1'), v_Rec.codobiect, v_Rec.pretmaximal, v_Rec.procadaosmaximal, v_Rec.adaosla, current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric, current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric, v_Rec.tippretmax, v_Rec.compensat, v_Rec.tipcompensare, v_Rec.grupa, v_Rec.uplift, v_Rec.codmoneda, v_Rec.puncte, v_Rec.umiditate, v_Rec.corpuri_straine, v_Rec.incoltit, v_Rec.hectolitrica, v_Rec.gluten, v_Rec.fuzaritate, v_Rec.cadere, v_Rec.deformare, v_Rec.sticlozitate, v_Rec.sparturi, v_Rec.punctesectie, COALESCE(v_rec.tippret, 1));
    END IF;
    CALL prc_al_refresh('nartobj1', v_Rec.codobiect);
  END LOOP;

  FOR v_rec IN (SELECT obj1.codobiect1, obj1.codobiect, obj1.TipPret, c.valmat, c.valman, c.valregie
                FROM nartobj1 obj1
                     INNER JOIN TMP_PCArt_Pret c ON  c.codobiect = obj1.codobiect
                WHERE getanlucru()*12+getlunalucru() BETWEEN obj1.alstart AND obj1.alstop
               )
  LOOP
    vValMat   := COALESCE(v_rec.ValMat, 0);
    vValMan   := COALESCE(v_rec.ValMan, 0);
    vValRegie := COALESCE(v_rec.ValRegie, 0);

    IF  aTip = 1 THEN
      UPDATE nartobj1
      SET
      pretreferinta = vValMat + (2 - v_rec.tippret)  * vValMan + (2 - v_rec.tippret)  * vValRegie,
      valmat        = vValMat,
      valman        = vValMan,
      valregie      = vValRegie
      WHERE
       codobiect1 = v_Rec.codobiect1;

      UPDATE tmp_pcart
      SET
      PretReferinta = vValMat + (2 - v_rec.tippret)  * vValMan + (2 - v_rec.tippret)  * vValRegie
      WHERE
       codobiect = v_rec.codobiect;
    ELSE
      UPDATE nartobj1
      SET
      valmat   = vValMat,
      valman   = vValMan,
      valregie = vValRegie
      WHERE
       codobiect1 = v_Rec.codobiect1;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_updatenartobj1antec</obj_name>
  <obj_hashval>4a1cc413eb7a4905c2ac2cd62d938a46</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_updatenartobj1antec()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  TipPret character varying;
BEGIN
  --Adina 12.03.2021 - prc_al_refresh
  --Florin 08.01.2021 - tip pret numeric in if
  TipPret := fnc_GetValConstanta('TipEvaluarePret', getANLUCRU(), getLUNALUCRU());

  FOR v_rec IN (SELECT obj1.*
                FROM nartobj1 obj1
                     INNER JOIN (SELECT  DISTINCT codobiect FROM prodcomp_clona) pcc ON  pcc.codobiect = obj1.codobiect
                WHERE getanlucru()*12+getlunalucru() BETWEEN obj1.alstart AND obj1.alstop
                ORDER BY obj1.codobiect
               )
  LOOP
    IF  v_Rec.anstart * 12 + v_Rec.lunastart &lt;&gt; getANLUCRU() * 12 + getLUNALUCRU() THEN
      INSERT INTO nartobj1(codobiect1, codobiect, pretmaximal, procadaosmaximal, adaosla, anstart, lunastart, pretreferinta, tippretmax, compensat, tipcompensare, grupa, uplift, codmoneda, puncte, umiditate, corpuri_straine, incoltit, hectolitrica, gluten, fuzaritate, cadere, deformare, sticlozitate, sparturi, punctesectie, tippret, cost)
      VALUES(NEXTVAL('SEQ_NARTOBJ1_CODOBIECT1'), v_Rec.codobiect, v_Rec.pretmaximal, v_Rec.procadaosmaximal, v_Rec.adaosla, current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric, current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric, v_Rec.pretreferinta, v_Rec.tippretmax, v_Rec.compensat, v_Rec.tipcompensare, v_Rec.grupa, v_Rec.uplift, v_Rec.codmoneda, v_Rec.puncte, v_Rec.umiditate, v_Rec.corpuri_straine, v_Rec.incoltit, v_Rec.hectolitrica, v_Rec.gluten, v_Rec.fuzaritate, v_Rec.cadere, v_Rec.deformare, v_Rec.sticlozitate, v_Rec.sparturi, v_Rec.punctesectie, COALESCE(v_rec.tippret, 1), v_Rec.cost);

      CALL prc_al_refresh('nartobj1', v_Rec.codobiect);
    END IF;
  END LOOP;

  FOR v_rec IN (SELECT obj1.codobiect1, pc.valmat, pcc.valman, pcc.valregie, obj1.codobiect, obj1.tippret, pc.tippret TIPPRETRETETA, pc.totpretfix
                FROM nartobj1 obj1
                     INNER JOIN prodcomp_clona pcc ON  pcc.codobiect = obj1.codobiect
                     LEFT JOIN prodcomp pc ON  pcc.codprodcomp = pc.codprodcomp
                WHERE getanlucru()*12+getlunalucru() BETWEEN obj1.alstart AND obj1.alstop
                      and  pc.generic = 1
                ORDER BY obj1.codobiect
               )
  LOOP
    IF  current_setting('PKG_PRODCOMP.vTipPretDin', true)::numeric = 1 THEN
      IF  v_rec.tippretreteta = 1 THEN
        UPDATE nartobj1
        SET
        pretreferinta = v_Rec.valmat + v_Rec.valman + v_Rec.valregie,
        cost          = v_rec.totpretfix
        WHERE
         codobiect1 = v_Rec.codobiect1;
      ELSE
        UPDATE nartobj1
        SET
        pretreferinta = v_Rec.valmat,
        cost          = v_rec.totpretfix
        WHERE
         codobiect1 = v_Rec.codobiect1;
      END IF;
    ELSE
      IF  v_rec.tippret = 1 THEN
        UPDATE nartobj1
        SET
        pretreferinta = v_Rec.valmat + v_Rec.valman + v_Rec.valregie,
        cost          = v_rec.totpretfix
        WHERE
         codobiect1 = v_Rec.codobiect1;
      ELSE
        UPDATE nartobj1
        SET
        pretreferinta = v_Rec.valmat,
        cost          = v_rec.totpretfix
        WHERE
         codobiect1 = v_Rec.codobiect1;
      END IF;
    END IF;

    DELETE FROM prodcomp_clona WHERE codobiect = v_rec.codobiect;
  END LOOP;

  IF  TipPret::numeric = 1 THEN
    FOR v_rec IN (SELECT obj1.codobiect1, cc.valmat, cc.valtot, obj1.tippret, cc.totpretfix
                  FROM nartobj1 obj1
                       INNER JOIN (SELECT pcc.codobiect, max(pcc.valmat) VALMAT, max(pcc.valmat + pcc.valman + pcc.valregie) VALTOT, max(pc.totpretfix) TOTPRETFIX
                                   FROM prodcomp_clona pcc
                                        INNER JOIN prodcomp pc ON  pcc.codprodcomp = pc.codprodcomp
                                   GROUP BY pcc.codobiect
                                  ) cc ON  cc.codobiect = obj1.codobiect
                  WHERE getanlucru()*12+getlunalucru() BETWEEN obj1.alstart AND obj1.alstop
                 )
    LOOP
      IF  v_rec.tippret = 1 THEN
        UPDATE nartobj1
        SET
        pretreferinta = v_Rec.valtot,
        cost          = v_Rec.totpretfix
        WHERE
         codobiect1 = v_Rec.codobiect1;
      ELSE
        UPDATE nartobj1
        SET
        pretreferinta = v_Rec.valmat,
        cost          = v_Rec.totpretfix
        WHERE
         codobiect1 = v_Rec.codobiect1;
      END IF;
    END LOOP;
  ELSE
    IF  TipPret::numeric = 3 THEN
      FOR v_rec IN (SELECT obj1.codobiect1, cc.valmat, cc.valtot, obj1.tippret, cc.totpretfix
                    FROM nartobj1 obj1
                         INNER JOIN (SELECT pcc.codobiect, min(pcc.valmat) VALMAT, min(pcc.valmat + pcc.valman + pcc.valregie) VALTOT, min(pc.totpretfix) TOTPRETFIX
                                     FROM prodcomp_clona pcc
                                          INNER JOIN prodcomp pc ON  pc.codprodcomp = pcc.codprodcomp
                                     GROUP BY pcc.codobiect
                                    ) cc ON  cc.codobiect = obj1.codobiect
                    WHERE getanlucru()*12+getlunalucru() BETWEEN obj1.alstart AND obj1.alstop
                   )
      LOOP
        IF  v_rec.tippret = 1 THEN
          UPDATE nartobj1
          SET
          pretreferinta = v_Rec.valtot,
          cost          = v_Rec.totpretfix
          WHERE
           codobiect1 = v_Rec.codobiect1;
        ELSE
          UPDATE nartobj1
          SET
          pretreferinta = v_Rec.valmat,
          cost          = v_Rec.totpretfix
          WHERE
           codobiect1 = v_Rec.codobiect1;
        END IF;
      END LOOP;
    ELSE
      FOR v_rec IN (SELECT obj1.codobiect1, cc.valmat, cc.valtot, obj1.tippret, cc.totpretfix
                    FROM nartobj1 obj1
                         INNER JOIN (SELECT pcc.codobiect, avg(pcc.valmat) VALMAT, avg(pcc.valmat + pcc.valman + pcc.valregie) VALTOT, avg(pc.totpretfix) TOTPRETFIX
                                     FROM prodcomp_clona pcc
                                          INNER JOIN prodcomp pc ON  pc.codprodcomp = pcc.codprodcomp
                                     GROUP BY pcc.codobiect
                                    ) cc ON  cc.codobiect = obj1.codobiect
                    WHERE getanlucru()*12+getlunalucru() BETWEEN obj1.alstart AND obj1.alstop
                   )
      LOOP
        IF  v_rec.tippret = 1 THEN
          UPDATE nartobj1
          SET
          pretreferinta = v_Rec.valtot,
          cost          = v_rec.totpretfix
          WHERE
           codobiect1 = v_Rec.codobiect1;
        ELSE
          UPDATE nartobj1
          SET
          pretreferinta = v_Rec.valmat,
          cost          = v_rec.totpretfix
          WHERE
           codobiect1 = v_Rec.codobiect1;
        END IF;
      END LOOP;
    END IF;
  END IF;

  FOR v_rec IN (SELECT obj1.codobiect1, rez.pret_n, obj1.codobiect, rez.codrez
                FROM nartobj1 obj1
                     INNER JOIN prodrez r ON  obj1.codobiect = r.codobiect
                     INNER JOIN prodrez_clona rez ON  rez.codrez = r.codrez
                WHERE getanlucru()*12+getlunalucru() BETWEEN obj1.alstart AND obj1.alstop
                ORDER BY obj1.codobiect
               )
  LOOP
    UPDATE nartobj1
    SET
    pretreferinta = v_Rec.pret_n
    WHERE
     codobiect1 = v_Rec.codobiect1;

    DELETE FROM prodrez_clona WHERE codrez = v_rec.codrez;
  END LOOP;

  IF current_setting('PKG_PRODCOMP.DoCommit', true) THEN
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_updatenartobj1double</obj_name>
  <obj_hashval>46c52c417967d37029b3ae2df17ceb16</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_updatenartobj1double(acodobiect numeric, camp character varying, valoare numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  sString varchar;
BEGIN
  --Laura 26.01.2022 - sinc. Oracle (28.12.2021)
  --Adina 12.03.2021
  IF  fnc_GetValConstanta('PretRefUnicArticol', getANLUCRU(), getLUNALUCRU()) = '1' THEN
    FOR v_rec IN (SELECT obj1.*
                  FROM nartobj1 obj1
                       INNER JOIN nartobj obj  ON  obj1.codobiect  = obj.codobiect
                       INNER JOIN nartobj objp ON  objp.codarticol = obj.codarticol
                  WHERE getanlucru()*12+getlunalucru() BETWEEN obj1.alstart AND obj1.alstop
                   and  OBJP.CODOBIECT = aCodObiect
                  ORDER BY obj1.codobiect
                 )
    LOOP
      IF  v_Rec.anstart * 12 + v_Rec.lunastart &lt;&gt; getanlucru()*12+getlunalucru() THEN
        INSERT INTO nartobj1(codobiect1, codobiect, pretmaximal, procadaosmaximal, adaosla, anstart, lunastart, tippretmax, compensat, tipcompensare, grupa, uplift, codmoneda, puncte, umiditate, corpuri_straine, incoltit, hectolitrica, gluten, fuzaritate, cadere, deformare, sticlozitate, sparturi, punctesectie)
        VALUES(NEXTVAL('SEQ_NARTOBJ1_CODOBIECT1'), v_Rec.codobiect, v_Rec.pretmaximal, v_Rec.procadaosmaximal, v_Rec.adaosla, current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric, current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric, v_Rec.tippretmax, v_Rec.compensat, v_Rec.tipcompensare, v_Rec.grupa, v_Rec.uplift, v_Rec.codmoneda, v_Rec.puncte, v_Rec.umiditate, v_Rec.corpuri_straine, v_Rec.incoltit, v_Rec.hectolitrica, v_Rec.gluten, v_Rec.fuzaritate, v_Rec.cadere, v_Rec.deformare, v_Rec.sticlozitate, v_Rec.sparturi, v_Rec.punctesectie);
        CALL prc_al_refresh('nartobj1', v_Rec.codobiect);
      END IF;
    END LOOP;

    FOR v_rec IN (SELECT obj1.codobiect1
                  FROM nartobj1 obj1
                    INNER JOIN nartobj obj  ON  obj1.codobiect  = obj.codobiect
                    INNER JOIN nartobj objp ON  objp.codarticol = obj.codarticol
                  WHERE getAnLunaLucru() BETWEEN obj1.ALStart AND obj1.ALStop and  OBJP.CODOBIECT = aCodObiect
                  ORDER BY obj1.codobiect
                 )
    LOOP
      sString := 'update nartobj1 set ' || coalesce(Camp,'') || ' = ' || coalesce(replace((valoare)::varchar, ',', '.'),'') || ' where codobiect1 = ' || coalesce(v_Rec.codobiect1::varchar ,'');
      EXECUTE sString;
    END LOOP;
  ELSE
    FOR v_rec IN (SELECT obj1.* FROM nartobj1 obj1
                  WHERE getanlucru()*12+getlunalucru() BETWEEN obj1.alstart AND obj1.alstop
                   and  OBJ1.CODOBIECT = aCodObiect
                  ORDER BY obj1.codobiect
                 )
    LOOP
      IF  v_Rec.anstart * 12 + v_Rec.lunastart &lt;&gt; getanlucru()*12+getlunalucru() THEN
        INSERT INTO nartobj1(codobiect1, codobiect, pretmaximal, procadaosmaximal, adaosla, anstart, lunastart, tippretmax, compensat, tipcompensare, grupa, uplift, codmoneda, puncte, umiditate, corpuri_straine, incoltit, hectolitrica, gluten, fuzaritate, cadere, deformare, sticlozitate, sparturi, punctesectie)
        VALUES(NEXTVAL('SEQ_NARTOBJ1_CODOBIECT1'), v_Rec.codobiect, v_Rec.pretmaximal, v_Rec.procadaosmaximal, v_Rec.adaosla, current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric, current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric, v_Rec.tippretmax, v_Rec.compensat, v_Rec.tipcompensare, v_Rec.grupa, v_Rec.uplift, v_Rec.codmoneda, v_Rec.puncte, v_Rec.umiditate, v_Rec.corpuri_straine, v_Rec.incoltit, v_Rec.hectolitrica, v_Rec.gluten, v_Rec.fuzaritate, v_Rec.cadere, v_Rec.deformare, v_Rec.sticlozitate, v_Rec.sparturi, v_Rec.punctesectie);
        CALL prc_al_refresh('nartobj1', v_Rec.codobiect);
      END IF;
    END LOOP;

    FOR v_rec IN (SELECT obj1.codobiect1
                  FROM nartobj1 obj1
                  WHERE getanlucru()*12+getlunalucru() BETWEEN obj1.alstart AND obj1.alstop
                   and  obj1.codobiect = aCodObiect
                  ORDER BY obj1.codobiect
                 )
    LOOP
      sString := 'update nartobj1 set ' || coalesce(Camp,'') || ' = ' || coalesce(replace((valoare)::varchar, ',', '.'),'') || ' where codobiect1 = ' || coalesce(v_Rec.codobiect1::varchar ,'');
      EXECUTE sString;
    END LOOP;
  END IF;

  IF current_setting('PKG_PRODCOMP.DoCommit', true) THEN
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_updatepretdinpostcalc</obj_name>
  <obj_hashval>62535460140dcd8112e13df69afdc9bc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_updatepretdinpostcalc(atip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  xMat numeric;
  xVal numeric;
begin
  DELETE FROM prodcomp_clona;

  IF  fnc_GetValConstantaLucru('TipValMatPC') = '2' THEN
    xMat := 1;
    xVal := 0;
  ELSE
    xMat := 0;
    xVal := 1;
  END IF;

  INSERT INTO TMP_PCArt_Pret(codobiect, codArticol, valmat, valman, valregie)
  SELECT Codobiect, 0,
         Round(((Sum(xMat * COALESCE(Mat, 0)) + Sum(xVal * COALESCE(Val, 0)))  / Sum(COALESCE(Cant, 0)))::numeric, 5),
         Round((Sum(COALESCE(Man , 0)) / Sum(COALESCE(Cant, 0)))::numeric, 5),
         Round((Sum(COALESCE(ValS, 0)) / Sum(COALESCE(Cant, 0)))::numeric, 5)
  FROM tmp_pcart
  GROUP BY codobiect;

  IF  fnc_GetValConstantaLucru('PretRefUnicArticol') = '1' THEN
    UPDATE TMP_PCArt_Pret pc SET CodArticol = (SELECT codarticol FROM nartobj WHERE codobiect = pc.codobiect);

    FOR v_rec IN
    (
    SELECT na.Codarticol,
           Round(((Sum(xMat * COALESCE(pc.Mat, 0)) + Sum(xVal * COALESCE(pc.Val, 0)))  / Sum(COALESCE(pc.Cant, 0)))::numeric, 5) VALMAT,
           Round((Sum(COALESCE(pc.Man , 0)) / Sum(COALESCE(pc.Cant, 0)))::numeric, 5) VALMAN,
           Round((Sum(COALESCE(pc.ValS, 0)) / Sum(COALESCE(pc.Cant, 0)))::numeric, 5) VALREGIE
    FROM tmp_pcart pc INNER JOIN NartObj na ON  na.codobiect = pc.codobiect
    GROUP BY na.codArticol
    )
    LOOP
      UPDATE TMP_PCArt_Pret
      SET
      valmat   = v_rec.valmat,
      valman   = v_rec.valman,
      valregie = v_rec.valRegie
      WHERE
       CodArticol = v_rec.CodArticol;
    END LOOP;
  END IF;

  PERFORM PKG_PRODCOMP_UpdateNArtObj1(aTip);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_updateprocreal</obj_name>
  <obj_hashval>efe8913d620163544db5a6d221dacb5a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_updateprocreal(vart numeric, vproc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC    RECORD;
  V_XXX    RECORD;
  aCantNou numeric;
BEGIN
  --Florin 31.03.2023 - fixat 57823
  --Florin 23.03.2021 - pkg_userfirme_postlogcucommit
  DELETE FROM tmp_manevra_liste WHERE filtru = 'CODPRODCOMP' or  filtru = 'CODPROIECT';

  FOR v_rec IN
  (
    WITH
    nu AS
    (
      SELECT mat.codmat
      FROM prodmat mat
          INNER JOIN proiectnod pn ON  pn.codprodmat  = mat.codmat
          INNER JOIN proiect    p  ON  p.codproiect   = pn.codproiect
          INNER JOIN comanda1   c1 ON  c1.codproiect  = p.codproiect
          INNER JOIN cmdlink    l  ON  c1.codcomanda1 = l.codliniecomanda
      WHERE mat.codobiect = vart
      union ALL
      SELECT mat.codmat
      FROM livr1 l1
          INNER JOIN livr       l   ON  l1.codlivr    = l.codlivr
          INNER JOIN proiectnod pn  ON  l1.codproiect = pn.codproiect
          INNER JOIN prodmat    mat ON  mat.codmat    = pn.codprodmat
      WHERE COALESCE(l.anulat, 0) = 0 and  l.operat = 1 and  mat.codobiect = vart
    )
    SELECT mat.codmat, mat.codprodcomp, pc.data, mat.cant,
           'OBJ:' || coalesce(obj.denumire,'') || ' (' || coalesce(mat.CODPRODCOMP::varchar ,'') || ') - % utilizare.(' || coalesce(vProc::varchar,'') || ')' DOC,
           round((mat.Cant * 100 / CASE WHEN  COALESCE(mat.ProcReal, 100)=0 THEN 100 ELSE  COALESCE(mat.ProcReal, 100) END )::numeric, 7) CANTT
    FROM prodmat mat
        INNER JOIN prodcomp pc ON  mat.codprodcomp = pc.codprodcomp
        INNER JOIN nartobj obj ON  obj.codobiect   = pc.codobiect
    WHERE mat.codobiect = vart and  NOT mat.codmat IN (SELECT codmat FROM nu)
  )
  LOOP
    aCantNou := vProc / 100 * v_rec.CantT;

    UPDATE prodmat
    SET
    procreal = vProc,
    Cant     = aCantNou,
    Valoare  = Pret * vProc / 100 * v_rec.CantT
    WHERE
     codmat = v_rec.codmat;

    INSERT INTO tmp_manevra_liste(filtru, valoare) VALUES('CODPRODCOMP', v_rec.codprodcomp);

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_PRODCOMP.CT_MONITOR', true)))
    THEN
      PERFORM pkg_userfirme_postlogcucommit('PRODCOMP', current_setting('PKG_GLOBALS.USERNAME', true), 'M', v_rec.codprodcomp, current_setting('PKG_GLOBALS.FIRMANAME', true), current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, v_rec.Data, v_rec.Doc, null, current_setting('PKG_GLOBALS.EXE_VERSION', true));
    END IF;

    FOR v_xxx IN
    (
      WITH
      nu AS
      (
        SELECT pn.codproiectnod
        FROM prodmat mat
            INNER JOIN proiectnod pn ON  pn.codprodmat  = mat.codmat
            INNER JOIN proiect    p  ON  p.codproiect   = pn.codproiect
            INNER JOIN comanda1   c1 ON  c1.codproiect  = p.codproiect
            INNER JOIN cmdlink    l  ON  c1.codcomanda1 = l.codliniecomanda
        WHERE mat.codmat = v_rec.codmat
        union ALL
        SELECT pn.codproiectnod
        FROM livr1 l1
            INNER JOIN livr       l   ON  l1.codlivr    = l.codlivr
            INNER JOIN proiectnod pn  ON  l1.codproiect = pn.codproiect
            INNER JOIN prodmat    mat ON  mat.codmat    = pn.codprodmat
        WHERE COALESCE(l.anulat, 0) = 0 and  l.operat = 1 and  mat.codmat = v_rec.codmat
      )
      SELECT pn.codproiectnod, pn.codproiect, 'Inloc.mat. (' || coalesce(pn.codproiectnod::varchar ,'') || ')' DOC, p.dataproiect
      FROM proiect p
      INNER JOIN proiectnod pn ON  pn.codproiect = p.codproiect
      WHERE pn.codprodmat = v_rec.codmat and  NOT pn.codproiectnod IN (SELECT codproiectnod FROM nu)
    )
    LOOP
      UPDATE proiectnod SET cant = cant * aCantNou / v_rec.cant WHERE codproiectnod = v_xxx.codproiectnod;

      INSERT INTO tmp_manevra_liste(filtru, valoare) VALUES('CODPROIECT', v_xxx.codproiect);

      IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, 'MON_42'))
      THEN
        PERFORM pkg_userfirme_postlogcucommit('PROIECT', current_setting('PKG_GLOBALS.USERNAME', true), 'M', v_xxx.codproiect, current_setting('PKG_GLOBALS.FIRMANAME', true), current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, v_xxx.DataProiect, v_xxx.Doc, null, current_setting('PKG_GLOBALS.EXE_VERSION', true));
      END IF;
    END LOOP;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_updatevalmandintarif</obj_name>
  <obj_hashval>66b9e2678cab8197ef740e5b6bfa540a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_updatevalmandintarif(acodtarif1 numeric, atipfiltru numeric, adatastart character varying, adatastop character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC    RECORD;
  aPretRef numeric;
begin
  FOR v_rec IN
  (
  SELECT man.codman, COALESCE(man.tu, 0) * COALESCE(t1.tarif, 0) / 60 VALOARE
  FROM tarifeman1 t1
      INNER JOIN prodman man ON  man.codtarif    = t1.codtarif
      INNER JOIN prodcomp pc ON  man.codprodcomp = pc.codprodcomp
  WHERE  t1.codtarif1 = aCodTarif1
    and ((aTipFiltru = 0)
          or
         (aTipFiltru IN (1, 3) and pc.data BETWEEN to_date(aDataStart, 'dd.mm.yyyy') AND to_date(aDataStop, 'dd.mm.yyyy'))
          or
         (aTipFiltru = 2 and  pc.data &gt;= to_date(aDataStart, 'dd.mm.yyyy'))
        )
  )
  LOOP
    UPDATE prodman SET valoare = v_rec.valoare WHERE codman = v_rec.codman;
  END LOOP;

  IF  fnc_GetValConstantaLucru('PretRefAutReteta') = '1' THEN
    FOR v_rec IN
    (
    SELECT  DISTINCT man.codprodcomp
    FROM tarifeman1 t1
        INNER JOIN prodman man ON  man.codtarif   = t1.codtarif
        INNER JOIN prodcomp pc ON  pc.codprodcomp = man.codprodcomp
    WHERE t1.codtarif1 = aCodTarif1
      and ((aTipFiltru = 0)
            or
           (aTipFiltru IN (1, 3) and pc.data BETWEEN to_date(aDataStart, 'dd.mm.yyyy') AND to_date(aDataStop, 'dd.mm.yyyy'))
            or
           (aTipFiltru = 2 and  pc.data &gt;= to_date(aDataStart, 'dd.mm.yyyy'))
          )
    )
    LOOP
      aPretRef := (SELECT PKG_PRODCOMP_CalcAndGetPretRef.WME_RESULT FROM PKG_PRODCOMP_CalcAndGetPretRef(NULL,v_rec.codprodcomp));
    END LOOP;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_vdatamin</obj_name>
  <obj_hashval>19c9464be038e94715347c4d496ed6e8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_vdatamin(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_PRODCOMP.vDataMin', true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_vdatastart</obj_name>
  <obj_hashval>1b306520cc313c6c9842f2533b11f5da</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_vdatastart(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PRODCOMP.vDataStart', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_vdatastop</obj_name>
  <obj_hashval>b0215f9d968550fc0ea3a8414186ed29</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_vdatastop(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PRODCOMP.vDataStop', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_vmodgenerice</obj_name>
  <obj_hashval>bc675ea3600869a60fd5a172e996f56e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_vmodgenerice(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PRODCOMP.vModGenerice', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_vtipfiltru</obj_name>
  <obj_hashval>abfaf670305bfe7afbd10844b6f398c4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_vtipfiltru(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PRODCOMP.vTipFiltru', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_vtippretdin</obj_name>
  <obj_hashval>8767f6849b15c6340b7ceb89b7e91ec1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_vtippretdin(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PRODCOMP.vTipPretDin', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodnet_refaceredirty</obj_name>
  <obj_hashval>cf1bb694e1325cbabf17f4e77b465734</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodnet_refaceredirty(acodprodnet numeric, docommit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC    RECORD;
  V_TMP    RECORD;
  vCodGest numeric;
  vAnLuna  numeric;
  vSterg   boolean;
begin
  vAnLuna := (SELECT pkg_globals_GetANLUCRU.WME_RESULT FROM pkg_globals_GetANLUCRU(NULL,NULL)) * 12 + (SELECT pkg_globals_GetLUNALUCRU.WME_RESULT FROM pkg_globals_GetLUNALUCRU(NULL,NULL));

  SELECT pn.CodGest
  INTO vCodGest
  FROM prodnet pn
  WHERE pn.codprodnet = aCodProdNet and  pn.an * 12 + pn.luna = vAnLuna;

  FOR v_rec IN
  (
    SELECT pn1.codprodnet1, COALESCE( pn1.codies1, 0) CODIES1, pn1.coddoc1 CODCOMANDA1, COALESCE( pn1.codcmdprodmat, 0) CODCMDPRODMAT, pn1.codprodnet, COALESCE( pn1.tip, 0) TIP
    FROM prodnet1 pn1
         INNER JOIN prodnet pn ON  pn1.codprodnet = pn.codprodnet
    WHERE pn.codprodnet = aCodProdNet and  pn1.dirty = 1 and  pn.An * 12 + pn.luna = vAnLuna
  )
  LOOP
    IF  v_rec.tip = 0 THEN
      IF  v_rec.codcmdprodmat &gt; 0 THEN
        vSterg := True;

        FOR v_tmp IN
        (
          SELECT round( x.valoare, 7) VALOARE, round( x.difcant, 7) DIFCANT, round( x.cant, 7) CANT, round( x.cantReal, 7) CANTREAL
          FROM (SELECT (consumuri.cant - COALESCE( predari.cant, 0))  * consumuri.pret VALOARE,
                       consumuri.codcmdprodmat,
                       consumuri.codies1,
                       consumuri.cant - COALESCE( predari.cant, 0) DIFCANT,
                       consumuri.cant CANTREAL,
                       COALESCE( predari.cant, 0) CANT,
                       consumuri.codcomanda1
                FROM consumuri LEFT JOIN predari ON  consumuri.codcmdprodmat = predari.codcmdprodmat
                WHERE consumuri.cant - COALESCE( predari.cant, 0) &gt; 0
                ) x
              INNER JOIN comanda1   c1     ON  c1.codcomanda1  = x.codcomanda1
              INNER JOIN comanda    c      ON  c1.codcomanda   = c.codcomanda
              INNER JOIN nartobj    obj    ON  c1.codobiect    = obj.codobiect
              INNER JOIN iesiri1    i1     ON  i1.codies1      = x.codies1
              INNER JOIN nartobj    objmat ON  i1.codobiect    = objmat.codobiect
              LEFT  JOIN cmdprodmat mat    ON  x.codcmdprodmat = mat.codcmdprodmat
        )
        LOOP
          vSterg := False;
          UPDATE prodnet1
          SET
          VALMAT   = v_tmp.valoare,
          VALMAN   = 0,
          DIFCANT  = v_tmp.difcant,
          CANTREAL = v_tmp.cantreal,
          PRET     = CASE WHEN  v_tmp.difcant &lt;&gt; 0 THEN round( v_tmp.valoare / v_tmp.difcant, 2) ELSE 0 END ,
          DIRTY    = 0
          WHERE
           codprodnet1 = v_rec.codprodnet1;

          UPDATE prodnet1 SET valmat = pret * difcant WHERE codprodnet1 = v_rec.codprodnet1;
        END LOOP;

        IF vSterg THEN
          DELETE FROM prodnet1 WHERE codprodnet1 = v_rec.codprodnet1;
        END IF;
      ELSE
        vSterg := True;

        FOR v_tmp IN
        (
        SELECT sum( round( x.valoare, 7)) VALOARE
        FROM (SELECT (consumuri.cant - COALESCE( predari.cant, 0))  * consumuri.pret VALOARE, consumuri.codcomanda1, consumuri.codies1, consumuri.codcmdprodmat
              FROM consumuri LEFT JOIN predari ON  consumuri.codcmdprodmat = predari.codcmdprodmat
              WHERE consumuri.cant - COALESCE( predari.cant, 0) &gt; 0
             ) x
            INNER JOIN comanda1   c1     ON  c1.codcomanda1  = x.codcomanda1
            INNER JOIN comanda    c      ON  c1.codcomanda   = c.codcomanda
            INNER JOIN nartobj    obj    ON  c1.codobiect    = obj.codobiect
            INNER JOIN iesiri1    i1     ON  i1.codies1      = x.codies1
            INNER JOIN nartobj    objmat ON  i1.codobiect    = objmat.codobiect
            LEFT  JOIN cmdprodmat mat    ON  x.codcmdprodmat = mat.codcmdprodmat
        GROUP BY c1.codcomanda1, obj.denumire, c.nrdoc, c.datadoc
        )
        LOOP
          vSterg := False;
          UPDATE prodnet1
          SET
          VALMAT = v_tmp.valoare,
          VALMAN = 0
          WHERE
           codprodnet1 = v_rec.codprodnet1;
        END LOOP;

        IF vSterg THEN
          DELETE FROM prodnet1 WHERE codprodnet1 = v_rec.codprodnet1;
        END IF;
      END IF;
    ELSE
      IF  v_rec.codcmdprodmat &gt; 0 THEN
        vSterg := True;

        FOR v_tmp IN
        (
        SELECT round( x.valoare, 7) VALOARE, round( x.difcant, 7) DIFCANT, round( x.cant, 7) CANT, round( x.cantReal, 7) CANTREAL
        FROM (SELECT (consumuri.cant - COALESCE( predari.cant, 0))  * consumuri.pret VALOARE,
                     consumuri.codcmdprodman,
                     consumuri.cant - COALESCE( predari.cant, 0) DIFCANT,
                     consumuri.cant CANTREAL,
                     COALESCE( predari.cant, 0) CANT
              FROM consumuri LEFT JOIN predari ON  consumuri.codcmdprodman = predari.codcmdprodman
              WHERE consumuri.cant - COALESCE( predari.cant, 0) &gt; 0
             ) x
            INNER JOIN cmdprodman man ON  x.codcmdprodman = man.codcmdprodman
            INNER JOIN comanda1   c1  ON  c1.codcomanda1  = man.codcomanda1
            INNER JOIN comanda    c   ON  c1.codcomanda   = c.codcomanda
            INNER JOIN nartobj    obj ON  c1.codobiect    = obj.codobiect
            INNER JOIN noper      op  ON  op.codop        = man.codop
        )
        LOOP
          vSterg := False;
          UPDATE prodnet1
          SET
          VALMAT   = 0,
          VALMAN   = v_tmp.valoare,
          DIFCANT  = v_tmp.difcant,
          CANTREAL = v_tmp.cantreal,
          PRET     = CASE WHEN  v_tmp.difcant &lt;&gt; 0 THEN round( v_tmp.valoare / v_tmp.difcant, 2) ELSE 0 END ,
          DIRTY    = 0
          WHERE
           codprodnet1 = v_rec.codprodnet1;

          UPDATE prodnet1 SET valman = pret * difcant WHERE codprodnet1 = v_rec.codprodnet1;
        END LOOP;

        IF vSterg THEN
          DELETE FROM prodnet1 WHERE codprodnet1 = v_rec.codprodnet1;
        END IF;
      ELSE
        vSterg := True;

        FOR v_tmp IN
        (
        SELECT round( sum( x.valoare), 7) VALOARE
        FROM (SELECT sum( (consumuri.cant - COALESCE( predari.cant, 0))  * consumuri.pret) VALOARE, consumuri.codcomanda1
              FROM consumuri LEFT JOIN predari ON  consumuri.codcomanda1 = predari.codcomanda1
              WHERE consumuri.cant - COALESCE( predari.cant, 0) &gt; 0
              GROUP BY consumuri.codcomanda1
             ) x
            INNER JOIN comanda1 c1  ON  c1.codcomanda1 = x.codcomanda1
            INNER JOIN comanda  c   ON  c1.codcomanda  = c.codcomanda
            INNER JOIN nartobj  obj ON  c1.codobiect   = obj.codobiect
        GROUP BY c1.codcomanda1, c.nrdoc, c.datadoc, obj.denumire
        )
        LOOP
          vSterg := False;
          UPDATE prodnet1
          SET
          VALMAT = 0,
          VALMAN = v_tmp.valoare
          WHERE
           codprodnet1 = v_rec.codprodnet1;

          IF vSterg THEN
            DELETE FROM prodnet1 WHERE codprodnet1 = v_rec.codprodnet1;
          END IF;
        END LOOP;
      END IF;
    END IF;
  END LOOP;

  IF  COALESCE( DoCommit, 1) = 1 THEN
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodnet_setdirty</obj_name>
  <obj_hashval>053b58f0c871f4acddc1c03a8c3c4f7a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodnet_setdirty(acodcmdprodmat numeric, pan numeric, pluna numeric, atip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  vCodComanda1 numeric;
begin
  --Bogdan 16.10.2020
  vCodComanda1 := 0;
  FOR v_rec IN (SELECT pn1.codprodnet1, pn1.coddoc1
                FROM prodnet1           pn1
                  INNER JOIN prodnet    pn  ON pn1.codprodnet  = pn.codprodnet
                  INNER JOIN cmdprodmat mat ON mat.codcomanda1 = pn1.coddoc1
                WHERE
                  COALESCE (pn1.Tip, 0) = aTip
                  and mat.codcmdprodmat = aCodCmdProdMat
                  and pn1.dirty = 1
                  and pn.An * 12 + pn.luna = pAn * 12 + pLuna)
  LOOP
    vCodComanda1 := v_rec.coddoc1;
    UPDATE prodnet1 SET dirty = 1 WHERE codprodnet1 = v_rec.codprodnet1;
  END LOOP;

  IF vCodComanda1 = 0 THEN
    BEGIN
      IF aTip = 0 THEN
        SELECT COALESCE (codcomanda1, 0) INTO vCodComanda1 FROM cmdprodmat WHERE codcmdprodmat = aCodCmdProdMat;
      ELSE
        SELECT COALESCE (codcomanda1, 0) INTO vCodComanda1 FROM cmdprodman WHERE codcmdprodman = aCodCmdProdMat;
      END IF;
    EXCEPTION
    WHEN others THEN
      vCodComanda1 := 0;
    END;

    FOR v_rec IN (SELECT pn1.codprodnet1, pn1.coddoc1
                  FROM prodnet1 pn1 INNER JOIN prodnet pn ON pn1.codprodnet = pn.codprodnet
                  WHERE
                    pn1.coddoc1 = vCodComanda1
                    and pn1.dirty = 1
                    and pn.An * 12 + pn.luna = pAn * 12 + pLuna)
    LOOP
      UPDATE prodnet1 SET dirty = 1 WHERE codprodnet1 = v_rec.codprodnet1;
    END LOOP;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodnet_sp_deleterecord</obj_name>
  <obj_hashval>636b1a661475f49315d0c13366d1e404</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodnet_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC          RECORD;
  V_REC_JURN_SUB RECORD;
begin
  PERFORM PKG_GLOBALS_MarkDirtyJurnal();
  PERFORM PKG_PRODNET_SP_LOCKRECORD( RecId);

  FOR V_REC IN (SELECT * FROM JURNAL WHERE CODDOC = RecID AND  TIPDOC = 71) LOOP
    UPDATE NCONTRUL
    SET
    RULAJCD  = RULAJCD  - V_REC.VALOARE,
    RULAJVCD = RULAJVCD - V_REC.VALOAREV
    WHERE
     CODCONT = V_REC.CONTD AND  AN = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') AND  LUNA = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999');

    FOR V_REC_JURN_SUB IN (SELECT * FROM NCONTRUL WHERE CODCONT = V_REC.CONTD AND  AN = V_REC.AN AND  LUNA = V_REC.LUNA)
    LOOP
      UPDATE NCONTRULSUB
      SET
      RULAJCD  = RULAJCD  - V_REC.VALOARE,
      RULAJVCD = RULAJVCD - V_REC.VALOAREV
      WHERE
       CODCONTRUL = V_REC_JURN_SUB.CODCONTRUL AND  SUBUNITATEA = V_REC.SUBUNITATEA;
    END LOOP;

    UPDATE NCONTRUL
    SET
    RULAJCC  = RULAJCC  - V_REC.VALOARE,
    RULAJVCC = RULAJVCC - V_REC.VALOAREV
    WHERE
     CODCONT = V_REC.CONTC AND  AN = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') AND  LUNA = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999');

    FOR V_REC_JURN_SUB IN (SELECT * FROM NCONTRUL WHERE CODCONT = V_REC.CONTC AND  AN = V_REC.AN AND  LUNA = V_REC.LUNA)
    LOOP
      UPDATE NCONTRULSUB
      SET
      RULAJCC  = RULAJCC  - V_REC.VALOARE,
      RULAJVCC = RULAJVCC - V_REC.VALOAREV
      WHERE
       CODCONTRUL = V_REC_JURN_SUB.CODCONTRUL AND  SUBUNITATEA = V_REC.SUBUNITATEA;
    END LOOP;
  END LOOP;

  DELETE FROM JURNAL   WHERE CODDOC = RecID AND  TIPDOC = 71;
  DELETE FROM JURNAL1  WHERE CODDOC = RecID AND  TIPDOC = 71;
  DELETE FROM prodnet1 WHERE codprodnet = RecId;
  DELETE FROM prodnet  WHERE codprodnet = RecId;

  PERFORM NotifyModif( 2, RecId, 'PRODNET');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodnet_sp_gotorecord</obj_name>
  <obj_hashval>000ae7a7ffe66e5a75ec2788f2b364fe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodnet_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_STOC_GENERARE_FACTURI_MAKE_CONFIG_LUNA();

  INSERT INTO TMP_prodnet(Codprodnet, An, Luna, Obs, Tip, Subunitatea, CodGest, Codcentru)
  (SELECT Codprodnet, An, Luna, Obs, Tip, Subunitatea, CodGest, CodCentru FROM prodnet WHERE codprodnet = RecId);

  INSERT INTO tmp_prodnet1(codprodnet1, codprodnet, Tip, coddoc1, explicatii, valmat, valman, CODCENTRU, CODANALIZANOD, CODCMDPRODMAT, DIFCANT, CANTREAL, CANT, PRET, denumire, nrdoc, datadoc, material, codies1)
  (
  SELECT pn1.codprodnet1, pn1.codprodnet, COALESCE( pn1.Tip, 0), pn1.coddoc1, pn1.explicatii, pn1.valmat, pn1.valman, pn1.CODCENTRU, pn1.CODANALIZANOD, pn1.CODCMDPRODMAT, pn1.DIFCANT, pn1.CANTREAL, COALESCE( pn1.CANTREAL, 0) - COALESCE( pn1.DIFCANT, 0), pn1.Pret, obj.denumire, c.nrdoc, c.datadoc, objmat.denumire, pn1.codies1
  FROM prodnet1 pn1
      LEFT JOIN comanda1   c1     ON  pn1.coddoc1       = c1.codcomanda1
      LEFT JOIN comanda    c      ON  c1.codcomanda     = c.codcomanda
      LEFT JOIN nartobj    obj    ON  obj.codobiect     = c1.codobiect
      LEFT JOIN cmdprodmat mat    ON  pn1.codcmdprodmat = mat.codcmdprodmat
      LEFT JOIN iesiri1    i1     ON  pn1.codies1       = i1.codies1
      LEFT JOIN nartobj    objmat ON  i1.codobiect      = objmat.codobiect
  WHERE codprodnet = recid and  COALESCE( pn1.tip, 0) = 0
  union ALL
  SELECT pn1.codprodnet1, pn1.codprodnet, COALESCE( pn1.Tip, 0), pn1.coddoc1, pn1.explicatii, pn1.valmat, pn1.valman, pn1.CODCENTRU, pn1.CODANALIZANOD, pn1.CODCMDPRODMAT, pn1.DIFCANT, pn1.CANTREAL, COALESCE( pn1.CANTREAL, 0) - COALESCE( pn1.DIFCANT, 0), pn1.Pret, obj.denumire, c.nrdoc, c.datadoc, op.denumire, pn1.codies1
  FROM prodnet1 pn1
      LEFT JOIN comanda1   c1  ON  pn1.coddoc1       = c1.codcomanda1
      LEFT JOIN nartobj    obj ON  obj.codobiect     = c1.codobiect
      LEFT JOIN comanda    c   ON  c1.codcomanda     = c.codcomanda
      LEFT JOIN cmdprodman man ON  pn1.codcmdprodmat = man.codcmdprodman
      LEFT JOIN noper      op  ON  op.codop          = man.codop
  WHERE codprodnet = recid and  COALESCE( pn1.tip, 0) = 1
  );

  INSERT INTO TMP_JURNAL
  (SELECT * FROM JURNAL WHERE TIPDOC = 71 AND  CODDOC = RECID);

  INSERT INTO TMP_JURNAL1
  (SELECT * FROM JURNAL1 WHERE TIPDOC = 71 AND  CODDOC = RECID);

  DELETE FROM TMP_RULAJ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodnet_sp_lockrecord</obj_name>
  <obj_hashval>4dae3874bf6fd8d82ca431925098324e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodnet_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT codprodnet INTO Tmp FROM prodnet WHERE codprodnet = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_calcul_gest</obj_name>
  <obj_hashval>1fadf30b26c683e6fef12cc2d6da34cb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_calcul_gest(xt character varying, yt character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vDATASTART date;
  vDATASTOP  date;
  vZILEN     numeric;
begin
  --Florin 04.01.2022 - sinc. Oracle (29.12.2021)
  --Adina 16.08.2021 - sinc.Oracle din 14.08.2021
  --Adina 12.07.2021 - sinc.Oracle din 10.07.2021
  --Adina 09.07.2021 - sinc.Oracle din 09.07.2021
  SELECT VDELA   INTO vDATASTART FROM TMP_PROGRAMF_MANEVRA;
  SELECT VPANALA INTO vDATASTOP  FROM TMP_PROGRAMF_MANEVRA;

  SELECT count(zn1.data) INTO vZILEN FROM zineluc1 zn1
  WHERE zn1.data BETWEEN (SELECT VDELA FROM tmp_programf_manevra limit 1) AND (SELECT VpanaLA FROM tmp_programf_manevra limit 1);

  DELETE FROM TMP_PF_MAT_GEST;
  DELETE FROM TMP_PF_SDV_GEST;
  DELETE FROM TMP_PF_LOCM_GEST;
  DELETE FROM TMP_PF_MAN_GEST;

  IF  (fnc_GetValConstantaLucru('RAPORDMAN')) = '1' THEN
    INSERT INTO TMP_PF_MAT_GEST(CODOBIECT, DENOBJ, DEN_UM, DEN_GEST, CANTPROGRAMAT, RESTASIGURAT, CODGEST, REZERVAT)
    SELECT MAT.CODOBIECT, NOBJ.DENUMIRE, NUM.DEN_UM, NG.DEN_GEST, ROUND((SUM(MAT.CANT * PFM.CANT / MAN.CANT))::numeric, 2) CANT,
           sum(CASE WHEN MAT.CANT * PFM.CANT / MAN.CANT - COALESCE(REZ.CANT, 0) &lt; 0 THEN 0
                    ELSE MAT.CANT * PFM.CANT / MAN.CANT - COALESCE(REZ.CANT, 0)
               END ) RESTASIGURAT,
           C.CODGEST, SUM(COALESCE(REZ.CANT, 0))
    FROM TMP_PROGRAMFMAN_MANEVRA PFM
        INNER JOIN CMDPRODMAN MAN  ON  MAN.CODCMDPRODMAN = PFM.CODCMDPRODMAN
        INNER JOIN COMANDA1   C1   ON  C1.CODCOMANDA1    = MAN.CODCOMANDA1
        INNER JOIN COMANDA    C    ON  C.CODCOMANDA      = C1.CODCOMANDA
        INNER JOIN CMDPRODMAT MAT  ON  MAT.CODCMDPRODMAN = MAN.CODCMDPRODMAN
        INNER JOIN NARTOBJ    NOBJ ON  NOBJ.CODOBIECT    = MAT.CODOBIECT
        INNER JOIN NART            ON  NART.CODARTICOL   = NOBJ.CODARTICOL
        INNER JOIN NUM             ON  NUM.CODUM         = NART.UM
        INNER JOIN NGEST      NG   ON  C.CODGEST         = NG.CODGEST
        LEFT  JOIN (SELECT R.CODCMDPRODMAT, SUM(R.REST) CANT
                    FROM REZERVATS R
                        INNER JOIN NIRSTOC NS ON  NS.CODNIRSTOC = R.CODNIRSTOC
                        INNER JOIN NIR        ON  NIR.CODNIR    = NS.CODNIR
                        INNER JOIN NGEST   NG ON  NIR.GEST      = NG.CODGEST
                    WHERE EXISTS (SELECT codcomanda1 FROM tmp_programf1_manevra WHERE codcomanda1 = R.codcomanda1)
                      AND  NG.CODSUBUNIT = current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric
                    GROUP BY R.CODCMDPRODMAT
                   ) REZ ON  REZ.CODCMDPRODMAT = MAT.CODCMDPRODMAT
    WHERE
      (C1.CONSUM = 1 AND  MAT.TIP = 1)  OR (C1.CONSUM = 2 AND MAT.TIP IN (0, 1))
    GROUP BY
      MAT.CODOBIECT, NOBJ.DENUMIRE, NUM.DEN_UM, NG.DEN_GEST, C.CODGEST;

    INSERT INTO TMP_PF_SDV_GEST(CODPROGRAMFSDV, CODPROGRAMF, CODGEST, CODOBIECT, CANT, STOC, DEN_GEST, DEN_UM)
    SELECT COALESCE(PROGSDV.CODPROGRAMFSDV, -1) CODPROGRAMFSDV, PFM.CODPROGRAMF, NG.CODGEST, PSDV.CODSDV,
           COALESCE(PROGSDV.CANT, ROUND((PSDV.CANT * PFM.CANT / MAN.CANT)::numeric, 2)) CANT,
           ROUND((COALESCE(STOC.REST, 0))::numeric, 2), NG.DEN_GEST, NUM.DEN_UM
    FROM TMP_PROGRAMFMAN_MANEVRA PFM
    INNER JOIN CMDPRODMAN MAN  ON  PFM.CODCMDPRODMAN = MAN.CODCMDPRODMAN
    INNER JOIN COMANDA1   C1   ON  C1.CODCOMANDA1    = MAN.CODCOMANDA1
    INNER JOIN COMANDA    C    ON  C.CODCOMANDA      = C1.CODCOMANDA
    INNER JOIN PRODSDV    PSDV ON  PSDV.CODPRODMAN   = MAN.CODMAN
    INNER JOIN NGEST      NG   ON  NG.CODGEST        = C.CODGEST
    INNER JOIN NARTOBJ    NOBJ ON  PSDV.CODSDV       = NOBJ.CODOBIECT
    INNER JOIN NART            ON  NART.CODARTICOL   = NOBJ.CODARTICOL
    INNER JOIN NUM             ON  NUM.CODUM         = NART.UM
    LEFT  JOIN (SELECT NS.CODOBIECT, SUM(NS.REST) REST FROM NIRSTOC NS GROUP BY NS.CODOBIECT
               )           STOC    ON  PSDV.CODSDV = STOC.CODOBIECT
    LEFT  JOIN PROGRAMFSDV PROGSDV ON  PROGSDV.CODPROGRAMF = PFM.CODPROGRAMF AND  PROGSDV.CODGEST = C.CODGEST AND  PROGSDV.CODOBIECT = PSDV.CODSDV;

    INSERT INTO TMP_PF_LOCM_GEST(SECTIE, CODGEST, CODLOCMUNCA, DISPONIBIL, NECESAR, DIFERENTE, DISPONIBILM, NECESARM, DIFERENTEM)
    WITH
    CRS_ZILE AS
    (
    SELECT T.CodProgramf,
           (T.vPanaLa - T.VDeLa)  + 1 - (SELECT count(zn1.data) FROM zineluc1 zn1
                                         WHERE zn1.data BETWEEN (SELECT VDELA FROM tmp_programf_manevra limit 1) AND (SELECT VpanaLA FROM tmp_programf_manevra limit 1)
                                        ) ZILE
    FROM TMP_PROGRAMF_MANEVRA T
    ),
    CRS_NECESAR AS
    (
    SELECT SUM(PFM.CANT * COALESCE(PMAN.TPI, 0) + PFM.CANT * PMAN.TU) NECESAR, NG.ORESCHIMB * NG.NRSCHIMBURI * ZILE.ZILE DISPONIBIL,
           COALESCE(PMAN.CODLOC, 0) CODLOC, COALESCE(CMD.CODGEST, 0) CODGEST
    FROM (SELECT ZILE FROM CRS_ZILE limit 1) ZILE, TMP_PROGRAMFMAN_MANEVRA PFM
        INNER JOIN CMDPRODMAN PMAN ON  PMAN.CODCMDPRODMAN = PFM.CODCMDPRODMAN
        INNER JOIN COMANDA1   CMD1 ON  PMAN.CODCOMANDA1   = CMD1.CODCOMANDA1
        INNER JOIN COMANDA    CMD  ON  CMD1.CODCOMANDA    = CMD.CODCOMANDA
        INNER JOIN NGEST      NG   ON  NG.CODGEST         = CMD.CODGEST
    GROUP BY NG.ORESCHIMB, NG.NRSCHIMBURI, ZILE.ZILE, PMAN.CODLOC, CMD.CODGEST
    )
    SELECT NG.DEN_GEST SECTIE, NG.CODGEST, NECESAR.CODLOC,
           coalesce(NECESAR.DISPONIBIL,0)  DISPONIBIL,
           coalesce(NECESAR.NECESAR,0)/60  NECESAR,
           coalesce(NECESAR.DISPONIBIL,0) - coalesce(NECESAR.NECESAR,0)/60  DIFERENTE,
           COALESCE(NECESAR.DISPONIBIL, 0) * 60 DISPONIBILM,
           COALESCE(NECESAR.NECESAR, 0) NECESARM,
           COALESCE(NECESAR.DISPONIBIL, 0) * 60 - COALESCE(NECESAR.NECESAR, 0) DIFERENTEM
    FROM CRS_NECESAR NECESAR INNER JOIN NGEST NG ON  NG.CODGEST = NECESAR.CODGEST;

    INSERT INTO TMP_PF_MAN_GEST(CODOP, CODGEST, DEN_GEST, ORE, VALOARE, OREM, OPERATII)
    SELECT OP.CODOP, G.CodGEST, G.DEN_GEST,
           round((sum(PFM.CANT * coalesce(MAN.TPI, 0) + PFM.CANT * coalesce(MAN.TU, 0)) / 60)::numeric, 3),
           round((sum(PFM.CANT * COALESCE(MAN.TPI, 0) + PFM.CANT * COALESCE(MAN.TU, 0) / 60 * T1.TARIF))::numeric, 2),
           round((sum(PFM.CANT * COALESCE(MAN.TPI, 0) + PFM.CANT * COALESCE(MAN.TU, 0)))::numeric, 2),
           SUM(MAN.CANT)
    FROM TMP_PROGRAMFMAN_MANEVRA PFM
        INNER JOIN CMDPRODMAN MAN ON  MAN.CODCMDPRODMAN = PFM.CODCMDPRODMAN
        INNER JOIN COMANDA1   C1  ON  MAN.CODCOMANDA1   = C1.CODCOMANDA1
        INNER JOIN COMANDA    C   ON  C1.CODCOMANDA     = C.CODCOMANDA
        INNER JOIN NGEST      G   ON  C.CODGEST         = G.CODGEST
        INNER JOIN NOPER      OP  ON  OP.CODOP          = MAN.CODOP
        INNER JOIN TARIFEMAN1 T1  ON  T1.CODTARIF       = MAN.CODTARIF
        WHERE GetAnLunaLucru() BETWEEN T1.ALSTART AND T1.ALSTOP
    GROUP BY OP.CODOP, G.CODGEST, G.DEN_GEST;
  ELSE
    INSERT INTO TMP_PF_MAT_GEST(CODOBIECT, DENOBJ, DEN_UM, DEN_GEST, CANTPROGRAMAT, STOCDISP, RESTASIGURAT, CODGEST, REZERVAT)
    SELECT PRODM.CODOBIECT, NOBJ.DENUMIRE, NUM.DEN_UM, NG.DEN_GEST,
           ROUND((SUM(PRODM.CANT * PF1.CANTPROGRAMAT / C1.CANTACCEPTAT))::numeric, 2) CANT,
           ROUND((COALESCE(STOC.STOCDISP, 0))::numeric, 2),
           sum(CASE WHEN PRODM.CANT * PF1.CANTPROGRAMAT / C1.CANTACCEPTAT - COALESCE(REZ.CANT, 0) &lt; 0 THEN 0
                    ELSE PRODM.CANT * PF1.CANTPROGRAMAT / C1.CANTACCEPTAT - COALESCE(REZ.CANT, 0)
               END ) RESTASIGURAT,
           C.CODGEST, SUM(COALESCE(REZ.CANT, 0))
    FROM TMP_PROGRAMF1_MANEVRA PF1
        INNER JOIN COMANDA1    C1    ON  C1.CODCOMANDA1    = PF1.CODCOMANDA1
        INNER JOIN COMANDA     C     ON  C.CODCOMANDA      = C1.CODCOMANDA
        INNER JOIN CMDPRODMAT  PRODM ON  PRODM.CODCOMANDA1 = C1.CODCOMANDA1
        INNER JOIN NARTOBJ     NOBJ  ON  NOBJ.CODOBIECT    = PRODM.CODOBIECT
        INNER JOIN NART              ON  NART.CODARTICOL   = NOBJ.CODARTICOL
        INNER JOIN NUM               ON  NUM.CODUM         = NART.UM
        INNER JOIN PRODCOMP    PC    ON  PC.CODPRODCOMP    = C1.CODRETETA
        INNER JOIN NGEST       NG    ON  NG.CODGEST        = C.CODGEST
        LEFT  JOIN (SELECT NS.CODOBIECT, SUM(NS.REST) STOCDISP
                    FROM NIRSTOC NS
                        INNER JOIN NIR      ON  NIR.CODNIR = NS.CODNIR
                        INNER JOIN NGEST NG ON  NIR.GEST   = NG.CODGEST
                    WHERE NG.CODSUBUNIT = current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric
                    GROUP BY CODOBIECT
                   ) STOC ON  STOC.CODOBIECT = PRODM.CODOBIECT
        LEFT  JOIN (SELECT R.CODCMDPRODMAT, SUM(R.REST) CANT
                    FROM REZERVATS R
                        INNER JOIN NIRSTOC NS ON  NS.CODNIRSTOC = R.CODNIRSTOC
                        INNER JOIN NIR        ON  NIR.CODNIR    = NS.CODNIR
                        INNER JOIN NGEST   NG ON  NIR.GEST      = NG.CODGEST
                    WHERE EXISTS (SELECT codcomanda1 FROM tmp_programf1_manevra WHERE codcomanda1 = R.codcomanda1)
                      AND  NG.CODSUBUNIT = current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric
                    GROUP BY R.CODCMDPRODMAT
                   ) REZ ON  REZ.CODCMDPRODMAT = PRODM.CODCMDPRODMAT
    WHERE
      (C1.CONSUM = 1 AND  PRODM.TIP = 1)  OR (C1.CONSUM = 2 AND PRODM.TIP IN (0, 1))
    GROUP BY PRODM.CODOBIECT, NOBJ.DENUMIRE, NUM.DEN_UM, NG.DEN_GEST, C.CODGEST, COALESCE(STOC.STOCDISP, 0);

    INSERT INTO TMP_PF_SDV_GEST(CODPROGRAMFSDV, CODPROGRAMF, CODGEST, CODOBIECT, CANT, STOC, DEN_GEST, DEN_UM)
    SELECT COALESCE(PROGSDV.CODPROGRAMFSDV, -1) CODPROGRAMFSDV, PF1.CODPROGRAMF, NG.CODGEST, PSDV.CODSDV,
           ROUND((COALESCE(PROGSDV.CANT, PSDV.CANT) * PF1.CANTPROGRAMAT)::numeric, 2) CANT, ROUND((COALESCE(STOC.REST, 0))::numeric, 2), NG.DEN_GEST, NUM.DEN_UM
    FROM TMP_PROGRAMF1_MANEVRA PF1
    INNER JOIN COMANDA1    C1      ON  C1.CODCOMANDA1   = PF1.CODCOMANDA1
    INNER JOIN COMANDA     C       ON  C.CODCOMANDA     = C1.CODCOMANDA
    INNER JOIN PRODSDV     PSDV    ON  PSDV.CODPRODCOMP = C1.CODRETETA
    INNER JOIN NGEST       NG      ON  NG.CODGEST       = C.CODGEST
    INNER JOIN NARTOBJ     NOBJ    ON  PSDV.CODSDV      = NOBJ.CODOBIECT
    INNER JOIN NART                ON  NART.CODARTICOL  = NOBJ.CODARTICOL
    INNER JOIN NUM                 ON  NUM.CODUM        = NART.UM
    LEFT  JOIN (SELECT NS.CODOBIECT, SUM(NS.REST) REST FROM NIRSTOC NS GROUP BY NS.CODOBIECT) STOC ON  PSDV.CODSDV = STOC.CODOBIECT
    LEFT  JOIN PROGRAMFSDV PROGSDV ON  PROGSDV.CODPROGRAMF = PF1.CODPROGRAMF AND  PROGSDV.CODGEST = C.CODGEST AND  PROGSDV.CODOBIECT = PSDV.CODSDV;

    INSERT INTO TMP_PF_LOCM_GEST(SECTIE, CODGEST, CODLOCMUNCA, DISPONIBIL, NECESAR, DIFERENTE, DISPONIBILM, NECESARM, DIFERENTEM)
    WITH
    CRS_ZILE AS
    (SELECT T.CodProgramf,
            (T.vPanaLa - T.VDeLa)  + 1 - (SELECT count(zn1.data) FROM zineluc1 zn1
                                          WHERE zn1.data BETWEEN (SELECT VDELA FROM tmp_programf_manevra limit 1) AND (SELECT VpanaLA FROM tmp_programf_manevra limit 1)
                                         ) ZILE
     FROM TMP_PROGRAMF_MANEVRA T
    ),
    CRS_NECESAR AS
    (SELECT SUM(CASE WHEN  PC.CANT &lt;&gt; 1 THEN PF1.CANTPROGRAMAT / PC.CANT * COALESCE(PMAN.TPI, 0) + PF1.CANTPROGRAMAT / PMAN.BPS * PMAN.TU
                     ELSE COALESCE(PMAN.TPI, 0) + PF1.CANTPROGRAMAT / PMAN.BPS * PMAN.TU
                END ) NECESAR,
            NG.ORESCHIMB * NG.NRSCHIMBURI * ZILE.ZILE DISPONIBIL, COALESCE(PMAN.CODLOC, 0) CODLOC, COALESCE(CMD.CODGEST, 0) CODGEST
     FROM (SELECT ZILE FROM CRS_ZILE limit 1) ZILE, TMP_PROGRAMF1_MANEVRA PF1
        INNER JOIN COMANDA1   CMD1 ON  PF1.CODCOMANDA1  = CMD1.CODCOMANDA1
        INNER JOIN COMANDA    CMD  ON  CMD1.CODCOMANDA  = CMD.CODCOMANDA
        INNER JOIN PRODCOMP   PC   ON  CMD1.CODRETETA   = PC.CODPRODCOMP
        INNER JOIN CMDPRODMAN PMAN ON  PMAN.CODCOMANDA1 = CMD1.CODCOMANDA1
        INNER JOIN NGEST      NG   ON  NG.CODGEST       = CMD.CODGEST
     GROUP BY NG.ORESCHIMB, NG.NRSCHIMBURI, ZILE.ZILE, PMAN.CODLOC, CMD.CODGEST
    )
    SELECT NG.DEN_GEST SECTIE, NG.CODGEST, NECESAR.CODLOC,
           coalesce(NECESAR.DISPONIBIL,0)  DISPONIBIL,
           coalesce(NECESAR.NECESAR,0)/60  NECESAR,
           coalesce(NECESAR.DISPONIBIL,0) - coalesce(NECESAR.NECESAR,0)/60  DIFERENTE,
           COALESCE(NECESAR.DISPONIBIL, 0) * 60 DISPONIBILM,
           COALESCE(NECESAR.NECESAR, 0) NECESARM,
           COALESCE(NECESAR.DISPONIBIL, 0) * 60 - COALESCE(NECESAR.NECESAR, 0) DIFERENTEM
    FROM CRS_NECESAR NECESAR
    INNER JOIN NGEST NG ON  NG.CODGEST = NECESAR.CODGEST;

    INSERT INTO TMP_PF_MAN_GEST(CODOP, CODGEST, DEN_GEST, ORE, VALOARE, OREM, OPERATII)
    SELECT OP.CODOP, G.CodGEST, G.DEN_GEST,
           round((sum(CASE WHEN PC.CANT &lt;&gt; 1 THEN round((PF1.CANTPROGRAMAT/coalesce(PC.CANT, 1) * coalesce(MAN.TPI, 0) + PF1.CANTPROGRAMAT / coalesce(MAN.BPS, 1) * coalesce(MAN.TU, 0))::numeric, 2)
                          ELSE round((coalesce(MAN.TPI, 0) + PF1.CANTPROGRAMAT * coalesce(MAN.TU, 0))::numeric, 2)
                     END
                    ) / 60)::numeric, 2),
           round((sum(CASE WHEN  PC.CANT &lt;&gt; 1 THEN round((PF1.CANTPROGRAMAT / COALESCE(PC.CANT, 1) * COALESCE(MAN.TPI, 0) + PF1.CANTPROGRAMAT / COALESCE(MAN.BPS, 1) * COALESCE(MAN.TU, 0))::numeric, 2)
                           ELSE round((COALESCE(MAN.TPI, 0) + PF1.CANTPROGRAMAT * COALESCE(MAN.TU, 0))::numeric, 2)
                      END  * T1.TARIF) / 60)::numeric, 2),
           round((sum(CASE WHEN  PC.CANT &lt;&gt; 1 THEN round((PF1.CANTPROGRAMAT / COALESCE(PC.CANT, 1) * COALESCE(MAN.TPI, 0) + PF1.CANTPROGRAMAT / COALESCE(MAN.BPS, 1) * COALESCE(MAN.TU, 0))::numeric, 2)
                           ELSE round((COALESCE(MAN.TPI, 0) + PF1.CANTPROGRAMAT * COALESCE(MAN.TU, 0))::numeric, 2)
                      END ))::numeric, 2),
           SUM(MAN.CANT)
    FROM TMP_PROGRAMF1_MANEVRA PF1
        INNER JOIN COMANDA1   C1  ON  PF1.CODCOMANDA1 = C1.CODCOMANDA1
        INNER JOIN COMANDA    C   ON  C1.CODCOMANDA   = C.CODCOMANDA
        INNER JOIN PRODCOMP   PC  ON  C1.CODRETETA    = PC.CODPRODCOMP
        INNER JOIN CMDPRODMAN MAN ON  MAN.CODCOMANDA1 = PF1.CODCOMANDA1
        INNER JOIN PRODGEST   PG  ON  PG.CODPRODGEST  = MAN.CODPRODGEST
        INNER JOIN NGEST      G   ON  C.CODGEST       = G.CODGEST
        INNER JOIN NOPER      OP  ON  OP.CODOP        = MAN.CODOP
        INNER JOIN TARIFEMAN1 T1  ON  T1.CODTARIF     = MAN.CODTARIF
        WHERE GetAnLunaLucru() BETWEEN T1.ALSTART AND T1.ALSTOP
    GROUP BY OP.CODOP, G.CODGEST, G.DEN_GEST;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_calcul_gest_xx</obj_name>
  <obj_hashval>5ea9441106a9b855815bb0c4ba94d55c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_calcul_gest_xx(xt character varying, yt character varying, vtip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vDATASTART date;
  vDATASTOP  date;
  vZILEN     numeric;
BEGIN
  --Adina 12.07.2021 - sinc.Oracle din 10.07.2021
  --Adina 09.07.2021 - sinc.Oracle din 09.07.2021
  SELECT VDELA   INTO vDATASTART FROM TMP_PROGRAMF_MANEVRA;
  SELECT VPANALA INTO vDATASTOP  FROM TMP_PROGRAMF_MANEVRA;

  SELECT count(zn1.data) INTO vZILEN FROM zineluc1 zn1
  WHERE zn1.data BETWEEN (SELECT VDELA FROM tmp_programf_manevra limit 1) AND (SELECT VpanaLA FROM tmp_programf_manevra limit 1);

  DELETE FROM TMP_PF_MAT_GEST;
  DELETE FROM TMP_PF_SDV_GEST;
  DELETE FROM TMP_PF_LOCM_GEST;
  DELETE FROM TMP_PF_MAN_GEST;

  IF  (fnc_GetValConstantaLucru('RAPORDMAN')) = '1' THEN
    INSERT INTO TMP_PF_MAT_GEST(CODOBIECT, DENOBJ, DEN_UM, DEN_GEST, CANTPROGRAMAT, RESTASIGURAT, CODGEST, REZERVAT)
    SELECT MAT.CODOBIECT, NOBJ.DENUMIRE, NUM.DEN_UM, NG.DEN_GEST, ROUND((SUM(MAT.CANT * PFM.CANT / MAN.CANT))::numeric, 2) CANT,
           sum(CASE WHEN  MAT.CANT * PFM.CANT / MAN.CANT - COALESCE(REZ.CANT, 0) &lt; 0 THEN 0
                    ELSE MAT.CANT * PFM.CANT / MAN.CANT - COALESCE(REZ.CANT, 0)
               END ) RESTASIGURAT,
           C.CODGEST, SUM(COALESCE(REZ.CANT, 0))
    FROM TMP_PROGRAMFMAN_MANEVRA PFM
        INNER JOIN CMDPRODMAN MAN  ON  MAN.CODCMDPRODMAN = PFM.CODCMDPRODMAN
        INNER JOIN COMANDA1   C1   ON  C1.CODCOMANDA1    = MAN.CODCOMANDA1
        INNER JOIN COMANDA    C    ON  C.CODCOMANDA      = C1.CODCOMANDA
        INNER JOIN CMDPRODMAT MAT  ON  MAT.CODCMDPRODMAN = MAN.CODCMDPRODMAN
        INNER JOIN NARTOBJ    NOBJ ON  NOBJ.CODOBIECT    = MAT.CODOBIECT
        INNER JOIN NART            ON  NART.CODARTICOL   = NOBJ.CODARTICOL
        INNER JOIN NUM             ON  NUM.CODUM         = NART.UM
        INNER JOIN NGEST      NG   ON  C.CODGEST         = NG.CODGEST
        LEFT  JOIN (SELECT R.CODCMDPRODMAT, SUM(R.REST) CANT
                    FROM REZERVATS R
                        INNER JOIN NIRSTOC NS ON  NS.CODNIRSTOC = R.CODNIRSTOC
                        INNER JOIN NIR        ON  NIR.CODNIR    = NS.CODNIR
                        INNER JOIN NGEST   NG ON  NIR.GEST      = NG.CODGEST
                    WHERE EXISTS (SELECT codcomanda1 FROM tmp_programf1_manevra WHERE codcomanda1 = R.codcomanda1)
                      AND  NG.CODSUBUNIT = current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric
                    GROUP BY R.CODCMDPRODMAT
                   ) REZ ON  REZ.CODCMDPRODMAT = MAT.CODCMDPRODMAT
    WHERE
      (C1.CONSUM = 1 AND  MAT.TIP = 1)  OR (C1.CONSUM = 2 AND MAT.TIP IN (0, 1))
    GROUP BY
      MAT.CODOBIECT, NOBJ.DENUMIRE, NUM.DEN_UM, NG.DEN_GEST, C.CODGEST;

    INSERT INTO TMP_PF_SDV_GEST(CODPROGRAMFSDV, CODPROGRAMF, CODGEST, CODOBIECT, CANT, STOC, DEN_GEST, DEN_UM)
    SELECT COALESCE(PROGSDV.CODPROGRAMFSDV, -1) CODPROGRAMFSDV, PFM.CODPROGRAMF, NG.CODGEST, PSDV.CODSDV,
           COALESCE(PROGSDV.CANT, ROUND((PSDV.CANT * PFM.CANT / MAN.CANT)::numeric, 2)) CANT,
           ROUND((COALESCE(STOC.REST, 0))::numeric, 2), NG.DEN_GEST, NUM.DEN_UM
    FROM TMP_PROGRAMFMAN_MANEVRA PFM
    INNER JOIN CMDPRODMAN MAN  ON  PFM.CODCMDPRODMAN = MAN.CODCMDPRODMAN
    INNER JOIN COMANDA1   C1   ON  C1.CODCOMANDA1    = MAN.CODCOMANDA1
    INNER JOIN COMANDA    C    ON  C.CODCOMANDA      = C1.CODCOMANDA
    INNER JOIN PRODSDV    PSDV ON  PSDV.CODPRODMAN   = MAN.CODMAN
    INNER JOIN NGEST      NG   ON  NG.CODGEST        = C.CODGEST
    INNER JOIN NARTOBJ    NOBJ ON  PSDV.CODSDV       = NOBJ.CODOBIECT
    INNER JOIN NART            ON  NART.CODARTICOL   = NOBJ.CODARTICOL
    INNER JOIN NUM             ON  NUM.CODUM         = NART.UM
    LEFT  JOIN (SELECT NS.CODOBIECT, SUM(NS.REST) REST FROM NIRSTOC NS GROUP BY NS.CODOBIECT
               )           STOC    ON  PSDV.CODSDV = STOC.CODOBIECT
    LEFT  JOIN PROGRAMFSDV PROGSDV ON  PROGSDV.CODPROGRAMF = PFM.CODPROGRAMF AND  PROGSDV.CODGEST = C.CODGEST AND  PROGSDV.CODOBIECT = PSDV.CODSDV;

    INSERT INTO TMP_PF_LOCM_GEST(SECTIE, CODGEST, CODLOCMUNCA, DISPONIBIL, NECESAR, DIFERENTE, DISPONIBILM, NECESARM, DIFERENTEM)
    WITH
    CRS_ZILE AS
    (
    SELECT T.CodProgramf,
           (T.vPanaLa - T.VDeLa)  + 1 - (SELECT count(zn1.data) FROM zineluc1 zn1
                                         WHERE zn1.data BETWEEN (SELECT VDELA FROM tmp_programf_manevra limit 1) AND (SELECT VpanaLA FROM tmp_programf_manevra limit 1)
                                        ) ZILE
    FROM TMP_PROGRAMF_MANEVRA T
    ),
    CRS_NECESAR AS
    (
    SELECT SUM(PFM.CANT * COALESCE(PMAN.TPI, 0) + PFM.CANT * PMAN.TU) NECESAR, NG.ORESCHIMB * NG.NRSCHIMBURI * ZILE.ZILE DISPONIBIL,
           COALESCE(PMAN.CODLOC, 0) CODLOC, COALESCE(CMD.CODGEST, 0) CODGEST
    FROM (SELECT ZILE FROM CRS_ZILE limit 1) ZILE, TMP_PROGRAMFMAN_MANEVRA PFM
        INNER JOIN CMDPRODMAN PMAN ON  PMAN.CODCMDPRODMAN = PFM.CODCMDPRODMAN
        INNER JOIN COMANDA1   CMD1 ON  PMAN.CODCOMANDA1   = CMD1.CODCOMANDA1
        INNER JOIN COMANDA    CMD  ON  CMD1.CODCOMANDA    = CMD.CODCOMANDA
        INNER JOIN NGEST      NG   ON  NG.CODGEST         = CMD.CODGEST
    GROUP BY NG.ORESCHIMB, NG.NRSCHIMBURI, ZILE.ZILE, PMAN.CODLOC, CMD.CODGEST
    )
    SELECT NG.DEN_GEST SECTIE, NG.CODGEST, NECESAR.CODLOC,
           CASE WHEN  vtip &lt;&gt; 0 THEN COALESCE(NECESAR.DISPONIBIL, 0)   ELSE COALESCE(NECESAR.DISPONIBIL, 0) * 60 END  DISPONIBIL,
           CASE WHEN  vtip &lt;&gt; 0 THEN COALESCE(NECESAR.NECESAR, 0) / 60 ELSE COALESCE(NECESAR.NECESAR, 0)         END  NECESAR,
           CASE WHEN  vtip &lt;&gt; 0 THEN COALESCE(NECESAR.DISPONIBIL, 0) - COALESCE(NECESAR.NECESAR, 0) / 60
                ELSE COALESCE(NECESAR.DISPONIBIL, 0) * 60 - COALESCE(NECESAR.NECESAR, 0)
           END  DIFERENTE,
           COALESCE(NECESAR.DISPONIBIL, 0) * 60 DISPONIBILM, COALESCE(NECESAR.NECESAR, 0) NECESARM,
           COALESCE(NECESAR.DISPONIBIL, 0) * 60 - COALESCE(NECESAR.NECESAR, 0) DIFERENTEM
    FROM CRS_NECESAR NECESAR INNER JOIN NGEST NG ON  NG.CODGEST = NECESAR.CODGEST;

    INSERT INTO TMP_PF_MAN_GEST(CODOP, CODGEST, DEN_GEST, ORE, VALOARE, OREM, OPERATII)
    SELECT OP.CODOP, G.CodGEST, G.DEN_GEST,
           CASE WHEN  vtip &lt;&gt; 0 THEN round((sum(PFM.CANT * COALESCE(MAN.TPI, 0) + PFM.CANT * COALESCE(MAN.TU, 0)) / 60)::numeric, 2)
                ELSE round((sum(PFM.CANT * COALESCE(MAN.TPI, 0) + PFM.CANT * COALESCE(MAN.TU, 0)))::numeric, 2)
           END ,
           round((sum(PFM.CANT * COALESCE(MAN.TPI, 0) + PFM.CANT * COALESCE(MAN.TU, 0) / 60 * T1.TARIF))::numeric, 2),
           round((sum(PFM.CANT * COALESCE(MAN.TPI, 0) + PFM.CANT * COALESCE(MAN.TU, 0)))::numeric, 2),
           SUM(MAN.CANT)
    FROM TMP_PROGRAMFMAN_MANEVRA PFM
        INNER JOIN CMDPRODMAN MAN ON  MAN.CODCMDPRODMAN = PFM.CODCMDPRODMAN
        INNER JOIN COMANDA1   C1  ON  MAN.CODCOMANDA1   = C1.CODCOMANDA1
        INNER JOIN COMANDA    C   ON  C1.CODCOMANDA     = C.CODCOMANDA
        INNER JOIN NGEST      G   ON  C.CODGEST         = G.CODGEST
        INNER JOIN NOPER      OP  ON  OP.CODOP          = MAN.CODOP
        INNER JOIN TARIFEMAN1 T1  ON  T1.CODTARIF       = MAN.CODTARIF
    WHERE
       T1.ANSTART * 12 + T1.LUNASTART = (SELECT MAX(T2.ANSTART * 12 + T2.LUNASTART)
                                         FROM TARIFEMAN1 T2
                                         WHERE  T2.CODTARIF = T1.CODTARIF
                                           AND  T2.ANSTART * 12 + T2.LUNASTART &lt;= (SELECT PKG_GLOBALS_AnLunaLucru.WME_RESULT FROM PKG_GLOBALS_AnLunaLucru(NULL,NULL))
                                        )
    GROUP BY OP.CODOP, G.CODGEST, G.DEN_GEST;
  ELSE
    INSERT INTO TMP_PF_MAT_GEST(CODOBIECT, DENOBJ, DEN_UM, DEN_GEST, CANTPROGRAMAT, STOCDISP, RESTASIGURAT, CODGEST, REZERVAT)
    SELECT PRODM.CODOBIECT, NOBJ.DENUMIRE, NUM.DEN_UM, NG.DEN_GEST,
           ROUND((SUM(PRODM.CANT * PF1.CANTPROGRAMAT / C1.CANTACCEPTAT))::numeric, 2) CANT,
           ROUND((COALESCE(STOC.STOCDISP, 0))::numeric, 2),
           sum(CASE WHEN  PRODM.CANT * PF1.CANTPROGRAMAT / C1.CANTACCEPTAT - COALESCE(REZ.CANT, 0) &lt; 0 THEN 0
                    ELSE PRODM.CANT * PF1.CANTPROGRAMAT / C1.CANTACCEPTAT - COALESCE(REZ.CANT, 0)
               END ) RESTASIGURAT,
           C.CODGEST, SUM(COALESCE(REZ.CANT, 0))
    FROM TMP_PROGRAMF1_MANEVRA PF1
        INNER JOIN COMANDA1    C1    ON  C1.CODCOMANDA1    = PF1.CODCOMANDA1
        INNER JOIN COMANDA     C     ON  C.CODCOMANDA      = C1.CODCOMANDA
        INNER JOIN CMDPRODMAT  PRODM ON  PRODM.CODCOMANDA1 = C1.CODCOMANDA1
        INNER JOIN NARTOBJ     NOBJ  ON  NOBJ.CODOBIECT    = PRODM.CODOBIECT
        INNER JOIN NART              ON  NART.CODARTICOL   = NOBJ.CODARTICOL
        INNER JOIN NUM               ON  NUM.CODUM         = NART.UM
        INNER JOIN PRODCOMP    PC    ON  PC.CODPRODCOMP    = C1.CODRETETA
        INNER JOIN NGEST       NG    ON  NG.CODGEST        = C.CODGEST
        LEFT  JOIN (SELECT NS.CODOBIECT, SUM(NS.REST) STOCDISP
                    FROM NIRSTOC NS
                        INNER JOIN NIR      ON  NIR.CODNIR = NS.CODNIR
                        INNER JOIN NGEST NG ON  NIR.GEST   = NG.CODGEST
                    WHERE NG.CODSUBUNIT = current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric
                    GROUP BY CODOBIECT
                   ) STOC ON  STOC.CODOBIECT = PRODM.CODOBIECT
        LEFT  JOIN (SELECT R.CODCMDPRODMAT, SUM(R.REST) CANT
                    FROM REZERVATS R
                        INNER JOIN NIRSTOC NS ON  NS.CODNIRSTOC = R.CODNIRSTOC
                        INNER JOIN NIR        ON  NIR.CODNIR    = NS.CODNIR
                        INNER JOIN NGEST   NG ON  NIR.GEST      = NG.CODGEST
                    WHERE EXISTS (SELECT codcomanda1 FROM tmp_programf1_manevra WHERE codcomanda1 = R.codcomanda1)
                      AND  NG.CODSUBUNIT = current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric
                    GROUP BY R.CODCMDPRODMAT
                   ) REZ ON  REZ.CODCMDPRODMAT = PRODM.CODCMDPRODMAT
    WHERE
      (C1.CONSUM = 1 AND  PRODM.TIP = 1)  OR (C1.CONSUM = 2 AND PRODM.TIP IN (0, 1))
    GROUP BY PRODM.CODOBIECT, NOBJ.DENUMIRE, NUM.DEN_UM, NG.DEN_GEST, C.CODGEST, COALESCE(STOC.STOCDISP, 0);

    INSERT INTO TMP_PF_SDV_GEST(CODPROGRAMFSDV, CODPROGRAMF, CODGEST, CODOBIECT, CANT, STOC, DEN_GEST, DEN_UM)
    SELECT COALESCE(PROGSDV.CODPROGRAMFSDV, -1) CODPROGRAMFSDV, PF1.CODPROGRAMF, NG.CODGEST, PSDV.CODSDV,
           ROUND((COALESCE(PROGSDV.CANT, PSDV.CANT) * PF1.CANTPROGRAMAT)::numeric, 2) CANT, ROUND((COALESCE(STOC.REST, 0))::numeric, 2), NG.DEN_GEST, NUM.DEN_UM
    FROM TMP_PROGRAMF1_MANEVRA PF1
    INNER JOIN COMANDA1    C1      ON  C1.CODCOMANDA1   = PF1.CODCOMANDA1
    INNER JOIN COMANDA     C       ON  C.CODCOMANDA     = C1.CODCOMANDA
    INNER JOIN PRODSDV     PSDV    ON  PSDV.CODPRODCOMP = C1.CODRETETA
    INNER JOIN NGEST       NG      ON  NG.CODGEST       = C.CODGEST
    INNER JOIN NARTOBJ     NOBJ    ON  PSDV.CODSDV      = NOBJ.CODOBIECT
    INNER JOIN NART                ON  NART.CODARTICOL  = NOBJ.CODARTICOL
    INNER JOIN NUM                 ON  NUM.CODUM        = NART.UM
    LEFT  JOIN (SELECT NS.CODOBIECT, SUM(NS.REST) REST FROM NIRSTOC NS GROUP BY NS.CODOBIECT) STOC ON  PSDV.CODSDV = STOC.CODOBIECT
    LEFT  JOIN PROGRAMFSDV PROGSDV ON  PROGSDV.CODPROGRAMF = PF1.CODPROGRAMF AND  PROGSDV.CODGEST = C.CODGEST AND  PROGSDV.CODOBIECT = PSDV.CODSDV;

    INSERT INTO TMP_PF_LOCM_GEST(SECTIE, CODGEST, CODLOCMUNCA, DISPONIBIL, NECESAR, DIFERENTE, DISPONIBILM, NECESARM, DIFERENTEM)
    WITH
    CRS_ZILE AS
    (SELECT T.CodProgramf,
            (T.vPanaLa - T.VDeLa)  + 1 - (SELECT count(zn1.data) FROM zineluc1 zn1
                                          WHERE zn1.data BETWEEN (SELECT VDELA FROM tmp_programf_manevra limit 1) AND (SELECT VpanaLA FROM tmp_programf_manevra limit 1)
                                         ) ZILE
     FROM TMP_PROGRAMF_MANEVRA T
    ),
    CRS_NECESAR AS
    (SELECT SUM(CASE WHEN  PC.CANT &lt;&gt; 1 THEN PF1.CANTPROGRAMAT / PC.CANT * COALESCE(PMAN.TPI, 0) + PF1.CANTPROGRAMAT / PMAN.BPS * PMAN.TU
                     ELSE COALESCE(PMAN.TPI, 0) + PF1.CANTPROGRAMAT / PMAN.BPS * PMAN.TU
                END ) NECESAR,
            NG.ORESCHIMB * NG.NRSCHIMBURI * ZILE.ZILE DISPONIBIL, COALESCE(PMAN.CODLOC, 0) CODLOC, COALESCE(CMD.CODGEST, 0) CODGEST
     FROM (SELECT ZILE FROM CRS_ZILE limit 1) ZILE, TMP_PROGRAMF1_MANEVRA PF1
        INNER JOIN COMANDA1   CMD1 ON  PF1.CODCOMANDA1  = CMD1.CODCOMANDA1
        INNER JOIN COMANDA    CMD  ON  CMD1.CODCOMANDA  = CMD.CODCOMANDA
        INNER JOIN PRODCOMP   PC   ON  CMD1.CODRETETA   = PC.CODPRODCOMP
        INNER JOIN CMDPRODMAN PMAN ON  PMAN.CODCOMANDA1 = CMD1.CODCOMANDA1
        INNER JOIN NGEST      NG   ON  NG.CODGEST       = CMD.CODGEST
     GROUP BY NG.ORESCHIMB, NG.NRSCHIMBURI, ZILE.ZILE, PMAN.CODLOC, CMD.CODGEST
    )
    SELECT NG.DEN_GEST SECTIE, NG.CODGEST, NECESAR.CODLOC,
           CASE WHEN  vtip &lt;&gt; 0 THEN COALESCE(NECESAR.DISPONIBIL, 0)   ELSE COALESCE(NECESAR.DISPONIBIL, 0) * 60 END  DISPONIBIL,
           CASE WHEN  vtip &lt;&gt; 0 THEN COALESCE(NECESAR.NECESAR, 0) / 60 ELSE COALESCE(NECESAR.NECESAR, 0)         END  NECESAR,
           CASE WHEN  vtip &lt;&gt; 0 THEN COALESCE(NECESAR.DISPONIBIL, 0) - COALESCE(NECESAR.NECESAR, 0) / 60
                ELSE COALESCE(NECESAR.DISPONIBIL, 0) * 60 - COALESCE(NECESAR.NECESAR, 0)
           END  DIFERENTE,
           COALESCE(NECESAR.DISPONIBIL, 0) * 60 DISPONIBILM,
           COALESCE(NECESAR.NECESAR, 0) NECESARM,
           COALESCE(NECESAR.DISPONIBIL, 0) * 60 - COALESCE(NECESAR.NECESAR, 0) DIFERENTEM
    FROM CRS_NECESAR NECESAR
    INNER JOIN NGEST NG ON  NG.CODGEST = NECESAR.CODGEST;

    INSERT INTO TMP_PF_MAN_GEST(CODOP, CODGEST, DEN_GEST, ORE, VALOARE, OREM, OPERATII)
    SELECT OP.CODOP, G.CodGEST, G.DEN_GEST,
           CASE WHEN  vtip &lt;&gt; 0 THEN round((sum(CASE WHEN  PC.CANT &lt;&gt; 1 THEN round((PF1.CANTPROGRAMAT / COALESCE(PC.CANT, 1) * COALESCE(MAN.TPI, 0) + PF1.CANTPROGRAMAT / COALESCE(MAN.BPS, 1) * COALESCE(MAN.TU, 0))::numeric, 2)
                                                     ELSE round((COALESCE(MAN.TPI, 0) + PF1.CANTPROGRAMAT * COALESCE(MAN.TU, 0))::numeric, 2)
                                                END ) / 60)::numeric, 2)
                ELSE round((sum(CASE WHEN  PC.CANT &lt;&gt; 1 THEN round((PF1.CANTPROGRAMAT / COALESCE(PC.CANT, 1) * COALESCE(MAN.TPI, 0) + PF1.CANTPROGRAMAT / COALESCE(MAN.BPS, 1) * COALESCE(MAN.TU, 0))::numeric, 2)
                                     ELSE round((COALESCE(MAN.TPI, 0) + PF1.CANTPROGRAMAT * COALESCE(MAN.TU, 0))::numeric, 2)
                                END ))::numeric, 2)
           END ,
           round((sum(CASE WHEN  PC.CANT &lt;&gt; 1 THEN round((PF1.CANTPROGRAMAT / COALESCE(PC.CANT, 1) * COALESCE(MAN.TPI, 0) + PF1.CANTPROGRAMAT / COALESCE(MAN.BPS, 1) * COALESCE(MAN.TU, 0))::numeric, 2)
                           ELSE round((COALESCE(MAN.TPI, 0) + PF1.CANTPROGRAMAT * COALESCE(MAN.TU, 0))::numeric, 2)
                      END  * T1.TARIF) / 60)::numeric, 2),
           round((sum(CASE WHEN  PC.CANT &lt;&gt; 1 THEN round((PF1.CANTPROGRAMAT / COALESCE(PC.CANT, 1) * COALESCE(MAN.TPI, 0) + PF1.CANTPROGRAMAT / COALESCE(MAN.BPS, 1) * COALESCE(MAN.TU, 0))::numeric, 2)
                           ELSE round((COALESCE(MAN.TPI, 0) + PF1.CANTPROGRAMAT * COALESCE(MAN.TU, 0))::numeric, 2)
                      END ))::numeric, 2),
           SUM(MAN.CANT)
    FROM TMP_PROGRAMF1_MANEVRA PF1
        INNER JOIN COMANDA1   C1  ON  PF1.CODCOMANDA1 = C1.CODCOMANDA1
        INNER JOIN COMANDA    C   ON  C1.CODCOMANDA   = C.CODCOMANDA
        INNER JOIN PRODCOMP   PC  ON  C1.CODRETETA    = PC.CODPRODCOMP
        INNER JOIN CMDPRODMAN MAN ON  MAN.CODCOMANDA1 = PF1.CODCOMANDA1
        INNER JOIN PRODGEST   PG  ON  PG.CODPRODGEST  = MAN.CODPRODGEST
        INNER JOIN NGEST      G   ON  C.CODGEST       = G.CODGEST
        INNER JOIN NOPER      OP  ON  OP.CODOP        = MAN.CODOP
        INNER JOIN TARIFEMAN1 T1  ON  T1.CODTARIF     = MAN.CODTARIF
    WHERE
       T1.ANSTART * 12 + T1.LUNASTART = (SELECT MAX(T2.ANSTART * 12 + T2.LUNASTART)
                                         FROM TARIFEMAN1 T2
                                         WHERE T2.CODTARIF = T1.CODTARIF AND
                                               T2.ANSTART * 12 + T2.LUNASTART &lt;= (SELECT PKG_GLOBALS_AnLunaLucru.WME_RESULT FROM PKG_GLOBALS_AnLunaLucru(NULL,NULL))
                                        )
    GROUP BY OP.CODOP, G.CODGEST, G.DEN_GEST;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_carnetdoc_i</obj_name>
  <obj_hashval>f58e1392635bd08f47f93e915966c245</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_carnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PROGRAMF.CARNETDOC_I', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_clearpf1manevra</obj_name>
  <obj_hashval>be0d2aa90571c01b87cc7748a5c5d809</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_clearpf1manevra()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM tmp_programf1_manevra;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_clearpfmanop</obj_name>
  <obj_hashval>d993e2c45cdd9fd1d4467667e2062d3c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_clearpfmanop()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM tmp_programfman_manevra;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_ct_monitor</obj_name>
  <obj_hashval>305fb55d693da85333e680343f02d77f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PROGRAMF.CT_MONITOR', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_39';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_curata_zero</obj_name>
  <obj_hashval>d68907a0eca31f2428279e4da9c084cc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_curata_zero(acodprogramf numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR v_rec IN (SELECT codprogramf1 FROM programf1 WHERE codprogramf = aCodProgramF and  CantProgramat = 0) LOOP
    DELETE FROM locurimuncaobs WHERE codprogramf1 = v_rec.codprogramf1;
    DELETE FROM programf1      WHERE codprogramf1 = v_rec.codprogramf1;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_este_sectia</obj_name>
  <obj_hashval>7b6708298df736ce28714d0f8a20caa7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_este_sectia(INOUT wme_result numeric, INOUT acodprogramf numeric, INOUT acodgest numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCount numeric;
begin
  aCount := 0;
  SELECT count(*) INTO aCount FROM programf1 WHERE codprogramf = aCodProgramF and  codgest = aCodGest;

  IF  aCount &gt; 0 THEN
    aCount := 1;
  END IF;

  WME_Result :=  aCount;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_getcarnetdoc_i</obj_name>
  <obj_hashval>4ce366baef62075e51193c633ec2f0c1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_getcarnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PROGRAMF.CARNETDOC_I', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_getct_monitor</obj_name>
  <obj_hashval>181ee8b303b94c481afef5085357b349</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PROGRAMF.CT_MONITOR', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_39';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_getdisponibil</obj_name>
  <obj_hashval>1cdeecbf90abdb9d62393a4bd8c2e80d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_getdisponibil(INOUT wme_result numeric, INOUT aoia numeric, INOUT ns numeric, INOUT ds numeric, INOUT dstart date, INOUT adstop date, INOUT aostart numeric, INOUT aostop numeric, INOUT azileneluc numeric, INOUT codgest numeric, INOUT acodloc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NRLM        numeric;
  DISPZILNIC  numeric;
  OSA         numeric;
  STOPA       numeric;
  DISPPROGRAM numeric;
  ZNELUC      numeric;
  ZLP         numeric;
  OIA         numeric;
  OSTART      numeric;
  OSTOP       numeric;
  DSTOP       date;
begin
  OIA    := aOIA;
  OSTART := aOSTART;

  IF  aOSTOP = 0 THEN
    OSTOP := 24;
    DSTOP := aDSTOP - 1;
  ELSE
    OSTOP := aOSTOP;
    DSTOP := aDSTOP;
  END IF;

  ZNELUC := (DSTOP - DSTART)  + 1 - aZILENELUC;

  SELECT COUNT(LM1.CODLOC1)
  INTO NRLM
  FROM LOCMUNCA LM
      INNER JOIN LOCMUNCA1 LM1 ON  LM.CODLOC     = LM1.CODLOC
      LEFT  JOIN MIFIX1    MF1 ON  MF1.CODMIFIX  = LM1.CODMIFIX
      LEFT  JOIN NIRSTOC   NS  ON  NS.CODNIRSTOC = MF1.CODNIRSTOC
      LEFT  JOIN NIR           ON  NIR.CODNIR    = NS.CODNIR
  WHERE  NIR.GEST = CODGEST AND  LM.CODLOC = aCODLOC
    AND  MF1.Anstart * 12 + MF1.lunastart = (SELECT max(anstart * 12 + lunastart) FROM mifix1 WHERE codmifix = LM1.codmifix);

  DISPZILNIC := NS * DS;
  STOPA      := OIA + DISPZILNIC - 24;

  IF  STOPA &gt; 0 THEN
    OSA := STOPA;
    IF  DSTOP &gt; DSTART THEN
      ZLP := DSTOP - DSTART + 1 - ZNELUC;
      IF  ZLP &gt; 0 THEN
        IF  OSTART &gt;= OIA THEN
          IF  OSTOP &gt;= OSA THEN
            IF  OSTOP &gt;= OIA THEN
              DISPPROGRAM := (DISPZILNIC * ZLP - OSTART - (24 - OSTOP)  + (OIA - OSA) )  * NRLM;
            ELSE
              DISPPROGRAM := (DISPZILNIC * ZLP - OSTART - (24 - OSTOP)  + (OIA - OSA)  + (OIA - OSTOP) )  * NRLM;
            END IF;
          ELSE
            DISPPROGRAM := (DISPZILNIC * ZLP - OSTART - (24 - OSTOP)  + 2 * (OIA - OSA) )  * NRLM;
          END IF;
        ELSE
          IF  OSTART &gt;= OSA THEN
            IF  OSTOP &gt;= OSA THEN
              IF  OSTOP &gt;= OIA THEN
                DISPPROGRAM := (DISPZILNIC * ZLP - OSA - (24 - OSTOP) )  * NRLM;
              ELSE
                DISPPROGRAM := (DISPZILNIC * ZLP - OSA - (24 - OIA) )  * NRLM;
              END IF;
            ELSE
              DISPPROGRAM := (DISPZILNIC * ZLP - OSA - (24 - OSTOP)  + (OIA - OSA) )  * NRLM;
            END IF;
          ELSE
            IF  OSTOP &gt;= OSA THEN
              IF  OSTOP &gt;= OIA THEN
                DISPPROGRAM := (DISPZILNIC * ZLP - OSTART - (24 - OSTOP) )  * NRLM;
              ELSE
                DISPPROGRAM := (DISPZILNIC * ZLP - OSTART - (24 - OIA) )  * NRLM;
              END IF;
            ELSE
              DISPPROGRAM := (DISPZILNIC * ZLP - OSTART - (24 - OSTOP)  + (OIA - OSA) )  * NRLM;
            END IF;
          END IF;
        END IF;
      ELSE
        DISPPROGRAM := 0;
      END IF;
    ELSE
      IF  OSTART &gt;= OIA THEN
        DISPPROGRAM := (OSTOP - OSTART)  * NRLM;
      ELSE
        DISPPROGRAM := (OSTOP - OIA)  * NRLM;
      END IF;
    END IF;
  ELSE
    OSA := 24 + STOPA;
    IF  DSTOP &gt; DSTART THEN
      ZLP := DSTOP - DSTART + 1 - ZNELUC;
      IF  ZLP &gt; 0 THEN
        IF  OSTART &gt;= OIA THEN
          IF  OSTART &gt;= OSA THEN
            IF  OSTOP &gt;= OSA THEN
              DISPPROGRAM := (DISPZILNIC * (ZLP - 1) )  * NRLM;
            ELSE
              IF  OSTOP &gt;= OIA THEN
                DISPPROGRAM := (DISPZILNIC * (ZLP - 1)  - (OSA - OSTOP) )  * NRLM;
              ELSE
                DISPPROGRAM := (DISPZILNIC * (ZLP - 2) )  * NRLM;
              END IF;
            END IF;
          ELSE
            IF  OSTOP &gt;= OSA THEN
              DISPPROGRAM := (DISPZILNIC * ZLP - (OSTART - OIA) )  * NRLM;
            ELSE
              IF  OSTOP &gt;= OIA THEN
                DISPPROGRAM := (DISPZILNIC * (ZLP)  - (OSTART - OIA)  - (OSA - OSTOP) )  * NRLM;
              ELSE
                DISPPROGRAM := (DISPZILNIC * (ZLP - 1)  - (OSTART - OIA) )  * NRLM;
              END IF;
            END IF;
          END IF;
        ELSE
          IF  OSTART &gt;= OSA THEN
            DISPPROGRAM := (DISPZILNIC * ZLP)  * NRLM;
          ELSE
            IF  OSTOP &gt;= OIA THEN
              DISPPROGRAM := (DISPZILNIC * ZLP - (OSA - OSTOP) )  * NRLM;
            ELSE
              DISPPROGRAM := (DISPZILNIC * (ZLP - 1) )  * NRLM;
            END IF;
          END IF;
        END IF;
      ELSE
        DISPPROGRAM := 0;
      END IF;
    ELSE
      IF  OSTART &gt;= OIA THEN
        IF  OSTART &gt;= OSA THEN
          DISPPROGRAM := 0;
        ELSE
          IF  OSTOP &gt;= OSA THEN
            DISPPROGRAM := (OSA - OSTART)  * NRLM;
          ELSE
            DISPPROGRAM := (OSTOP - OSTART)  * NRLM;
          END IF;
        END IF;
      ELSE
        IF  OSTOP &gt;= OSA THEN
          DISPPROGRAM := DISPZILNIC * NRLM;
        ELSE
          DISPPROGRAM := (DISPZILNIC - (OSA - OSTOP) )  * NRLM;
        END IF;
      END IF;
    END IF;
  END IF;

  WME_Result :=  DISPPROGRAM;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_getnrdoc_i</obj_name>
  <obj_hashval>988059029d5e00d92fdba0147b91be01</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_getnrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PROGRAMF.NRDOC_I', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_getvcodprogramf</obj_name>
  <obj_hashval>fbc0a40a7dbceac01d296aa4af509f25</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_getvcodprogramf(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PROGRAMF.vCodProgramF', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_getvdingoto</obj_name>
  <obj_hashval>12c3b286e150273183c179e77b71fb97</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_getvdingoto(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PROGRAMF.vDinGoTo', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := False;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_insertpf1manevra</obj_name>
  <obj_hashval>e6296050674337ad1f2f0b2b6237ee81</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_insertpf1manevra(vcodprogramf numeric, vcodcomanda1 numeric, vcodgest numeric, vprioritate numeric, vtermen character varying, vcantprogramat numeric, vcodcmdprodman numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO tmp_programf1_manevra(codprogramf, codcomanda1, codgest, prioritate, termenexec, cantprogramat, codcmdprodman, termen)
  VALUES(vcodprogramf, vCodComanda1, vCodGest, vPrioritate, to_date(vTermen, 'DD.MM.YYYY'), vCantProgramat, vCodCmdPRodMan, to_date(vTermen, 'DD.MM.YYYY'));
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_nrdoc_i</obj_name>
  <obj_hashval>694fa561cefcdcee4a0fecf2f5864d11</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_nrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PROGRAMF.NRDOC_I', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_setct_monitor</obj_name>
  <obj_hashval>bbd50c2b211c9c08ecf021402b5a032b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PROGRAMF.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_setdingoto</obj_name>
  <obj_hashval>71cfa47fad07f7173a04ef5341d3f08e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_setdingoto(adingoto boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PROGRAMF.vDinGoTo',(aDinGoTo)::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_setnrdoc_i</obj_name>
  <obj_hashval>d18e9523e0e23d56bb765052871a2f1a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_setnrdoc_i(anrdoc numeric, acarnet numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_PROGRAMF.CARNETDOC_I',(aCARNET)::varchar,false);
  perform set_config('PKG_PROGRAMF.NRDOC_I'    ,(aNRDOC)::varchar ,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_setvcodprogramf</obj_name>
  <obj_hashval>875bf3200f2343cac0469bb45b463c64</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_setvcodprogramf(avcodprogramf numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PROGRAMF.vCodProgramF',avCodProgramF::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_sp_deleterecord</obj_name>
  <obj_hashval>997be6fdf9f6cf4b8132b8f9c9caf1b9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC      RECORD;
  aCarnetDoc numeric;
  aNrDoc     numeric;
BEGIN
  --Florin 01.06.2023 - monitor
  --Adina 16.08.2021 - sinc.Oracle din 14.08.2021
  --Adina 09.07.2021 - sinc.Oracle din 09.07.2021
  perform pkg_programf_setct_monitor('MON_39');
  PERFORM PKG_PROGRAMF_SP_LOCKRECORD(RECID);

  SELECT CarnetDoc, NrDoc INTO aCarnetDoc, aNrDoc FROM ProgramF WHERE CodProgramF = recId;

  DELETE FROM PROGRAMFSDV WHERE CODPROGRAMF = RECID;

  FOR v_rec IN (SELECT codprogramf1 FROM programf1 WHERE codprogramf = recid) LOOP
    UPDATE intrprodlink SET codprogramf1 = NULL WHERE codprogramf1 = v_rec.codprogramf1;
    UPDATE iesprodlink  SET codprogramf1 = NULL WHERE codprogramf1 = v_rec.codprogramf1;
  END LOOP;

  DELETE FROM PROGRAMF1    WHERE CODPROGRAMF = RECID;
  DELETE FROM PROGRAMF     WHERE CODPROGRAMF = RECID;
  DELETE FROM PROGRAMFSDV  WHERE CODPROGRAMF = RECID;
  DELETE FROM PROGRAMFMAN  WHERE CODPROGRAMF = RECID;
  DELETE FROM PROGRAMFLMC  WHERE CODPROGRAMF = RECID;
  DELETE FROM PROGRAMFCONT WHERE CODPROGRAMF = RECID;
  DELETE FROM PROGRAMFGEST WHERE CODPROGRAMF = RECID;

  IF  aCarnetDoc &gt; 0 THEN
    PERFORM PKG_CARNETEDOC_RELEASENUMARDOC(ACARNETDOC, ANRDOC);
    PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE(ACARNETDOC);
  END IF;

  PERFORM NotifyModif(2, RecId, 'CODPROGRAMF');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_sp_gotorecord</obj_name>
  <obj_hashval>754ee7f2ec6d010386fff7f51ff20e1b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  V_XXX RECORD;
  ora1  date;
  ora2  date;
  vTip  numeric;
BEGIN
  --Florin 20.06.2024 - fixat 62407
  --Laura 09.11.2021 - sinc Oracle (09.11.2021)
  --Adina 16.08.2021 - sinc.Oracle din 14.08.2021
  --Adina 09.07.2021 - sinc.Oracle din 09.07.2021
  --Florin 16.11.2021 - fixat 52001
  perform pkg_programf_setct_monitor('MON_39');
  perform set_config('PKG_PROGRAMF.vDinGoTo'    ,(True)::varchar ,false);
  perform set_config('PKG_PROGRAMF.vCodProgramF',(RecId)::varchar,false);

  INSERT INTO TMP_PROGRAMF(CODPROGRAMF, DATAINREG, VDELA, VPANALA, VDELAORA, VPANALAORA, OPERAT, BLOCAT, ANULAT,
                           TIP, CODFORMATIE, SUBUNITATEA, AN, LUNA, ZILEN,
                           TIPDURATA, NRDOC, CarnetDoc, PREFIXDOC, SERIADOC,
                           ALLGEST, ALLTIPCONT)
  SELECT CODPROGRAMF, DATAINREG, VDELA, VPANALA,
         TO_char(VDELA, 'HH24:MI:SS'), TO_CHAR(VPANALA, 'HH24:MI:SS'), OPERAT, BLOCAT, ANULAT,
         TIP, CODFORMATIE, SUBUNITATEA, AN, LUNA,
         (SELECT count(zn1.data) FROM zineluc1 zn1
          WHERE zn1.data BETWEEN (SELECT VDELA FROM ProgramF WHERE CodProgramF = RecId) AND (SELECT VpanaLA FROM ProgramF WHERE CodProgramF = RecId)
         ),
         COALESCE(TIPDURATA, 0), NRDOC, CarnetDoc, PREFIXDOC, SERIADOC,
         ALLGEST, ALLTIPCONT
  FROM PROGRAMF
  WHERE CODPROGRAMF = RECID;

  SELECT to_date(to_char(vdela  , 'HH24'), 'HH24') INTO ora1 FROM programf WHERE codprogramf = recid;
  SELECT to_date(to_char(vpanala, 'HH24'), 'HH24') INTO ora2 FROM programf WHERE codprogramf = recid;
  SELECT tipdurata INTO vTip FROM tmp_programf;

  INSERT INTO TMP_PROGRAMF1(CODPROGRAMF1,CODPROGRAMF,CODCOMANDA1,CODGEST,DATASTART, PRIORITATE,TERMEN,CANTPROGRAMAT,
                            DEN_GEST,NRCMD,DEN_OBIECT,CODEXTERN,UM, TERMENEXEC,DEN_CLIENT,TERMENLIVR,CODOBIECT,
                            CODCOMANDA, DURATA, DURATAM, SCHIMB, CODFORMATIE, DEN_FORMATIE, D1, D2, D3, LANSAT,
                            CANTRETETA, DURATARETETA, TERMENCMDINT,SAPTAMANA,NRCMDCLI,OBSCMDINT,OBSCMDCLI)
  SELECT PF1.CODPROGRAMF1, PF1.CODPROGRAMF, PF1.CODCOMANDA1, PF1.CODGEST, G.DSTART, G.PRIORITATE,
         PF1.TERMEN, PF1.CANTPROGRAMAT, NG.DEN_GEST, ROUND((C.NRDOC + c1.indexlocal / 1000)::numeric, 3), NOBJ.DENUMIRE,
         NOBJ.CODEXTERN, NUM1.DEN_UM1, COALESCE(PF1.TERMEN, C1.TERMEN),
           CASE WHEN CCLIENT.TIPDOC = 44 THEN SS.DEN_SUBUNIT ELSE NP.DEN_PART END, c1client.termen, NOBJ.CODOBIECT, C.CODCOMANDA,
           Round((PF1.CANTPROGRAMAT/PC.CANT * PC.DURATA/60)::numeric, 3) ,
           PF1.CANTPROGRAMAT / PC.CANT * PC.DURATA, PF1.schimb, pf1.codformatie, F.Den_Formatie, C1.D1, C1.D2, C1.D3, C1.Cantacceptat,
           CASE WHEN  COALESCE(PC.CANT, 0)=0 THEN 1 ELSE  COALESCE(PC.CANT, 0) END ,
           PC.DURATA, C1.TERMEN, TO_CHAR(COALESCE(PF1.TERMEN, C1.TERMEN), 'IW')::numeric,Round((CCLIENT.NRDOC + C1CLIENT.indexlocal / 1000)::numeric, 3),
           C1.OBS, C1CLIENT.OBS
  FROM PROGRAMF1 PF1
      INNER JOIN PROGRAMF PF       ON  PF1.CODPROGRAMF      = PF.CODPROGRAMF
      INNER JOIN NGEST    NG       ON  NG.CODGEST           = PF1.CODGEST
      INNER JOIN COMANDA1 C1       ON  C1.CODCOMANDA1       = PF1.CODCOMANDA1
      INNER JOIN PRODCOMP PC       ON  C1.CODRETETA         = PC.CODPRODCOMP
      INNER JOIN COMANDA  C        ON  C.CODCOMANDA         = C1.CODCOMANDA
      INNER JOIN NARTOBJ  NOBJ     ON  NOBJ.CODOBIECT       = C1.CODOBIECT
      INNER JOIN NUM1              ON  NUM1.CODUM1          = C1.UMSEC
      LEFT  JOIN (Select CodComanda1, CODCMDPRODMAN from CMDPRODMAN where NROP = 1) PM ON PM.CODCOMANDA1 = C1.CODCOMANDA1
        LEFT  JOIN GANTT    G        ON G.CODCMDPRODMAN       = PM.CODCMDPRODMAN
      LEFT  JOIN FORMATII F        ON  PF1.Codformatie      = F.CodFormatie
      LEFT  JOIN CMDLINK  CLINK    ON  CLINK.CODCOMANDA1    = C1.CODCOMANDA1
      LEFT  JOIN COMANDA1 C1CLIENT ON  C1CLIENT.CODCOMANDA1 = CLINK.CODLINIECOMANDA
      LEFT  JOIN COMANDA  CCLIENT  ON  CCLIENT.CODCOMANDA   = C1CLIENT.CODCOMANDA
      LEFT  JOIN NSUBUNIT SS        ON  SS.CODSUBUNIT       = CCLIENT.SUBUNITSURSA
      LEFT  JOIN NPART    NP       ON  NP.CODPART           = CCLIENT.PARTENER
  WHERE PF1.CODPROGRAMF = RECID;

  UPDATE tmp_programf pf
  SET
  durata = (SELECT sum(pf1.DURATA) FROM tmp_programf1 pf1 WHERE pf.codprogramf = pf1.codprogramf);

  -- populez manevra
  DELETE FROM TMP_PROGRAMF_MANEVRA;
  INSERT INTO TMP_PROGRAMF_MANEVRA(CODPROGRAMF, DATAINREG, VDELA, VPANALA, VDELAORA, VPANALAORA, OPERAT, BLOCAT, ANULAT, TIP, CODFORMATIE, SUBUNITATEA, AN, LUNA, TIPDURATA, ALLGEST, ALLTIPCONT)
  SELECT CODPROGRAMF, DATAINREG, TO_DATE(to_CHAR(VDELA, 'dd.mm.yyyy'), 'DD.MM.YYYY'), TO_DATE(to_CHAR(VPANALA, 'dd.mm.yyyy'), 'DD.MM.YYYY'),
         TO_char(VDELA, 'HH24:MI:SS'), TO_CHAR(VPANALA, 'HH24:MI:SS'), OPERAT, BLOCAT, ANULAT, TIP, CODFORMATIE, SUBUNITATEA, AN, LUNA, TIPDURATA, ALLGEST, ALLTIPCONT
  FROM PROGRAMF WHERE CODPROGRAMF = RECID;

  DELETE FROM TMP_PROGRAMF1_MANEVRA;
  INSERT INTO TMP_PROGRAMF1_MANEVRA(CODPROGRAMF1, CODPROGRAMF, CODCOMANDA1, CODGEST, PRIORITATE, CANTPROGRAMAT, DURATARETETA, TERMENEXEC, DATASTART, DEN_GEST, NRCMD, DEN_OBIECT, CODEXTERN, UM, DEN_CLIENT, CODOBIECT, CODCOMANDA, DURATA, DURATAM, D1, D2, D3, CANTRETETA)
  SELECT PF1.CODPROGRAMF1, PF1.CODPROGRAMF, PF1.CODCOMANDA1, PF1.CODGEST, PF1.PRIORITATE, PF1.CANTPROGRAMAT, PC.DURATA, MAX(PF1.TERMENEXEC), PF1.DATASTART, PF1.DEN_GEST,
         PF1.NRCMD, PF1.DEN_OBIECT, PF1.CODEXTERN, PF1.UM, PF1.DEN_CLIENT, PF1.CODOBIECT, PF1.CODCOMANDA, PF1.DURATA, PF1.DURATAM, PF1.D1, PF1.D2, PF1.D3, PC.CANT
  FROM TMP_PROGRAMF1 PF1
  INNER JOIN COMANDA1 C1 ON  C1.CODCOMANDA1 = PF1.CODCOMANDA1
  INNER JOIN PRODCOMP PC ON  C1.CODRETETA   = PC.CODPRODCOMP
  GROUP BY PF1.CODPROGRAMF1, PF1.CODPROGRAMF, PF1.CODCOMANDA1, PF1.CODGEST, PF1.PRIORITATE, PF1.CANTPROGRAMAT, PC.DURATA, PF1.DATASTART, PF1.DEN_GEST, PF1.NRCMD, PF1.DEN_OBIECT, PF1.CODEXTERN, PF1.UM, PF1.DEN_CLIENT, PF1.CODOBIECT, PF1.CODCOMANDA, PF1.DURATA, PF1.DURATAM, PF1.D1, PF1.D2, PF1.D3, PC.CANT;

  INSERT INTO TMP_LOCURIMUNCAOBS(IDOBS, CODPROGRAMF1, CODLOCMUNCA, OBS)
  SELECT IDOBS, CODPROGRAMF1, CODLOCMUNCA, OBS
  FROM LOCURIMUNCAOBS
  WHERE EXISTS (SELECT TMP.CODPROGRAMF1 FROM TMP_PROGRAMF1 TMP WHERE TMP.CODPROGRAMF1 = CODPROGRAMF1);

  INSERT INTO TMP_PROGRAMFMAN(CODPFMAN, CODPROGRAMF, CODCMDPRODMAN, CANT)
  SELECT CODPFMAN, CODPROGRAMF, CODCMDPRODMAN, CANT FROM PROGRAMFMAN;
  INSERT INTO TMP_PROGRAMFMAN_MANEVRA(CODPFMAN,CODPROGRAMF,CODCMDPRODMAN,CANT)
  SELECT CODPFMAN, CODPROGRAMF, CODCMDPRODMAN, CANT FROM PROGRAMFMAN;

  INSERT INTO TMP_PROGRAMFGEST(CODPROGRAMF, CODGEST)
  SELECT CODPROGRAMF, CODGEST FROM PROGRAMFGEST WHERE CODPROGRAMF = RECID;

  INSERT INTO TMP_PROGRAMFCONT(CODPROGRAMF, CODIOART)
  SELECT CODPROGRAMF, CODIOART FROM PROGRAMFCONT WHERE CODPROGRAMF = RECID;

  DELETE FROM tmp_manevra_liste WHERE filtru = 'CODGEST' OR  FILTRU = 'CODIOART';
  INSERT INTO TMP_MANEVRA_LISTE(FILTRU, VALOARE)
  SELECT 'CODGEST', CODGEST FROM TMP_PROGRAMFGEST;

  INSERT INTO TMP_MANEVRA_LISTE(FILTRU, VALOARE)
  SELECT 'CODIOART', CODIOART FROM TMP_PROGRAMFCONT;

  PERFORM PKG_PROGRAMF_CALCUL_DETALII(to_char(ora1, 'HH24'), to_char(ora2, 'HH24'), 0);

  FOR v_rec IN (SELECT CODLMC, codprogramf, codgest, codloc, codcomanda1, codop FROM TMP_PF_LOCM_CMD) LOOP
    FOR v_xxx IN (SELECT pflmc.dataprogramare FROM programflmc pflmc
                  WHERE pflmc.codprogramf = v_rec.codprogramf and  pflmc.codgest = v_rec.codgest
                   and  pflmc.codloc = v_rec.codloc and  pflmc.codcomanda1 = v_rec.codcomanda1 AND  pflmc.CODOP = v_rec.CODOP
                 )
    LOOP
      UPDATE TMP_PF_LOCM_CMD SET dataprogramare = v_xxx.dataprogramare WHERE codlmc = v_rec.codlmc;
      EXIT ;
    END LOOP;
  END LOOP;

  perform set_config('PKG_PROGRAMF.vDinGoTo',(False)::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_sp_insertrecord</obj_name>
  <obj_hashval>100f20f09d49698ed1c9620a0138876e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_PROGRAMF(CODPROGRAMF) VALUES(0);

  DELETE FROM TMP_PF_MAT_CMD;
  DELETE FROM TMP_PF_SDV_CMD;
  DELETE FROM TMP_PF_LOCM_CMD;
  DELETE FROM TMP_PF_MAN_CMD;
  DELETE FROM TMP_PF_MAT_GEST;
  DELETE FROM TMP_PF_SDV_GEST;
  DELETE FROM TMP_PF_LOCM_GEST;
  DELETE FROM TMP_PF_MAN_GEST;
  DELETE FROM TMP_PF_MAT;
  DELETE FROM TMP_PF_SDV;
  DELETE FROM TMP_PF_LOCM;
  DELETE FROM TMP_PROGRAMF1_MANEVRA;
  --DELETE FROM TMP_PROGRAMF1C;
  DELETE FROM TMP_PF_MAN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_update_stocuri</obj_name>
  <obj_hashval>61adb1986b9b9c69100362d68dd67743</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_update_stocuri(allgest numeric, alltipcont numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  UPDATE TMP_PF_MAT MAT
  SET
    STOCDISP = COALESCE ( (SELECT SUM (NS.REST)
                           FROM NIRSTOC NS
                             INNER JOIN NIR      ON NIR.CODNIR = NS.CODNIR
                             INNER JOIN NGEST NG ON NIR.GEST   = NG.CODGEST
                           WHERE
                             NS.REST &gt; 0
                             AND NG.CODSUBUNIT = current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric
                             AND NS.CODOBIECT  = MAT.CODOBIECT
                             AND ( (ALLGEST = 1)
                                    OR
                                   (EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODGEST' AND VALOARE::numeric = NIR.GEST))
                                 )
                             AND ( (ALLTIPCONT = 1)
                                    OR
                                   (EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODIOART' AND VALOARE::numeric = NS.CODIOART)))) , 0),
    ALTEREZ = COALESCE ( (SELECT SUM (R.REST)
                          FROM REZERVATS       R
                            INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = R.CODNIRSTOC
                            INNER JOIN NIR        ON NIR.CODNIR    = NS.CODNIR
                            INNER JOIN NGEST   NG ON NIR.GEST      = NG.CODGEST
                          WHERE
                            NG.CODSUBUNIT = current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric
                            AND NS.CODOBIECT = MAT.CODOBIECT
                            AND ( (ALLGEST = 1)
                                   OR
                                  (EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODGEST' AND VALOARE::numeric = NIR.GEST))
                                )
                            AND ( (ALLTIPCONT = 1)
                                   OR
                                  (EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODIOART' AND VALOARE::numeric = NS.CODIOART)))) , 0);

  UPDATE TMP_PF_MAT_GEST MAT
  SET STOCDISP = COALESCE ( (SELECT SUM (NS.REST)
                             FROM NIRSTOC NS
                               INNER JOIN NIR      ON NIR.CODNIR = NS.CODNIR
                               INNER JOIN NGEST NG ON NIR.GEST   = NG.CODGEST
                             WHERE
                               REST &gt; 0
                               AND NG.CODSUBUNIT = current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric
                               AND NS.CODOBIECT  = MAT.CODOBIECT
                               AND ( (ALLGEST = 1)
                                      OR
                                     (EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODGEST' AND VALOARE::numeric = NIR.GEST))
                                   )
                               AND ( (ALLTIPCONT = 1)
                                      OR
                                     (EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODIOART' AND VALOARE::numeric = NS.CODIOART)))) , 0);

end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_updatepf</obj_name>
  <obj_hashval>08da0fd9a837f66f3f0d4f5a9e299482</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_updatepf(acodprogramf numeric, acodcomanda1 numeric, acant numeric, atermen character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodProgramF1 numeric;
  aCodGest      numeric;
begin
  BEGIN
    SELECT codprogramf1 INTO aCodProgramF1
    FROM programf1
    WHERE codprogramf = aCodProgramF and  termen = to_date(aTermen, 'dd.mm.yyyy') and  codcomanda1 = aCodComanda1;
  EXCEPTION WHEN others THEN
    aCodProgramF1 := 0;
  END;

  SELECT c.codgest INTO aCodGest
  FROM comanda c INNER JOIN comanda1 c1 ON  c.codcomanda = c1.codcomanda
  WHERE c1.codcomanda1 = aCodComanda1;

  IF  aCodProgramF1 &gt; 0 THEN
    UPDATE programf1 SET CANTPROGRAMAT = CANTPROGRAMAT + aCant WHERE codprogramf1 = aCodProgramF1;
  ELSE
    SELECT NEXTVAL('SEQ_PROGRAMF1_CODPROGRAMF1') INTO aCodProgramF1;

    INSERT INTO programf1(codprogramf1, codprogramf, codcomanda1, codgest, termen, cantprogramat)
    VALUES(aCodProgramF1, aCodProgramF, aCodComanda1, aCodGest, to_date(aTermen, 'dd.mm.yyyy'), aCant);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_updatepfmanevra</obj_name>
  <obj_hashval>eee2f52f59cac98e221910b15833e27f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_updatepfmanevra(ddela character varying, dpanala character varying, odela character varying, opanala character varying, dcodprogramf numeric, vallgest numeric, valltipcont numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 16.08.2021 - sinc.Oracle din 14.08.2021
  DELETE FROM tmp_programf_manevra;
  INSERT INTO tmp_programf_manevra(codprogramf, vdela, vpanala, vdelaora, vpanalaora, tipdurata, AllGest, AllTipCont)
  VALUES(dCodProgramf, to_date(dDela, 'DD.MM.YYYY'), to_date(dPanaLa, 'DD.MM.YYYY'), to_date(oDeLa, 'HH24'), to_date(oPanaLa, 'HH24'), 0, vAllGest, vAllTipCont);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_updatetermenpf</obj_name>
  <obj_hashval>3629ef2d087982e36753fd2f3f42f3d9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_updatetermenpf(INOUT wme_result numeric, INOUT acodprogramf1 numeric, INOUT atermen character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodProgramF numeric;
  aRez         numeric;
begin
  aRez := 1;
  BEGIN
    SELECT codprogramf INTO aCodProgramF FROM programf1 WHERE codprogramf1 = aCodProgramF1;
  EXCEPTION WHEN others THEN
    aRez := 0;
  END;

  IF  aRez = 0 THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  BEGIN
    PERFORM pkg_programf_SP_LOCKRECORD(aCodProgramF);
  EXCEPTION WHEN others THEN
    aRez := 0;
  END;

  IF  aRez = 0 THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  BEGIN
    UPDATE programf1 SET termen = to_date(aTermen, 'dd.mm.yyyy') WHERE codprogramf1 = aCodProgramF1;
  EXCEPTION WHEN others THEN
    aRez := 0;
  END;

  WME_Result :=  aRez;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_vcodprogramf</obj_name>
  <obj_hashval>c5a4baa2cfb22e965575c0b3428bfd4a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_vcodprogramf(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PROGRAMF.vCodProgramF', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_vdingoto</obj_name>
  <obj_hashval>79cded75c146e1ff301784123774b08a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_vdingoto(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PROGRAMF.vDinGoTo', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := False;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_bagaproiectnoddinreteta</obj_name>
  <obj_hashval>aabbf7b6092903c10b65bdef37214b96</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_bagaproiectnoddinreteta(acodproiect numeric, acodprodcomp numeric, acant numeric, aindexparinte character varying, anodoriginal numeric, anivel numeric, negeneric numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC          RECORD;
  Nivel          numeric;
  RetetaGenerica numeric;
  vCodNod        numeric;
BEGIN
  --Florin 28.03.2022 - sinc. Oracle
  --Adina 28.06.2021 - sinc.Oracle din 25.06.2021
  --Florin 18.02.2021 - fixat 42084
  Nivel := aNivel + 1;

  FOR v_rec IN (SELECT mat.*, pc.cant CANTRETETA, ROW_NUMBER() OVER() LVL
                FROM prodmat mat INNER JOIN prodcomp pc ON  pc.codprodcomp = mat.codprodcomp
                WHERE pc.codprodcomp = aCodProdComp
                ORDER BY mat.codmat
               )
  LOOP
    IF NeGeneric &gt; 0 THEN
      RetetaGenerica := v_rec.codreteta;
    ELSE
      RetetaGenerica := (SELECT pkg_prodcomp_GetRetetaGenerica.WME_RESULT FROM pkg_prodcomp_GetRetetaGenerica(NULL,v_rec.codobiect));
    END IF;
    if not v_rec.tip in (1,2) then RetetaGenerica := 0; end if;
    SELECT NEXTVAL('SEQ_PROIECTNOD_CODPROIECTNOD') INTO vCodNod;

    IF  v_rec.lvl &lt; 10 THEN
      INSERT INTO proiectnod(codproiectnod, codproiect, cant, nodoriginal, pozitie, codreteta, tip, codobiect, indexparinte, codprodmat, nivel)
      VALUES(vCodNod, aCodProiect, v_rec.cant / v_rec.cantreteta * aCant, aNodOriginal, v_rec.lvl, RetetaGenerica, v_Rec.tip, v_rec.codobiect, coalesce(aIndexParinte,'') || '.' || '0' || coalesce((v_rec.lvl)::varchar,''), v_rec.codmat, Nivel);
    ELSE
      INSERT INTO proiectnod(codproiectnod, codproiect, cant, nodoriginal, pozitie, codreteta, tip, codobiect, indexparinte, codprodmat, nivel)
      VALUES(vCodNod, aCodProiect, v_rec.cant / v_rec.cantreteta * aCant, aNodOriginal, v_rec.lvl, RetetaGenerica, v_Rec.tip, v_rec.codobiect, coalesce(aIndexParinte,'') || '.' || coalesce((v_rec.lvl)::varchar,''), v_rec.codmat, Nivel);
    END IF;

    IF  v_rec.tip &lt; 3 THEN
      IF  RetetaGenerica &gt; 0 THEN
         IF  v_rec.lvl &lt; 10 THEN
          PERFORM PKG_PROIECT_BagaProiectNodDinReteta(aCodProiect, RetetaGenerica, v_rec.cant / v_rec.cantreteta * aCant, coalesce(aIndexParinte,'') || '.' || '0' || coalesce((v_rec.lvl)::varchar,''), vCodNod, Nivel);
        ELSE
          PERFORM PKG_PROIECT_BagaProiectNodDinReteta(aCodProiect, RetetaGenerica, v_rec.cant / v_rec.cantreteta * aCant, coalesce(aIndexParinte,'') || '.' || coalesce((v_rec.lvl)::varchar,''), vCodNod, Nivel);
        END IF;
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_bagaproiectnoddinretetax</obj_name>
  <obj_hashval>b5e7caa426a37f749d9a5a191a99a8e8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_bagaproiectnoddinretetax(acodproiect numeric, acodprodcomp numeric, acant numeric, aindexparinte character varying, anodoriginal numeric, anivel numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC          RECORD;
  Poz            numeric;
  Nivel          numeric;
  vIndexParinte  varchar;
  vIndex         varchar;
  RetetaGenerica numeric;
  vCodNod        numeric;
begin
  Nivel         := aNivel + 1;
  Poz           := 0;
  vIndexParinte := '';

  IF  Length(aIndexParinte) &gt; 0 THEN
    vIndexparinte := coalesce(aIndexParinte,'') || '.';
  END IF;

  FOR v_rec IN (SELECT mat.*, pc.cant CANTRETETA
                FROM prodmat mat INNER JOIN prodcomp pc ON  pc.codprodcomp = mat.codprodcomp
                WHERE pc.codprodcomp = aCodProdComp
               )
  LOOP
    Poz := Poz + 1;
    IF  Poz &lt; 10 THEN
      vIndex := coalesce(vIndexParinte,'') || '0' || coalesce((Poz)::varchar,'');
    ELSE
      vIndex := coalesce(vIndexParinte,'') || coalesce((Poz)::varchar,'');
    END IF;

    BEGIN
      SELECT Valoare1::NUMERIC INTO RetetaGenerica FROM tmp_manevra_liste WHERE filtru = 'CODOBIECT' AND  FILTRU1 = 'CODPRODCOMP' AND  VALOARE = V_REC.CODOBIECT;
    EXCEPTION WHEN others THEN
      RetetaGenerica := 0;
    END;

    SELECT NEXTVAL('SEQ_PROIECTNOD_CODPROIECTNOD') INTO vCodNod;

    INSERT INTO tmp_proiectnod(codproiectnod, codproiect, cant, nodoriginal, pozitie, codreteta, tip, codobiect, indexparinte, codprodmat, nivel)
    VALUES(vCodNod, aCodProiect, v_rec.cant / v_rec.cantreteta * aCant, aNodOriginal, Poz, RetetaGenerica, v_Rec.tip, v_rec.codobiect, vIndexParinte, v_rec.codmat, Nivel);

    IF  v_rec.tip &lt; 3 THEN
      IF  RetetaGenerica &gt; 0 THEN
        PERFORM PKG_PROIECT_BagaProiectNodDinReteta(aCodProiect, RetetaGenerica, v_rec.cant / v_rec.cantreteta * aCant, vIndexParinte, vCodNod, Nivel);
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_checkandupdateretete</obj_name>
  <obj_hashval>d74dd46c0d94e44919eb473dbf97241e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_checkandupdateretete(acodproiect numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  V_MAT        RECORD;
  V_PN         RECORD;
  aCount       numeric;
  aModif       numeric;
  aCodProdComp numeric;
begin
  FOR v_rec IN (SELECT pn.codproiectnod, pn.cant, pc.cant CANTRETETA, pn.codreteta
                FROM proiectnod pn INNER JOIN prodcomp pc ON  pn.codreteta = pc.codprodcomp
                WHERE pn.codreteta &gt; 0 and  pn.codproiect = aCodProiect
               )
  LOOP
    aCount := 0;
    aModif := 0;

    FOR v_mat IN (SELECT pn.cant, mat.cant CANTMAT
                  FROM proiectnod pn INNER JOIN prodmat mat ON  pn.codprodmat = mat.codmat
                  WHERE pn.codproiect = aCodProiect and  pn.nodoriginal = v_rec.codproiectnod
                 )
    LOOP
      IF  v_mat.cant &lt;&gt; round((v_rec.cant * v_mat.cantmat / v_rec.cantreteta)::numeric, 7) THEN
        aModif := aModif + 1;
        SELECT count(*) INTO aCount FROM proiectnod WHERE codreteta = v_rec.codreteta and  codproiect &lt;&gt; aCodProiect;
      END IF;

      IF  aCount &gt; 0 THEN
        EXIT ;
      END IF;
    END LOOP;

    IF  aCount &gt; 0 THEN
      aCodProdComp := (SELECT pkg_prodcomp_CloneazaReteta.WME_RESULT FROM pkg_prodcomp_CloneazaReteta(NULL,v_rec.codreteta));

      UPDATE prodcomp   SET generic = 0, implicit = 0 WHERE codprodcomp = aCodProdComp;
      UPDATE proiectnod SET codreteta = aCodProdComp  WHERE codproiectnod = v_rec.codproiectnod;

      FOR v_pn IN (SELECT pn.codproiectnod, matc.codmat
                   FROM proiectnod pn
                   INNER JOIN prodmat mat  ON  pn.codprodmat  = mat.codmat    and  mat.codprodcomp = v_rec.codreteta
                   INNER JOIN prodmat matc ON  matc.codobiect = mat.codobiect and  matc.indexlocal = mat.indexlocal and  matc.cant = mat.cant
                   WHERE pn.nodoriginal = v_rec.codproiectnod and  pn.codproiect = aCodProiect and  matc.codprodcomp = aCodProdComp
                  )
      LOOP
        UPDATE proiectnod SET codprodmat = v_pn.codmat WHERE codproiectnod = v_pn.codproiectnod;
      END LOOP;
    END IF;

    FOR v_mat IN (SELECT pn.cant, mat.cant CANTMAT, mat.codmat
                  FROM proiectnod pn INNER JOIN prodmat mat ON  pn.codprodmat = mat.codmat
                   WHERE pn.codproiect = aCodProiect and  pn.nodoriginal = v_rec.codproiectnod
                 )
    LOOP
      IF  v_mat.cant &lt;&gt; round((v_rec.cant * v_mat.cantmat / v_rec.cantreteta)::numeric, 7) THEN
        UPDATE prodmat SET cant = round((v_mat.cant * v_rec.cantreteta / v_rec.cant)::numeric, 7) WHERE codmat = v_mat.codmat;
      END IF;
    END LOOP;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_checkextprj</obj_name>
  <obj_hashval>b780de1038d56f1029e50ea47cc68897</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_checkextprj(acodproiect numeric, acodproiecti numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodProiectExt  numeric;
  aCodProiectExtI numeric;
BEGIN
  --Florin 12.03.2021/18.03.2021 - fixat 44851
  BEGIN
    EXECUTE 'select coalesce(codproiectext,0) from proiectext where codproiect = ' || coalesce(aCodProiect::varchar ,'') INTO aCodProiectExt;
    EXCEPTION WHEN others THEN
      aCodProiectExt := 0;
  END;

  BEGIN
    EXECUTE 'select coalesce(codproiectext,0) from proiectext where codproiect = ' || coalesce(aCodProiectI::varchar ,'') INTO aCodProiectExtI;
    EXCEPTION WHEN others THEN
      aCodProiectExtI := 0;
  END;

  PERFORM PKG_PROIECT_CheckTmpExt();

  IF aCodProiectExt &gt; 0 THEN
      IF COALESCE(aCodProiectExtI, 0) = 0 THEN
        EXECUTE 'DELETE FROM TMP_PROIECTEXT';
        EXECUTE 'INSERT INTO TMP_PROIECTEXT SELECT * FROM PROIECTEXT WHERE CODPROIECTEXT = ' || coalesce(aCODPROIECTEXT::varchar ,'');
        EXECUTE 'UPDATE TMP_PROIECTEXT SET CODPROIECT = ' || coalesce(aCODPROIECTI::varchar ,'') || ', CODPROIECTEXT = NEXTVAL(''SEQ_PROIECTEXT_CODPROIECTEXT'')';
        EXECUTE 'INSERT INTO PROIECTEXT SELECT * FROM TMP_PROIECTEXT';
        EXECUTE 'DELETE FROM TMP_PROIECTEXT';
      ELSE
        EXECUTE 'DELETE FROM PROIECTEXT WHERE CODPROIECTEXT = ' || coalesce(aCodProiectExtI::varchar ,'');
        EXECUTE 'DELETE FROM TMP_PROIECTEXT';
        EXECUTE 'INSERT INTO TMP_PROIECTEXT SELECT * FROM PROIECTEXT WHERE CODPROIECTEXT = ' || coalesce(aCODPROIECTEXT::varchar ,'');
        EXECUTE 'UPDATE TMP_PROIECTEXT SET CODPROIECT = ' || coalesce(aCODPROIECTI::varchar ,'') || ', CODPROIECTEXT = NEXTVAL(''SEQ_PROIECTEXT_CODPROIECTEXT'')';
        EXECUTE 'INSERT INTO PROIECTEXT SELECT * FROM TMP_PROIECTEXT';
        EXECUTE 'DELETE FROM TMP_PROIECTEXT';
      END IF;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_checkmodificari</obj_name>
  <obj_hashval>e75be872896ff1f59c9907f121e1da98</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_checkmodificari(acodproiect numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
declare
  aCount numeric;
begin
  --Bogdan 28.11.2020
  SELECT count(*)
  into aCount
  FROM proiect p INNER JOIN tmp_proiect tmp ON tmp.codproiect = p.codproiect
  WHERE p.codproiect = aCodProiect and p.codobiectprod &lt;&gt; tmp.codobiectprod;

  IF aCount &gt; 0 THEN
    RETURN aCount;
  END IF;

  SELECT count(*)
  INTO aCount
  FROM tmp_proiectnod
  WHERE codproiect = aCodProiect and codproiectnod &lt;= 0;

  IF aCount &gt; 0 THEN
    RETURN aCount;
  END IF;

  SELECT count(*)
  INTO aCount
  FROM proiectnod pn LEFT JOIN tmp_proiectnod tmp ON pn.codproiectnod = tmp.codproiectnod
  WHERE
    pn.codproiect = aCodProiect
    and (pn.cant &lt;&gt; tmp.cant
      or COALESCE (pn.codreteta, 0) &lt;&gt; COALESCE (tmp.codreteta, 0)
      or tmp.codproiectnod IS NULL);

  RETURN aCount;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_checktmpext</obj_name>
  <obj_hashval>35458926f594d548ddbe975941239605</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_checktmpext()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  NR    numeric;
  NR1   numeric;
  SIR   varchar;
  DT    varchar;
  VG    varchar;
  sFIRMANAME   varchar;
BEGIN
  --Stef   24.03.2022 - CREATE TEMPORARY (scosGLOBAL fiindca e obsolete si apare/incurca in loguri de BD)
  --Adina 02.06.2021 - scos upper; add sFIRMANAME
  --Bogdan 13.10.2020
  sFIRMANAME := lower(current_setting('PKG_GLOBALS.FIRMANAME', true));

  IF (fnc_TmpExists ('TMP_PROIECTEXT')) = 1 THEN
    SELECT COUNT(*)
    INTO NR1
    FROM information_schema.Columns
    WHERE Table_Name = 'proiectext' and TABLE_SCHEMA = sFIRMANAME;

    SELECT COUNT(*)
    INTO NR
    FROM information_schema.Columns
    WHERE Table_Name = 'tmp_proiectext';

    IF NR1 &lt;&gt; NR THEN
      EXECUTE 'DROP TABLE TMP_PROIECTEXT';
    END IF;
    SELECT COUNT(*) INTO NR FROM pg_statio_all_sequences WHERE relname = 'SEQ_PROIECTEXT_CODPROIECTEXT' AND schemaname = sFIRMANAME;
      IF NR = 0 then
        PERFORM PKG_REMAKE_SEQUENCES_REMAKE_SEQUENCE('PROIECTEXT', 'CODPROIECTEXT', 'SEQ_PROIECTEXT_CODPROIECTEXT');
      END IF;
  END IF;

  IF (fnc_TmpExists ('TMP_PROIECTEXT')) = 0 THEN
    Sir := 'CREATE TEMPORARY TABLE TMP_PROIECTEXT(';
    SELECT COUNT(*)
    INTO NR
    FROM information_schema.Columns
    WHERE Table_Name = 'proiectext' and TABLE_SCHEMA = sFIRMANAME;

    FOR V_REC IN (SELECT * FROM information_schema.Columns
                  WHERE Table_Name = 'proiectext' and TABLE_SCHEMA = sFIRMANAME
                  ORDER BY ORDINAL_POSITION)
    LOOP
      IF V_REC.DATA_TYPE ='character varying' THEN
        DT := ' VARCHAR(' || coalesce (V_REC.CHARACTER_MAXIMUM_LENGTH,'') || ') ';
      ELSE
        IF V_REC.DATA_TYPE = 'date' THEN
          DT := ' DATE ';
        ELSE
          DT := ' NUMERIC(' || coalesce (V_REC.NUMERIC_PRECISION,'') || ',' || coalesce (V_REC.NUMERIC_SCALE,'') || ') ';
        END IF;
      END IF;

      IF V_REC.ORDINAL_POSITION &lt; NR THEN
        VG := ', ';
      ELSE
        VG := '';
      END IF;

      DT  := coalesce (DT,'') || coalesce (VG,'');
      SIR := coalesce (SIR,'') || ' ' || coalesce (V_REC.COLUMN_NAME,'') || ' ' || coalesce (DT,'');
    END LOOP;

    SIR := coalesce (SIR,'') || ' ) ON COMMIT PRESERVE ROWS';
    EXECUTE SIR;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_cloneazaprjascunse</obj_name>
  <obj_hashval>38983ba4bf2a9fbffc2cd0bc4d4546de</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_cloneazaprjascunse()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC          RECORD;
  aNewCodProiect numeric;
begin
  PERFORM PKG_REMAKE_SEQUENCES_REMAKE_ALL_SEQUENCES(NULL,NULL);

  FOR v_rec IN (SELECT codproiect FROM proiect WHERE COALESCE(ascuns, 0) = 0 and  COALESCE(codutilizare, 0) = 0 and  codproiect &gt; 0) LOOP
    aNewCodProiect := 0;
    DELETE FROM tmp_proiect;
    DELETE FROM tmp_proiectnod;
    DELETE FROM tmp_proiectman;
    DELETE FROM tmp_proiectgrid;
    PERFORM PKG_PROIECT_SP_GOTORECORD(v_rec.CodProiect);

    UPDATE tmp_proiectnod SET codproiectnod = -codproiectnod;
    UPDATE tmp_proiectnod SET nodoriginal = -nodoriginal WHERE nodoriginal &gt; 0;

    PERFORM PKG_PROIECT_SP_POSTRECORDS(1, aNewCodProiect);

    UPDATE proiect
    SET
    ascuns          = 1,
    generic         = 0,
    implicit        = 0,
    codidentificare = aNewCodProiect
    WHERE codproiect = v_rec.codproiect;

    UPDATE proiect SET codutilizare = v_rec.codproiect WHERE codproiect = aNewCodProiect;

    IF  (fnc_TmpExists('PROIECTEXT')) = 1 THEN
      BEGIN
        PERFORM PKG_PROIECT_CheckTmpExt();
        EXECUTE 'DELETE FROM TMP_PROIECTEXT';
        EXECUTE 'INSERT INTO TMP_PROIECTEXT SELECT * FROM PROIECTEXT WHERE CODPROIECT = ' || coalesce(V_REC.CODPROIECT::varchar ,'');
        EXECUTE 'UPDATE TMP_PROIECTEXT SET CODPROIECT = ' || coalesce(ANEWCODPROIECT::varchar ,'') || ', CODPROIECTEXT = SEQ_PROIECTEXT_CODPROIECTEXT.NEXTVAL';
        EXECUTE 'INSERT INTO PROIECTEXT SELECT * FROM TMP_PROIECTEXT';
      EXCEPTION WHEN others THEN
        null;
      END;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_cloneazaproiect</obj_name>
  <obj_hashval>7d584cd021458f7d961df3fb2ae0b499</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_cloneazaproiect(INOUT vcodproiect numeric, INOUT vcodretveche numeric, INOUT vcodretnoua numeric, INOUT vcodproiectnou numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  vCod   numeric;
  vCount numeric;
BEGIN
  --Adina 25.06.2021 - sinc.Oracle din 24.06.2021
  SELECT NEXTVAL('SEQ_PROIECT_CODPROIECT') INTO vCodProiectNou;

  INSERT INTO proiect(CODPROIECT, CODVERSIUNE, CODOBIECTPROD, VERSIUNE, INTOCMITA, DATAPROIECT, CLASA, PROCESARE, COMPLEX, ACTIV, FINALIZAT, BLOCAT, INVIZIBILA, GENERIC, DURATA, MARJAORDINE, USERID, DATACREARE, OBS1, OBS2, OBS3, OBS4, OBS5, OBS6, CodIdentificare)
  SELECT vCodProiectNou, CODVERSIUNE, CODOBIECTPROD, VERSIUNE, INTOCMITA, DATE_TRUNC('DAY',CURRENT_TIMESTAMP), CLASA, PROCESARE, COMPLEX, ACTIV, FINALIZAT, BLOCAT, INVIZIBILA, GENERIC, DURATA, MARJAORDINE, current_setting('PKG_GLOBALS.USERID', true)::numeric, CURRENT_TIMESTAMP, OBS1, OBS2, OBS3, OBS4, OBS5, OBS6, CodIdentificare
  FROM proiect WHERE codproiect = current_setting('PKG_PROIECT.vCodProiect', true)::numeric;

  DELETE FROM tmp_proiectnod;
  INSERT INTO tmp_proiectnod(CODPROIECTNOD, CODPROIECT, CANT, NODORIGINAL, POZITIE, CODRETETA, TIP, CODOBIECT, INDEXPARINTE, CODPRODMAT, NIVEL, ORDINE, DECALAJ)
  SELECT CODPROIECTNOD, vCodProiectNou, CANT, NODORIGINAL, POZITIE, CODRETETA, TIP, CODOBIECT, INDEXPARINTE, CODPRODMAT, NIVEL, ORDINE, DECALAJ
  FROM proiectnod WHERE codproiect = current_setting('PKG_PROIECT.vCodProiect', true)::numeric;

  FOR v_rec IN (SELECT codproiectnod FROM proiectnod WHERE codproiect = current_setting('PKG_PROIECT.vCodProiect', true)::NUMERIC ORDER BY codproiectnod) LOOP
    SELECT NEXTVAL('SEQ_PROIECTNOD_CODPROIECTNOD') INTO vCod;

    UPDATE tmp_proiectnod SET codproiectnod = vcod WHERE codproiectnod = v_rec.codproiectnod;
    UPDATE tmp_proiectnod SET nodoriginal   = vcod WHERE nodoriginal = v_rec.codproiectnod;
  END LOOP;

  FOR v_rec IN (SELECT codproiectnod, codreteta, indexparinte, cant, nivel FROM tmp_proiectnod ORDER BY codproiectnod) LOOP
    IF  v_rec.codreteta = vCodRetVeche THEN
      UPDATE tmp_proiectnod SET codreteta = vCodRetNoua WHERE codproiectnod = v_rec.codproiectnod;

      DELETE FROM tmp_proiectnod WHERE indexparinte &lt;&gt; v_rec.indexparinte and  instrb(indexparinte, v_rec.indexparinte) = 1;

      PERFORM PKG_PROIECT_BagaProiectNodDinRetetaX(vCodProiectNou, vCodRetNoua, v_rec.Cant, v_rec.IndexParinte, v_rec.CodProiectNod, v_rec.Nivel);
    END IF;
  END LOOP;

  INSERT INTO proiectnod(CODPROIECTNOD, CODPROIECT, CANT, NODORIGINAL, POZITIE, CODRETETA, TIP, CODOBIECT, INDEXPARINTE, CODPRODMAT, NIVEL, ORDINE, DECALAJ)
  SELECT CODPROIECTNOD, CODPROIECT, CANT, NODORIGINAL, POZITIE, CODRETETA, TIP, CODOBIECT, INDEXPARINTE, CODPRODMAT, NIVEL, ORDINE, DECALAJ
  FROM tmp_proiectnod;

  SELECT count(*)
  INTO vCount
  FROM proiectnod pn INNER JOIN prodcomp pc ON  pn.codreteta = pc.codprodcomp
  WHERE pn.codproiect = vCodProiectNou and  COALESCE(pc.generic, 0) = 0 and  pc.codprodcomp &gt; 0;

  IF  vCount = 0 THEN
    UPDATE proiect SET generic = 1 WHERE codproiect = vCodProiectNou;
  ELSE
    UPDATE proiect SET generic = 0 WHERE codproiect = vCodProiectNou;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_corectextunic</obj_name>
  <obj_hashval>3610e152a0ea0d2c35e9857deb7e9afe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_corectextunic()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodM  numeric;
  aCount numeric;
  vNr    numeric;
  ssql   varchar;
begin
  IF  (fnc_TmpExists('PROIECTEXT')) = 1 THEN
    BEGIN
      EXECUTE 'select count(*) from proiectext' INTO aCount;
    EXCEPTION WHEN others THEN
      aCount := 0;
    END;

    IF  aCount &gt; 0 THEN
      BEGIN
        EXECUTE 'select min(codproiectext) - 1 from proiectext' INTO aCodM;
      EXCEPTION WHEN others THEN
        aCodM := 100;
      END;

      sSql := 'begin
                 for v_rec in (select ' || coalesce(aCodM::varchar ,'') || ' + row_number() over() NewCod, codproiect from proiectext order by codproiectext) loop
                   update proiectext set codproiectext = v_rec.newcod where codproiect = v_rec.codproiect;
                 end loop;
               end;';
      EXECUTE ssql;
      EXECUTE 'SELECT SEQ_PROIECTEXT_CODPROIECTEXT.NEXTVAL' INTO vNr;
      EXECUTE 'select max(codproiectext)+1 from proiectext' INTO aCodM;

      BEGIN
        EXECUTE 'DROP SEQUENCE SEQ_PROIECTEXT_CODPROIECTEXT';
      EXCEPTION WHEN OTHERS THEN
        NULL;
      END;

      EXECUTE 'CREATE SEQUENCE SEQ_PROIECTEXT_CODPROIECTEXT START WITH ' || coalesce(aCodM::varchar ,'') || ' INCREMENT BY 1';
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_ct_monitor</obj_name>
  <obj_hashval>26ef3c60ab5fb957912575216f337afa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PROIECT.CT_MONITOR', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_42';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_curataextacunse</obj_name>
  <obj_hashval>e59607bd7eef1b6674912229d8f9924c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_curataextacunse()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  ssql varchar;
begin
  sSql := 'begin
               for v_rec in (select codproiect from proiect where ascuns = 1) loop
                 delete from proiectext where codproiect = v_rec.codproiect;
               end loop;
             end;';
  EXECUTE ssql;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_deleteproject</obj_name>
  <obj_hashval>601b1ec7df8479f9f01cfd4cf3033e5f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_deleteproject(INOUT wme_result numeric, INOUT acodprodcomp numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  Rez   numeric;
begin
  Rez := 1;
  FOR v_rec IN (SELECT  DISTINCT P.CodProiect
                FROM proiect p INNER JOIN proiectnod pn ON  p.codproiect = pn.codproiect
                WHERE pn.codreteta = aCodProdComp
               )
  LOOP
    BEGIN
      PERFORM PKG_PROIECT_SP_LOCKRECORD(v_rec.codproiect);
    EXCEPTION WHEN others THEN
      Rez := 0;
      EXIT ;
    END;
  END LOOP;

  IF  Rez = 0 THEN
    WME_Result :=  Rez;
    RETURN;
  END IF;

  FOR v_rec IN (SELECT  DISTINCT P.CodProiect
                FROM proiect p INNER JOIN proiectnod pn ON  p.codproiect = pn.codproiect
                WHERE pn.codreteta = aCodProdComp
               )
  LOOP
    BEGIN
      PERFORM PKG_PROIECT_SP_DELETERECORD_FARALOCKCOMMIT(v_rec.codproiect);
    EXCEPTION WHEN others THEN
      Rez := 0;
      EXIT ;
    END;
  END LOOP;

  IF  Rez = 0 THEN
  ELSE
  END IF;

  WME_Result :=  Rez;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_docommit</obj_name>
  <obj_hashval>bfff087a070bd48fec104f21a5424bfc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_docommit(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PROIECT.DoCommit', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := true;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_genprj_inlocret</obj_name>
  <obj_hashval>deb1811d7a8a14b7b95721ff249fec41</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_genprj_inlocret(vcodretvechi numeric, vcodretnou numeric, vinactiveprj numeric, vinactiveret numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC      RECORD;
  vCodPrjNou numeric;
begin
  FOR v_rec IN (SELECT  DISTINCT pn.codproiect FROM proiectnod pn WHERE codreteta = vCodRetVechi) LOOP
    PERFORM PKG_PROIECT_CloneazaProiect(v_rec.CodProiect, vCodRetVechi, vCodRetNou, vCodPrjNou);

    IF  vInactivePrj &gt; 0 THEN
      UPDATE proiect
      SET
      activ    = 0,
      generic  = 0,
      implicit = 0
      WHERE
       codproiect = v_rec.codproiect;
    END IF;

    IF  vInactiveRet &gt; 0 THEN
      UPDATE prodcomp
      SET
      inactiv  = 1,
      generic  = 0,
      implicit = 0
      WHERE
       codprodcomp = vCodRetVechi;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_genprjascuns</obj_name>
  <obj_hashval>ef24d8a9ef7e344053086abb5fc7747e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_genprjascuns(INOUT acodproiect numeric, INOUT acodproiectnou numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aCod     numeric;
  aCodPN   numeric;
  aNod     numeric;
  aCodRet  numeric;
  aCodRetN numeric;
BEGIN
  --Adina 22.06.2021 - sinc.Oracle din 21.06.2021
  --Bogdan 13.10.2020
  SELECT NEXTVAL ('SEQ_PROIECT_CODPROIECT') INTO aCod;

  INSERT INTO proiect (CODPROIECT,
      CODVERSIUNE,
      CODOBIECTPROD,
      VERSIUNE,
      INTOCMITA,
      DATAPROIECT,
      CLASA,
      PROCESARE,
      COMPLEX,
      ACTIV,
      FINALIZAT,
      BLOCAT,
      INVIZIBILA,
      GENERIC,
      DURATA,
      MARJAORDINE,
      USERID,
      DATACREARE,
      OBS1,
      OBS2,
      OBS3,
      OBS4,
      OBS5,
      OBS6,
      Ascuns)
  SELECT aCod,
    CODVERSIUNE,
    CODOBIECTPROD,
    VERSIUNE,
    INTOCMITA,
    DATE_TRUNC ('DAY',CURRENT_TIMESTAMP) ,
    CLASA,
    PROCESARE,
    COMPLEX,
    ACTIV,
    FINALIZAT,
    BLOCAT,
    INVIZIBILA,
    0,
    DURATA,
    MARJAORDINE,
    current_setting ('PKG_GLOBALS.USERID', true) ::numeric,
    CURRENT_TIMESTAMP,
    OBS1,
    OBS2,
    OBS3,
    OBS4,
    OBS5,
    OBS6,
    1
  FROM proiect WHERE codproiect = aCodProiect;

  DELETE FROM tmp_proiectnod;

  INSERT INTO tmp_proiectnod (CODPROIECTNOD, CODPROIECT, CANT, NODORIGINAL, POZITIE, CODRETETA, TIP, CODOBIECT, INDEXPARINTE, CODPRODMAT, NIVEL, ORDINE, DECALAJ, INCEPERE)
  SELECT CODPROIECTNOD, aCod, CANT, NODORIGINAL, POZITIE, CODRETETA, TIP, CODOBIECT, INDEXPARINTE, CODPRODMAT, NIVEL, ORDINE, DECALAJ, INCEPERE
  FROM proiectnod WHERE codproiect = aCodProiect;

  FOR v_rec IN (SELECT codproiectnod FROM proiectnod WHERE codproiect = aCodProiect ORDER BY indexparinte) LOOP
    SELECT NEXTVAL ('SEQ_PROIECTNOD_CODPROIECTNOD') INTO aCodPN;

    UPDATE tmp_proiectnod SET codproiectnod = aCodPN WHERE codproiectnod = v_rec.codproiectnod;
    UPDATE tmp_proiectnod SET nodoriginal   = aCodPN WHERE nodoriginal   = v_rec.codproiectnod;
  END LOOP;

  INSERT INTO proiectnod (CODPROIECTNOD, CODPROIECT, CANT, NODORIGINAL, POZITIE, CODRETETA, TIP, CODOBIECT, INDEXPARINTE, CODPRODMAT, NIVEL, ORDINE, DECALAJ, INCEPERE)
  SELECT CODPROIECTNOD, CODPROIECT, CANT, NODORIGINAL, POZITIE, CODRETETA, TIP, CODOBIECT, INDEXPARINTE, CODPRODMAT, NIVEL, ORDINE, DECALAJ, INCEPERE
  FROM tmp_proiectnod;

  UPDATE proiect SET codutilizare    = aCod WHERE codproiect      = aCodProiect;
  update proiect set codidentificare = aCod where codidentificare = aCodProiect;

  IF (fnc_TmpExists ('PROIECTEXT')) = 1 THEN
    PERFORM PKG_PROIECT_CheckTmpExt();
    EXECUTE 'DELETE FROM TMP_PROIECTEXT';
    EXECUTE 'INSERT INTO TMP_PROIECTEXT SELECT * FROM PROIECTEXT WHERE CODPROIECT = ' || coalesce (ACODPROIECT::varchar ,'');
    EXECUTE 'UPDATE TMP_PROIECTEXT SET CODPROIECT = ' || coalesce (ACOD::varchar ,'') || ', CODPROIECTEXT = NEXTVAL(''SEQ_PROIECTEXT_CODPROIECTEXT'')';
    EXECUTE 'INSERT INTO PROIECTEXT SELECT * FROM TMP_PROIECTEXT';
    EXECUTE 'DELETE FROM TMP_PROIECTEXT';
  END IF;

  aCodProiectNou := aCod;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_genprjfromreteta</obj_name>
  <obj_hashval>7e4329b5b1fd82cb62d0d009e941739b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_genprjfromreteta(INOUT wme_result numeric, INOUT acodprodcomp numeric, negeneric numeric DEFAULT 0)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCod    numeric;
  vCodNod numeric;
  vCant   numeric;
  aDurata numeric;
BEGIN
  --Florin 28.03.2022 - sinc. Oracle
  SELECT NEXTVAL('SEQ_PROIECT_CODPROIECT') INTO vCod;

  SELECT Cant INTO vCant FROM ProdComp WHERE codprodcomp = aCodProdComp;

  INSERT INTO proiect(codproiect, codobiectprod, versiune, intocmita, dataproiect, procesare, clasa, activ, finalizat, blocat, invizibila, generic, implicit, userid, datacreare)
  SELECT vCod, codobiect, substr(Obs, 1, 100), proiectant, data, tipreteta, codclasaprod, 1, 1, 0, 0, 1, 0, current_setting('PKG_GLOBALS.USERID', true)::numeric, CURRENT_TIMESTAMP
  FROM prodcomp WHERE codprodcomp = aCodProdComp;

  SELECT NEXTVAL('SEQ_PROIECTNOD_CODPROIECTNOD') INTO vCodNod;

  INSERT INTO proiectnod(codproiectnod, codproiect, cant, nodoriginal, pozitie, codreteta, tip, codobiect, indexparinte, nivel)
  SELECT vCodNod, vCod, cant, 0, 0, aCodProdComp, tipreteta, codobiect, '.00', 0
  FROM prodcomp WHERE codprodcomp = aCodProdComp;

  PERFORM PKG_PROIECT_BagaProiectNodDinReteta(vCod, aCodProdComp, vCant, '.00', vCodNod, 0);

  DELETE FROM tmp_proiectman;
  INSERT INTO tmp_proiectman(CODPROIECTNOD, CODPROIECT, NODORIGINAL, POZITIE, CODRETETA, DEN_OBIECT, TIP, SIMBOL, DURATA, CANT, NIVEL, ORDINE, INCEPERE, Decalaj, DURATANOD, COPILMAXIM, NODCRITIC, BARA)
  SELECT PN.CODPROIECTNOD, PN.CODPROIECT, PN.NODORIGINAL, PN.POZITIE, PN.CODRETETA, obj.denumire DEN_OBIECT, 0, pn.IndexParinte SIMBOL, Round((pn.Cant * COALESCE(pc.Durata, 0) / pc.cant)::numeric, 3) DURATA, pn.Cant, pn.nivel, o.Ordine, 0, 0, 0, -1, '...' NODCRITIC, '...' BARA
  FROM proiectnod pn
  INNER JOIN prodcomp pc ON  pn.codreteta  = pc.codprodcomp
  INNER JOIN nartobj obj ON  obj.codobiect = pc.codobiect
  INNER JOIN (SELECT DISTINCT Nivel,
                     (SELECT Max(Nivel) FROM proiectnod WHERE CodProiect = vCod) - Nivel AS ORDINE
              FROM proiectnod WHERE CodProiect = vCod GROUP BY Nivel
             ) O ON  O.Nivel = pn.Nivel
  WHERE PN.CodProiect = vCod and  pc.codprodcomp &gt; 0;

  PERFORM PKG_PROIECT_SetCopilMaxim(vCod);
  aDurata := 0;

  BEGIN
    SELECT DurataNod INTO aDurata FROM tmp_proiectman WHERE COALESCE(nodoriginal, 0) = 0;
  EXCEPTION WHEN others THEN
    aDurata := 0;
  END;

  IF  aDurata &lt;&gt; 0 THEN
    UPDATE proiect SET Durata = aDurata WHERE CodProiect = vCod;
  END IF;

  WME_Result :=  vCod;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_genproiectgeneric</obj_name>
  <obj_hashval>505bf0d8e5d862d9f4099f36f17294ec</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_genproiectgeneric(INOUT wme_result numeric, INOUT acodprodcomp numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  vCod    numeric;
  vCodNod numeric;
  vCant   numeric;
  aDurata numeric;
begin
  BEGIN
    vCod := 0;
    SELECT NEXTVAL('SEQ_PROIECT_CODPROIECT') INTO vCod;
    SELECT Cant INTO vCant FROM ProdComp WHERE codprodcomp = aCodProdComp;

    INSERT INTO proiect(codproiect, codobiectprod, versiune, intocmita, dataproiect, procesare, clasa, activ, finalizat, blocat, invizibila, generic, implicit, userid, datacreare)
    SELECT vCod, codobiect, Obs, proiectant, data, tipreteta, codclasaprod, 1, 1, 0, 0, 1, 0, current_setting('PKG_GLOBALS.USERID', true)::numeric, CURRENT_TIMESTAMP
    FROM prodcomp WHERE codprodcomp = aCodProdComp;

    SELECT NEXTVAL('SEQ_PROIECTNOD_CODPROIECTNOD') INTO vCodNod;

    INSERT INTO proiectnod(codproiectnod, codproiect, cant, nodoriginal, pozitie, codreteta, tip, codobiect, indexparinte, nivel)
    SELECT vCodNod, vCod, cant, 0, 0, aCodProdComp, tipreteta, codobiect, '.00', 0
    FROM prodcomp WHERE codprodcomp = aCodProdComp;

    PERFORM PKG_PROIECT_BagaProiectNodDinReteta(vCod, aCodProdComp, vCant, '.00', vCodNod, 0);

    DELETE FROM tmp_proiectman;
    INSERT INTO tmp_proiectman(CODPROIECTNOD, CODPROIECT, NODORIGINAL, POZITIE, CODRETETA, DEN_OBIECT, TIP, SIMBOL, DURATA, CANT, NIVEL, ORDINE, INCEPERE, Decalaj, DURATANOD, COPILMAXIM, NODCRITIC, BARA)
    SELECT PN.CODPROIECTNOD, PN.CODPROIECT, PN.NODORIGINAL, PN.POZITIE, PN.CODRETETA, obj.denumire DEN_OBIECT, 0, pn.IndexParinte SIMBOL, Round((pn.Cant * COALESCE(pc.Durata, 0) / pc.cant)::numeric, 3) DURATA, pn.Cant, pn.nivel, o.Ordine, 0, 0, 0, -1, '...' NODCRITIC, '...' BARA
    FROM proiectnod pn
        INNER JOIN prodcomp pc ON  pn.codreteta = pc.codprodcomp
        INNER JOIN nartobj obj ON  obj.codobiect = pc.codobiect
        INNER JOIN (SELECT DISTINCT Nivel,
                           (SELECT Max(Nivel) FROM proiectnod WHERE CodProiect = vCod) - Nivel AS ORDINE
                    FROM proiectnod WHERE CodProiect = vCod GROUP BY Nivel
                   ) O ON  O.Nivel = pn.Nivel
    WHERE PN.CodProiect = vCod and  pc.codprodcomp &gt; 0;

    PERFORM PKG_PROIECT_SetCopilMaxim(vCod);
    aDurata := 0;

    BEGIN
      SELECT DurataNod INTO aDurata FROM tmp_proiectman WHERE COALESCE(nodoriginal, 0) = 0;
    EXCEPTION WHEN others THEN
      aDurata := 0;
    END;

    IF  aDurata &lt;&gt; 0 THEN
      UPDATE proiect SET Durata = aDurata WHERE CodProiect = vCod;
    END IF;

    FOR v_rec IN (SELECT prj.nr NR_MAT_PROIECT, mat.nr NR_MAT_RETETA, mat.codprodcomp
                  FROM (SELECT count(*) NR, pn0.codproiect, pn0.codreteta
                        FROM proiect pn
                        INNER JOIN proiectnod pn0 ON  pn0.codproiect = pn.codproiect
                        INNER JOIN proiectnod pn1 ON  pn1.nodoriginal = pn0.codproiectnod and  pn1.codproiect = pn.codproiect
                        WHERE pn.codproiect = vCod
                        GROUP BY pn0.codproiect, pn0.codreteta
                       ) prj
                       INNER JOIN (SELECT count(*) NR, codprodcomp FROM prodmat WHERE codprodcomp = aCodProdComp GROUP BY codprodcomp
                                  ) mat ON  prj.codreteta = mat.codprodcomp
                  WHERE prj.nr &lt;&gt; mat.nr
                 )
    LOOP
      vCod := 0;
    END LOOP;
  EXCEPTION WHEN others THEN
    vCod := 0;
  END;

  IF  vCod &gt; 0 THEN
  END IF;

  WME_Result :=  vCod;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_genretcentralizatoare</obj_name>
  <obj_hashval>ac81d9b4a97762baa1e53ba1d13ecb0f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_genretcentralizatoare(INOUT wme_result numeric, INOUT acodproiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  vCodProdComp numeric;
  vCodProdGest numeric;
begin
  SELECT NEXTVAL('SEQ_PRODCOMP_CODPRODCOMP') INTO vCodProdComp;

  FOR v_rec IN (SELECT pc.*, pn0.cant CANTNOU
                FROM proiect p
                INNER JOIN proiectnod pn0 ON  pn0.codproiect = p.codproiect and  pn0.nodoriginal = 0
                INNER JOIN prodcomp pc ON  pn0.codreteta = pc.codprodcomp
                WHERE p.codproiect = aCodProiect
               )
  LOOP
    INSERT INTO prodcomp(codprodcomp, codobiect, obs, data, anulat, blocat, operat, cant, pret, coefindirecte, implicit, descriere, inactiv, gest, identificator, datadocumentatie, arhiva, observatii, proiectant, codclasaprod, invizibila, generic, durata, userid, datacreare, hfactor, valmat, valman, valregie, tippret, codproiect, obs1, obs2, obs3, obs4, obs5, obs6, codmoneda, pretvaluta, ag, valag, profit, valprofit, pretfinal, valprofitv, pretfinalv, totpretcoef, totpretfix, totpretcoefv, totpretfixv, valregieman)
    VALUES(vCodProdComp, v_rec.codobiect, v_rec.obs, v_rec.data, v_rec.anulat, v_rec.blocat, v_rec.operat, v_rec.cantnou, v_rec.pret, v_rec.coefindirecte, 0, v_rec.descriere, v_rec.inactiv, v_rec.gest, v_rec.identificator, v_rec.datadocumentatie, v_rec.arhiva, v_rec.observatii, v_rec.proiectant, v_rec.codclasaprod, v_rec.invizibila, 0, v_rec.durata, v_rec.userid, v_rec.datacreare, v_rec.hfactor, v_rec.valmat, v_rec.valman, v_rec.valregie, v_rec.tippret, aCodProiect, v_rec.obs1, v_rec.obs2, v_rec.obs3, v_rec.obs4, v_rec.obs5, v_rec.obs6, v_rec.codmoneda, v_rec.pretvaluta, v_rec.ag, v_rec.valag, v_rec.profit, v_rec.valprofit, v_rec.pretfinal, v_rec.valprofitv, v_rec.pretfinalv, v_rec.totpretcoef, v_rec.totpretfix, v_rec.totpretcoefv, v_rec.totpretfixv, v_rec.valregieman);

    EXIT ;
  END LOOP;

  SELECT NEXTVAL('SEQ_PRODGEST_CODPRODGEST') INTO vCodProdGest;

  FOR v_rec IN (SELECT pg.*
                FROM proiect p
                INNER JOIN proiectnod pn0 ON  pn0.codproiect = p.codproiect and  pn0.nodoriginal = 0
                INNER JOIN prodgest pg ON  pn0.codreteta = pg.codprodcomp
                WHERE p.codproiect = aCodProiect
               )
  LOOP
    INSERT INTO prodgest(codprodgest, codprodcomp, indexlocal, codgest, coefmat, coefman)
    VALUES(NEXTVAL('SEQ_PRODGEST_CODPRODGEST'), vCodProdComp, v_rec.indexlocal, v_rec.codgest, v_rec.coefmat, v_rec.coefman);

    EXIT ;
  END LOOP;

  FOR v_rec IN (SELECT sum(pn.cant) CANT_NOU, mat.codobiect, mat.pret, mat.d1, mat.d2, mat.d3, mat.indexlocal, sum(pn.cant / mat.cant * mat.cantum1) CANTUM1, mat.tip,
                       mat.codatribut, sum(pn.cant / pc.cant * mat.valmat) VALMAT, sum(pn.cant / mat.cant * mat.valman) VALMAN, sum(pn.cant / mat.cant * mat.valregie) VALREGIE,
                       mat.adddim, mat.adddim_transp, mat.pretorig, mat.procreal, sum(pn.cant / mat.cant * mat.valoare) VALOARE, mat.copyd1, mat.copyd2, mat.copyd3
                FROM proiectnod pn
                LEFT JOIN prodmat mat ON  mat.codmat = pn.codprodmat
                LEFT JOIN prodcomp pc ON  mat.codprodcomp = pc.codprodcomp
                WHERE pn.tip = 3 and  pn.codproiect = aCodProiect
                GROUP BY mat.codobiect, mat.pret, mat.d1, mat.d2, mat.d3, mat.indexlocal, mat.tip, mat.codatribut, mat.adddim, mat.adddim_transp, mat.pretorig, mat.procreal, mat.copyd1, mat.copyd2, mat.copyd3
               )
  LOOP
    INSERT INTO prodmat(codmat, codprodcomp, codobiect, cant, pret, d1, d2, d3, indexlocal, cantum1, codprodgest, tip, codatribut, valmat, valman, valregie, adddim, adddim_transp, pretorig, procreal, valoare, copyd1, copyd2, copyd3)
    VALUES(NEXTVAL('SEQ_PRODMAT_CODMAT'), vCodProdComp, v_rec.codobiect, v_rec.cant_nou, v_rec.pret, v_rec.d1, v_rec.d2, v_rec.d3, v_rec.indexlocal, v_rec.cantum1, vCodProdGest, v_rec.tip, v_rec.codatribut, v_rec.valmat, v_rec.valman, v_rec.valregie, v_rec.adddim, v_rec.adddim_transp, v_rec.pretorig, v_rec.procreal, v_rec.valoare, v_rec.copyd1, v_rec.copyd2, v_rec.copyd3);
  END LOOP;

  WME_Result :=  vCodProdComp;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_getcopilmaxim</obj_name>
  <obj_hashval>bdc0608f776195dbb7009fbbc72671ab</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_getcopilmaxim(INOUT wme_result numeric, INOUT anod numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  x numeric;
  y numeric;
BEGIN
  --Florin 23.10.2020
  SELECT CopilMaxim INTO x FROM Tmp_Proiectman WHERE CodProiectNod = aNod;

  IF  x = -1 THEN
    x := 0;
    FOR v_rec IN (SELECT * FROM Tmp_Proiectman WHERE NodOriginal = aNod) LOOP
      y := pkg_proiect_getcopilmaxim(NULL, v_rec.CodProiectNod) + v_rec.Durata;
      IF  y &gt; x THEN
        x := y;
      END IF;
    END LOOP;

    UPDATE tmp_proiectman
    SET
    copilmaxim = x,
    DurataNod  = Durata + x
    WHERE
     CodProiectNod = aNod;
  END IF;

  WME_Result :=  x;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_getdocommit</obj_name>
  <obj_hashval>8e2674c51b67a2c7a2a7f6dc000995ce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_getdocommit(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PROIECT.DoCommit', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := true;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_getduratacopii</obj_name>
  <obj_hashval>917b2cd29a53c86136f485fe2b020d4c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_getduratacopii(acodnod numeric, adur numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC           RECORD;
  Copii           numeric;
  Dur             numeric;
  DurNodPrecedent numeric;
  DurataNodCurent numeric;
BEGIN
  --Adina 10.06.2021 - sinc.Oracle din 09.06.2021
  Dur := 0;
  BEGIN
    SELECT Count(*) INTO STRICT Copii FROM tmp_proiectman WHERE NodOriginal = aCodNod;
  EXCEPTION WHEN no_data_found THEN
    Copii := 0;
  END;

  IF  Copii = 0 THEN
    Dur := aDur;
  ELSE
    DurNodPrecedent := 0;
    FOR V_REC IN (SELECT RowNum IND, X.* FROM tmp_proiectman x WHERE NodOriginal = aCodNod ORDER BY Pozitie) LOOP
      DurataNodCurent := V_Rec.Durata + GetDurataCopii(V_Rec.CODPROIECTNOD, V_Rec.Durata);
      IF  V_rec.Decalaj = 3 THEN
        IF  DurataNodCurent &gt; DurNodPrecedent THEN
          Dur := Dur + DurataNodCurent;
        ELSE
          Dur := Dur + DurNodPrecedent;
        END IF;
      ELSIF V_rec.Decalaj = 4 THEN
        IF  DurataNodCurent &gt; DurNodPrecedent THEN
          Dur := Dur + DurataNodCurent;
        ELSE
          Dur := Dur + DurNodPrecedent;
        END IF;
      ELSE
        Dur := Dur + DurataNodCurent;
      END IF;
      DurNodPrecedent := DurataNodCurent;
    END LOOP;
  END IF;

  UPDATE tmp_proiectman x SET DurataNod = Dur WHERE x.codproiectnod = aCodNod;

  RETURN Dur;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_getmasa</obj_name>
  <obj_hashval>74e51e1511146abe2a3688f8540c404b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_getmasa(INOUT wme_result numeric, INOUT acodproiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
   select sum(FI.Masa * PN.Cant) into WME_Result
   from PROIECT P
         INNER JOIN PROIECTNOD PN ON P.CODPROIECT     = PN.CODPROIECT
         INNER JOIN FISASUP    FS ON PN.CODPROIECTNOD = FS.CODPROIECTNOD
         INNER JOIN FISAINF    FI ON FS.CODFISASUP    = FI.Codfisapro
   where FI.CodFisaSup &gt; 0 and P.CODPROIECT = aCodProiect;
   RETURN ;
  EXCEPTION WHEN undefined_object then
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_getvalcampproiectextins</obj_name>
  <obj_hashval>0c13fbed0ba738e8a5b27020021842ed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_getvalcampproiectextins(INOUT wme_result character varying, INOUT nrfield numeric, INOUT codproiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  Val     varchar;
  sSelect varchar;
  sSchema varchar;
BEGIN
  --Adina 02.06.2021 - add schema
  sSchema := Lower(current_setting('PKG_GLOBALS.FIRMANAME', true));
  IF NULLIF(sSchema, '') IS NULL THEN
    sSchema := public.get_schema();
  END IF;

  IF  (fnc_TmpExists('PROIECTEXT')) = 0 THEN
    WME_Result :=  '';
    RETURN;
  END IF;

  Val := '';
  FOR v_rec IN (SELECT tab.*, row_number() over() NRFIELD FROM information_schema.columns tab WHERE tab.table_schema = sSchema AND tab.table_name = 'proiectext') LOOP
    IF  NrField = v_rec.NrField THEN
      IF  v_rec.data_type = 'numeric' THEN
        sSelect := 'select ' || coalesce(v_rec.column_name,'') || '::varchar from proiectext where codproiect = ' || coalesce(CodProiect::varchar ,'');
        EXECUTE sSelect INTO Val;
      END IF;

      IF  v_rec.data_type = 'character varying' THEN
        sSelect := 'select ' || coalesce(v_rec.column_name,'') || ' from proiectext where codproiect = ' || coalesce(CodProiect::varchar ,'');
        EXECUTE sSelect INTO Val;
      END IF;

      IF  v_rec.data_type = 'date' THEN
        sSelect := 'select to_char(' || coalesce(v_rec.column_name,'') || ', ''dd.mm.yyyy'') from proiectext where codproiect = ' || coalesce(CodProiect::varchar ,'');
        EXECUTE sSelect INTO Val;
      END IF;

      EXIT ;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_getvcodproiect</obj_name>
  <obj_hashval>c79ba36409437c41773072ae89b548eb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_getvcodproiect(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PROIECT.vCodProiect', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_getvnecesar</obj_name>
  <obj_hashval>d2e7da24649fcc212d94c8bb3cee531a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_getvnecesar(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result :=  current_setting('PKG_PROIECT.vNecesar', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_lockproject</obj_name>
  <obj_hashval>f673239746b8c56b90c58808a9692aaf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_lockproject(INOUT wme_result numeric, INOUT acodprodcomp numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  Rez   numeric;
begin
  Rez := 1;
  FOR v_rec IN (SELECT  DISTINCT P.CodProiect
                FROM proiect p INNER JOIN proiectnod pn ON  p.codproiect = pn.codproiect
                WHERE pn.codreteta = aCodProdComp
                )
  LOOP
    BEGIN
      PERFORM PKG_PROIECT_SP_LOCKRECORD(v_rec.codproiect);
    EXCEPTION WHEN others THEN
      Rez := 0;
      EXIT ;
    END;
  END LOOP;

  IF  Rez = 0 THEN
  END IF;

  WME_Result :=  Rez;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_propagagant</obj_name>
  <obj_hashval>fca02c8c86daf27b7d669f1a238f7255</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_propagagant(acodproiect numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  V_PN RECORD;
BEGIN
  --Adina 07.07.2021 - sinc.Oracle din 06.07.2021
  FOR v_rec IN (SELECT p.codproiect
                FROM proiect pi INNER JOIN proiect p ON  p.codidentificare = pi.codutilizare
                WHERE pi.codproiect = aCodProiect
               )
  LOOP
    FOR v_pn IN (SELECT pn.codproiectnod, pni.decalaj, pni.incepere
                 FROM proiectnod pni, proiectnod pn
                 WHERE  pni.codproiect = aCodProiect and  pn.codproiect = v_rec.codproiect
                   and  pni.indexparinte = pn.indexparinte and  pni.codobiect = pn.codobiect
                   and  pni.pozitie = pn.pozitie
                )
    LOOP
      UPDATE proiectnod
      SET
        decalaj  = v_pn.decalaj,
        incepere = v_pn.incepere
      WHERE
       codproiectnod = v_pn.codproiectnod;
    END LOOP;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_setcodproiect</obj_name>
  <obj_hashval>40f5bccff4b58d5890091c2accec34d4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_setcodproiect(acodproiect numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PROIECT.vCodProiect',(aCodProiect)::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_setcopilmaxim</obj_name>
  <obj_hashval>98b77266d0b90efc37521b7cd54893ba</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_setcopilmaxim(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  x     numeric;
BEGIN
  --Florin 04.11.2020 - fixat #40630
  FOR v_rec IN (SELECT * FROM tmp_proiectman ORDER BY simbol desc) LOOP
    x := pkg_proiect_getcopilmaxim(v_rec.CodProiectNod);

    UPDATE tmp_proiectman
    SET
    copilmaxim = x,
    DurataNod  = Durata + x
    WHERE
     CodProiectNod = v_rec.CodProiectNod;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_setdecalaj</obj_name>
  <obj_hashval>550a523b516a47e830f2251bdd84ff87</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_setdecalaj(acodnod numeric, total numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC          RECORD;
  DurataParinte  numeric;
  DecalajParinte numeric;
BEGIN
  --Adina 10.06.2021 - sinc.Oracle din 09.06.2021
  --Bogdan 28.11.2020
  UPDATE tmp_proiectman SET Incepere = Total - Decalaj - Durata WHERE CodProiectNod = aCodNod;

  BEGIN
    SELECT COALESCE (Durata, 0) , COALESCE (Decalaj, 0)
    into STRICT DurataParinte, DecalajParinte
    FROM tmp_proiectman
    WHERE CodProiectNod = aCodNod;
  EXCEPTION
  WHEN others THEN
    DurataParinte  := 0;
    DecalajParinte := 0;
  END;

  UPDATE tmp_proiectman
  SET
  --Decalaj  = Decalaj + DecalajParinte + DurataParinte,
  Incepere = Total - (Decalaj + DecalajParinte + DurataParinte)
  WHERE
    NodOriginal = aCodNod;

  FOR v_rec IN (SELECT CodProiectNod FROM tmp_proiectman WHERE NODORIGINAL = aCodNod) LOOP
    PERFORM PKG_PROIECT_SetDecalaj (v_rec.CodProiectNod, Total);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_setdrumcritic</obj_name>
  <obj_hashval>8ad2442c35fedc1cf15a48b252ae4cad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_setdrumcritic(acodnod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  X numeric;
begin
  UPDATE tmp_proiectman SET NodCritic = Simbol WHERE CodProiectNod = aCodNod;

  BEGIN
    SELECT COALESCE (CopilMaxim, 0) into STRICT X FROM tmp_proiectman WHERE CodProiectNod = aCodNod;

  EXCEPTION
  WHEN others THEN
    X := 0;
  END;

  FOR v_rec IN (SELECT CodProiectNod FROM tmp_proiectman WHERE COALESCE (DurataNod, 0) = X and NODORIGINAL = aCodNod) LOOP
    PERFORM PKG_PROIECT_SetDrumCritic (v_rec.CodProiectNod);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_setduratanod</obj_name>
  <obj_hashval>c3d04e4857b8ef95ad37c395819307b1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_setduratanod(acodproiectnod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC         RECORD;
  V_TMP         RECORD;
  aDurPrec      numeric;
  aPrecI        numeric;
  aPrecF        numeric;
  aCod          numeric;
  aCount        numeric;
  aDif          numeric;
  aIndexParinte varchar;
  aDur          numeric;
BEGIN
  --Adina 23.06.2021 - sinc.Oracle din 22.06.2021
  --Adina 10.06.2021 - sinc.Oracle din 09.06.2021
  SELECT indexparinte INTO aindexparinte FROM tmp_proiectman WHERE codproiectnod = acodproiectnod;
  SELECT count(*)     INTO aCount        FROM tmp_proiectman WHERE nodoriginal   = aCodproiectnod;

  IF  aCount = 0 THEN
    UPDATE tmp_proiectman SET incepere = 0 WHERE codproiectnod = acodproiectnod;
    RETURN;
  END IF;

  FOR v_rec IN (SELECT codproiectnod, durata, incepere FROM tmp_proiectman WHERE nodoriginal = aCodProiectNod ORDER BY pozitie) LOOP
    aDurPrec := v_rec.durata;
    aPrecI   := v_Rec.incepere;
    aPrecF   := v_Rec.incepere + v_rec.durata;
    aCod     := v_rec.codproiectnod;
    EXIT ;
  END LOOP;

  FOR v_rec IN (SELECT codproiectnod, durata, coalesce(decalaj, 4) DECALAJ, pozitie, indexparinte
                FROM tmp_proiectman
                WHERE nodoriginal = aCodProiectNod and  codproiectnod &lt;&gt; aCod
                ORDER BY pozitie
               )
  LOOP
    IF v_rec.decalaj IN (0, 1, 4) THEN
      SELECT aPrecF - incepere INTO aDif FROM tmp_proiectman WHERE codproiectnod = v_rec.codproiectnod;

      UPDATE tmp_proiectman SET incepere = incepere + aDif WHERE codproiectnod &lt;&gt; v_rec.codproiectnod and  instr(indexparinte, v_rec.indexparinte, 1) = 1;
      UPDATE tmp_proiectman SET incepere = aPrecF          WHERE codproiectnod = v_rec.codproiectnod;

      aPrecI := aPrecI + aDurPrec;
      aPrecF := aPrecF + v_rec.Durata;
    ELSE
      IF  v_Rec.decalaj = 2 THEN
        SELECT aPrecI - incepere INTO aDif FROM tmp_proiectman WHERE codproiectnod = v_rec.codproiectnod;

        UPDATE tmp_proiectman SET incepere = incepere + aDif WHERE codproiectnod &lt;&gt; v_rec.codproiectnod and  instr(indexparinte, v_rec.indexparinte, 1) = 1;
        UPDATE tmp_proiectman SET incepere = aPrecI          WHERE codproiectnod = v_rec.codproiectnod;

        aPrecF := aPrecI + v_Rec.Durata;
--      ELSE
--        IF  v_rec.decalaj = 3 THEN
--          SELECT max(incepere + durata) INTO aDur FROM tmp_proiectman WHERE nodoriginal = acodproiectnod and  pozitie &lt; v_rec.pozitie;
--
--          IF  aDur &lt; v_rec.Durata THEN
--            FOR v_tmp IN (SELECT codproiectnod, indexparinte, incepere FROM tmp_proiectman WHERE nodoriginal = aCodProiectNod and  pozitie &lt; v_Rec.pozitie) LOOP
--              UPDATE tmp_proiectman SET incepere = incepere + v_rec.durata - aDur WHERE instrb(indexparinte, v_tmp.indexparinte, 1) = 1;
--            END LOOP;
--
--            aPrecI := 0;
--            aPrecF := v_rec.Durata;
--          ELSE
--            aPrecI := aDur - v_Rec.Durata;
--
--            SELECT aPrecI - incepere INTO aDif FROM tmp_proiectman WHERE codproiectnod = v_rec.codproiectnod;
--
--            UPDATE tmp_proiectman SET incepere = aPrecI          WHERE codproiectnod = v_rec.codproiectnod;
--            UPDATE tmp_proiectman SET incepere = incepere + aDif WHERE codproiectnod &lt;&gt; v_rec.codproiectnod and  instr(indexparinte, v_rec.indexparinte, 1) = 1;
--          END IF;
--        END IF;
      END IF;
    END IF;
    aDurPrec := v_Rec.durata;
  END LOOP;

  UPDATE tmp_proiectman
  SET
  incepere = (SELECT max(t.incepere + t.durata) FROM tmp_proiectman t WHERE t.nodoriginal = acodproiectnod)
  WHERE codproiectnod = acodproiectnod;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_setinceperecopii</obj_name>
  <obj_hashval>cbdd8dc0f3087aa3894365269286ff3d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_setinceperecopii(acodnod numeric, afinal numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC              RECORD;
  Copii              numeric;
  IncepeNodPrecedent numeric;
  IncepeNodCurent    numeric;
  DurataNodPrecedent numeric;
  aDecalaj           numeric;
BEGIN
  --Adina 10.06.2021 - sinc.Oracle din 09.06.2021
  BEGIN
    SELECT Count(*) INTO Copii FROM tmp_proiectman WHERE NodOriginal = aCodNod;
  EXCEPTION WHEN no_data_found THEN
    Copii := 0;
  END;

  IF  Copii = 0 THEN
    UPDATE tmp_proiectman x SET Incepere = aFinal WHERE x.codproiectnod = aCodNod;
  ELSE
    IncepeNodPrecedent := 0;
    DurataNodPrecedent := 0;

    FOR V_REC IN (SELECT row_number() over() IND, X.* FROM tmp_proiectman x WHERE NodOriginal = aCodNod ORDER BY Pozitie) LOOP
      aDecalaj := COALESCE(V_rec.Decalaj, 0);
      IF  aDecalaj = 3 THEN
        IF  V_REC.Duratanod &gt;= DurataNodPrecedent THEN
          IncepeNodCurent := IncepeNodPrecedent;
        ELSE
          IncepeNodCurent := IncepeNodPrecedent + DurataNodPrecedent - V_REC.DurataNod;
          aDecalaj        := 4;
        END IF;
      ELSIF aDecalaj = 4 THEN
        IF  V_REC.Duratanod &gt;= DurataNodPrecedent THEN
          IncepeNodCurent := IncepeNodPrecedent;
          aDecalaj        := 3;
        ELSE
          IncepeNodCurent := IncepeNodPrecedent + DurataNodPrecedent - V_REC.DurataNod;
        END IF;
      ELSE
        IF  V_Rec.Ind = 1 THEN
          aDecalaj := 1;
        ELSE
          aDecalaj := 2;
        END IF;

        IncepeNodCurent := IncepeNodPrecedent + DurataNodPrecedent;
      END IF;

      IncepeNodCurent    := aFinal + IncepeNodCurent;
      DurataNodPrecedent := V_REC.DurataNod;
      IncepeNodPrecedent := IncepeNodCurent;

      UPDATE tmp_proiectman x
      SET
      Decalaj  = aDecalaj,
      Incepere = IncepeNodCurent
      WHERE
       x.codproiectnod = V_REC.CodProiectNod;

      PERFORM pkg_proiect_SetIncepereCopii(V_REC.CodProiectNod, IncepeNodCurent + V_REC.DurataNod);
    END LOOP;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_setvnecesar</obj_name>
  <obj_hashval>689b18ba1aa4566b9fcfed8f1e07dfa6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_setvnecesar(avnecesar numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PROIECT.vNecesar',avNecesar::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_sp_deleterecord</obj_name>
  <obj_hashval>10dc0aea9dc7bc35ef97479c3d8c6f22</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDataDoc      date;
  aDoc          varchar;
  aCodUtilizare numeric;
BEGIN
  --Florin 01.06.2023 - monitor
  --Florin 12.04.2023 - sinc. Oracle (11.04.2023)
  --Florin 23.10.2020
  --Florin 23.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_proiect_setct_monitor('MON_42');
  PERFORM PKG_PROIECT_SP_LOCKRECORD(RecId);
  PERFORM PKG_CFGTABLES_EXT_DELETERECORD (recId, 507);

  SELECT DATAPROIECT, VERSIUNE, CODUTILIZARE
  INTO aDATADOC, ADOC, ACODUTILIZARE
  FROM PROIECT
  WHERE CODPROIECT = RECID;

  IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_PROIECT.CT_MONITOR', true)))
  THEN
    PERFORM pkg_userfirme_postlogcucommit('PROIECT', current_setting('PKG_GLOBALS.USERNAME', true), 'S', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, aDataDoc, aDoc, null, current_setting('PKG_GLOBALS.EXE_VERSION', true));
  END IF;

  DELETE FROM PROIECTNOD WHERE CODPROIECT = RecId;
  update proiect set codidentificare = null where codidentificare = recid;

  IF  ACODUTILIZARE &gt; 0 THEN
    DELETE FROM PROIECTNOD WHERE CODPROIECT = ACODUTILIZARE;
    DELETE FROM PROIECT    WHERE CODPROIECT = ACODUTILIZARE;
  END IF;

  DELETE FROM PROIECT WHERE CodProiect = RecId;
  PERFORM NotifyModif(2, RecId, 'PROIECT');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_sp_deleterecord_faralockcommit</obj_name>
  <obj_hashval>f51113aa4801bb18a7560052d211322b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_sp_deleterecord_faralockcommit(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDataDoc date;
  aDoc     varchar;
BEGIN
  --Florin 12.04.2023 - sinc. Oracle (11.04.2023)
  --Florin 23.10.2020
  --Florin 23.03.2021 - pkg_userfirme_postlogcucommit
  SELECT DATAPROIECT, VERSIUNE INTO aDATADOC, ADOC FROM PROIECT WHERE CODPROIECT = RECID;
  PERFORM PKG_CFGTABLES_EXT_DELETERECORD (recId, 507);

  IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_PROIECT.CT_MONITOR', true)))
  THEN
    PERFORM pkg_userfirme_postlogcucommit('PROIECT', current_setting('PKG_GLOBALS.USERNAME', true), 'S', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, aDataDoc, aDoc, null, current_setting('PKG_GLOBALS.EXE_VERSION', true));
  END IF;

  DELETE FROM PROIECTNOD WHERE CODPROIECT = RecId;
  DELETE FROM PROIECT    WHERE CodProiect = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_sp_lockrecord</obj_name>
  <obj_hashval>87cfa684fa874e6346ae5b30b6f98bc0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMP numeric := 0;
BEGIN
  --Florin 23.10.2020
  SELECT CodProiect INTO Tmp FROM PROIECT WHERE CodProiect = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_testandupdategeneric</obj_name>
  <obj_hashval>644e484c9294bf04a1baf253fabf1af4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_testandupdategeneric(acodproiect numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCount     NUMERIC;
  aCodObiect numeric;
BEGIN
  --Florin 21.11.2020 - fixat #38205
  --Florin 21.01.2021 - account ''-&gt;0
  BEGIN
    SELECT codobiectprod INTO aCodObiect FROM proiect WHERE codproiect = aCodProiect;
  EXCEPTION WHEN others THEN
    aCodObiect := 0;
  END;

--  INSERT INTO x(test) VALUES('codobiect:' || coalesce(acodobiect::varchar ,''));

  IF  aCodObiect = 0 THEN
  END IF;

  SELECT count(1) INTO aCount FROM proiect WHERE codobiectprod = aCodObiect and  generic = 1;

--  INSERT INTO x(test) VALUES('proiecte generice:' || coalesce(acount,0));

  IF  aCount &gt; 0 THEN
  END IF;

  SELECT count(*) INTO aCount
  FROM proiectnod pn INNER JOIN prodcomp pc ON  pc.codprodcomp = pn.codreteta
  WHERE pn.codproiect = aCodProiect and  COALESCE(pc.generic, 0) = 0 and  pn.codreteta &gt; 0;

--  INSERT INTO x(test) VALUES('retete negenerice:' || coalesce(acount,0));

  IF  aCount = 0 THEN
    UPDATE proiect SET generic = 1 WHERE codproiect = aCodProiect;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_umpleman</obj_name>
  <obj_hashval>f12a76e3e329d6ae5feca44e8940c758</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_umpleman()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 23.06.2021 - sinc.Oracle din 22.06.2021
  INSERT INTO tmp_proiectman(CODPROIECTNOD, CODPROIECT, NODORIGINAL, POZITIE, CODRETETA, DEN_OBIECT, TIP, SIMBOL, DURATA, CANT, NIVEL, ORDINE, INCEPERE,
                             Decalaj, DURATANOD, COPILMAXIM, NODCRITIC, BARA, LOTOPTIM, INDEXPARINTE)
  SELECT PN.CODPROIECTNOD, PN.CODPROIECT, PN.NODORIGINAL, PN.POZITIE, PN.CODRETETA, obj.denumire DEN_OBIECT, 0, pn.IndexParinte SIMBOL,
         Round((pn.Cant * COALESCE(pc.Durata, 0) / pc.cant)::numeric, 3) DURATA, pn.Cant, pn.nivel, COALESCE(o.Ordine * 10000 + Pozitie, 0), COALESCE(Incepere, 0),
         PN.DECALAJ, 0, -1, '...' NODCRITIC, '...' BARA, pc.cant, PN.INDEXPARINTE
  FROM tmp_proiectnod pn
      INNER JOIN prodcomp pc  ON  pn.codreteta  = pc.codprodcomp
      INNER JOIN nartobj  obj ON  obj.codobiect = pc.codobiect
      INNER JOIN (SELECT  DISTINCT Nivel, (SELECT Max(Nivel) FROM tmp_proiectnod) - Nivel AS ORDINE
                  FROM tmp_proiectnod
                  GROUP BY Nivel
                 ) O ON  O.Nivel = pn.Nivel
  WHERE pc.codprodcomp &gt; 0;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_updateimplicit</obj_name>
  <obj_hashval>78166b17ee498ff872d53ef2ea02e896</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_updateimplicit(INOUT wme_result boolean, INOUT acodproiect numeric, INOUT aimplicit numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  Done BOOLEAN;
begin
  BEGIN
    UPDATE proiect SET implicit = aImplicit WHERE codproiect = aCodProiect;

    Done := True;
  EXCEPTION WHEN others THEN
    Done := False;
  END;

  WME_Result :=  Done;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_updateindexcopii</obj_name>
  <obj_hashval>5e144efc98b6178d23dceb3c465f9ee1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_updateindexcopii(acodproiectnod numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
declare
  aIndexParinte varchar(50);
  v_rec record;
begin
  select indexparinte into aIndexParinte from proiectnod where codproiectnod = aCodProiectNod;
  for v_rec in (
    select pozitie, codproiectnod
    from proiectnod
    where nodoriginal = aCodProiectNod
    order by pozitie
  ) loop
    update proiectnod set indexparinte = aIndexParinte||'.'||LPAD(to_char(v_rec.pozitie), 2, '0') where codproiectnod = v_rec.codproiectnod;
  end loop;
  for v_rec in (
    select codproiectnod
    from proiectnod
    where nodoriginal = aCodProiectNod and tip &lt; 3
  ) loop
    PERFORM pkg_proeict_UpdateIndexCopii(v_Rec.Codproiectnod);
  end loop;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_updateindexparinte</obj_name>
  <obj_hashval>89e3eab5d1e76ea2043d5820a2fb5764</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_updateindexparinte(acodproiect numeric DEFAULT 0)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
declare
  v_rec record;
BEGIN
  --Florin 16.03.2022
  for v_rec in (
    select p.codproiect, pn0.codproiectnod
    from proiect p
         inner join proiectnod pn0 on pn0.codproiect = p.codproiect and pn0.nodoriginal = 0
    where aCodProiect = 0 or p.CodProiect = aCodProiect
  ) loop
    Update proiectnod set IndexParinte = '.00' where codproiectnod = v_rec.codproiectnod;
    PERFORM pkg_proiectUpdateIndexCopii(v_rec.codproiectnod);
  end loop;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_vcodproiect</obj_name>
  <obj_hashval>67378bcaf45541b642dc8839ad8ecbbe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_vcodproiect(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PROIECT.vCodProiect', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_vnecesar</obj_name>
  <obj_hashval>de307dfc7e53337908e0ae803c4344e0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_vnecesar(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PROIECT.vNecesar', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiectcrm_sp_deleterecord</obj_name>
  <obj_hashval>b81aa6427272134b92d0975fd9b1c98b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiectcrm_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_PROIECTCRM_SP_LOCKRECORD( RecId);
  DELETE FROM PROIECTCRM WHERE CodProiectCRM = RecId;
  PERFORM NotifyModif( 2, RecId, 'PROIECTCRM');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiectcrm_sp_gotorecord</obj_name>
  <obj_hashval>0f8614fbaa28b2df20f011f8e44a5a08</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiectcrm_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_PROIECTCRM(CodProiectCRM, Denumire, Descriere, Valoare, Moneda, CodPers)
  SELECT CodProiectCRM, Denumire, Descriere, Valoare, Moneda, CodPers FROM PROIECTCRM WHERE CodProiectCRM = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiectcrm_sp_postrecords</obj_name>
  <obj_hashval>f20088c35cf6dd67be04fd06322e70b2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiectcrm_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    SELECT CodProiectCRM INTO RecId FROM TMP_PROIECTCRM;

    UPDATE PROIECTCRM
    SET
    (Denumire, Descriere, Valoare, Moneda, CodPers) = (SELECT Denumire, Descriere, Valoare, Moneda, CodPers FROM TMP_PROIECTCRM)
    WHERE
     CodProiectCRM = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_PROIECTCRM_CODPROIECTCRM') INTO RecId;

    INSERT INTO PROIECTCRM(CodProiectCRM, Denumire, Descriere, Valoare, Moneda, CodPers)
    SELECT RecId, Denumire, Descriere, Valoare, Moneda, CodPers FROM TMP_PROIECTCRM;
  END IF;

  PERFORM NotifyModif( Operation, RecId, 'NCLASEOP');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_promo_ct_monitor</obj_name>
  <obj_hashval>5200ef93eb792c50c5ab24d1526d1f9f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_promo_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_PROMO.CT_MONITOR'));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_30';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_promo_getct_monitor</obj_name>
  <obj_hashval>88092bdcee61836c73c57e78d7560c8d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_promo_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_PROMO.CT_MONITOR'));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_30';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_promo_sp_deleterecord</obj_name>
  <obj_hashval>d6731ebcd1509b09cf554c5ee20ad0da</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_promo_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCarnetDoc  numeric;
  aNrDoc      numeric;
  aCodSubunit numeric;
  aDataDoc    date;
  aDoc        varchar;
    aSyncPromoRetail varchar;
BEGIN
  --Florin 01.06.2023 - monitor
  --Florin 25.10.2021 - fixat 51760
  --Florin 23.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_promo_setct_monitor('MON_30');
  PERFORM PKG_PROMO_SP_LOCKRECORD( RecId);

  SELECT CarnetDoc, NrDoc, Subunitatea, DataStart, 'PROMO' || coalesce(NrDoc::varchar ,'') || '/' || coalesce(To_Char(DataStart,'dd.mm.yyyy'),'') || '-' || coalesce(To_Char(DataEnd,'dd.mm.yyyy'),'')
  INTO aCarnetDoc, aNrDoc, aCodSubunit, aDataDoc, aDoc
  FROM PROMO
  WHERE CodPromo = recId;

  IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_PROMO.CT_MONITOR', true)))
  THEN
    PERFORM pkg_userfirme_postlogcucommit( 'PROMO', current_setting('PKG_GLOBALS.USERNAME', true), 'S', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), aCodSubunit, aDataDoc, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  DELETE FROM PROMO1CADOUSER
  WHERE CODCADOU IN (SELECT PC.CodCadou
                     FROM PROMO1 P1 INNER JOIN PROMO1CADOU PC ON  PC.CodPromo1 = P1.CodPromo1
                     WHERE P1.CodPromo = RECID
                    );

  DELETE FROM PROMO1CADOUSER
  WHERE CODCADOU IN (SELECT PC.CodCadou FROM PROMO1CADOU PC WHERE PC.CodPromo = RECID);

  DELETE FROM PROMO1SER
  WHERE CodPromo1 IN (SELECT CodPromo1 FROM PROMO1 WHERE CodPromo = RecId);

  DELETE FROM PROMO1CADOU
  WHERE CodPromo1 IN (SELECT CodPromo1 FROM PROMO1 WHERE CodPromo = RecId);

  DELETE FROM PROMO1CADOU WHERE CodPromo = RECID;
  DELETE FROM PROMOPART   WHERE CodPromo = RECID;
  DELETE FROM PROMOSUB     WHERE CodPromo = RECID;
  DELETE FROM PROMOPRAG   WHERE CodPromo = RECID;
  DELETE FROM PROMO1      WHERE CodPromo = RecId;
  DELETE FROM PROMO       WHERE CodPromo = RecId;

  PERFORM PKG_CARNETEDOC_RELEASENUMARDOC( aCarnetDoc, aNrDoc);
  PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE( aCarnetDoc);
  PERFORM NotifyModif( 2, RecId, 'PROMO');
begin
    select
  (
  select
    PKG_CATEGCONST_GetValConstanta.WME_RESULT
  from
    PKG_CATEGCONST_GetValConstanta(null,
    'SyncPromoRetail',
    current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric,
    current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric))
into
  aSyncPromoRetail;

exception
when others then aSyncPromoRetail := '0';
end;

if aSyncPromoRetail = '1' then perform PKG_POSTRETAIL_MEMO_MODIF_PROMO_RETAIL(RECID, 1);
end if;

end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_promo_sp_insertrecord</obj_name>
  <obj_hashval>acec1d4a3492e45ff4f73c8480af9a21</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_promo_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_PROMO (CodPromo) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_promo_sp_lockrecord</obj_name>
  <obj_hashval>eb419f6ca8b11986b4d416f3efee301e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_promo_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodPromo INTO Tmp FROM PROMO WHERE CodPromo = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_punctaje_get_puncte_si_valoare</obj_name>
  <obj_hashval>953b94ca3b072a5800d530bb11c32d57</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_punctaje_get_puncte_si_valoare(INOUT adata character varying, INOUT avaloare numeric, INOUT apuncte numeric, INOUT avalpuncte numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  VALPUNCTE double precision := 0;
BEGIN
  --Florin 16.11.2020 - fixat #40859
  aPUNCTE    := 0;
  aVALPUNCTE := 0;

  FOR V_REC IN (SELECT P.CODPUNCTAJ, COALESCE( PUNCTE, 0) * TRUNC( aVALOARE / LIMITAVAL) AS PUNCTE
                FROM PUNCTAJVALDOC PV, PUNCTAJE P
                WHERE PV.CODPUNCTAJ = P.CODPUNCTAJ AND  P.TIP = 1 AND  P.DATASTART &lt;= TO_DATE( aDATA, 'DD.MM.YYYY') AND  P.DATAEND &gt;= TO_DATE( aDATA, 'DD.MM.YYYY') AND  PV.LIMITAVAL &lt;&gt; 0
               )
  LOOP
    IF  V_REC.PUNCTE &lt;&gt; 0 THEN
      aPUNCTE := aPUNCTE + V_REC.PUNCTE;
      SELECT VALACORDATA * V_REC.PUNCTE / PUNCTE INTO VALPUNCTE FROM PUNCTEUSE WHERE CODPUNCTAJ = V_REC.CODPUNCTAJ AND  COALESCE( PUNCTE, 0) &gt; 0 LIMIT 1;
      aVALPUNCTE := aVALPUNCTE + VALPUNCTE;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_punctaje_sp_deleterecord</obj_name>
  <obj_hashval>bc3ef1401a8bcb11f58702d63817bd07</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_punctaje_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodPunctaj numeric;
begin
  PERFORM PKG_PUNCTAJE_SP_LOCKRECORD( RecId);

  DELETE FROM PunctajValDoc WHERE CodPunctaj = RecId;
  DELETE FROM PuncteUse     WHERE CodPunctaj = RecId;
  DELETE FROM Punctaje      WHERE CodPunctaj = RecId;

  PERFORM NotifyModif( 2, RecId, 'PUNCTAJE');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_punctaje_sp_gotorecord</obj_name>
  <obj_hashval>4ad71b889191be3dd9bd75d7be6f889e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_punctaje_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_PUNCTAJE(CodPunctaj, denumire, datastart, dataend, tip, casademarcat, facturare)
  SELECT CodPunctaj, denumire, datastart, dataend, tip, casademarcat, facturare
  FROM Punctaje WHERE CodPunctaj = RecId;

  INSERT INTO TMP_PunctajValDoc(cod, CodPunctaj, LIMITAVAL, PUNCTE)
  SELECT cod, CodPunctaj, limitaval, puncte FROM PunctajValDoc WHERE CodPunctaj = RecId;

  INSERT INTO TMP_PuncteUse(cod, CodPunctaj, puncte, valacordata)
  SELECT cod, CodPunctaj, puncte, valacordata FROM PuncteUse WHERE CodPunctaj = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_punctaje_sp_insertrecord</obj_name>
  <obj_hashval>268f7a2fff10e15401266834c23025e1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_punctaje_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_PUNCTAJE(CodPunctaj) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_punctaje_sp_lockrecord</obj_name>
  <obj_hashval>2c458fa6ab9b4f2cc8aaed4df9faaa8e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_punctaje_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMP numeric := 0;
begin
  SELECT CodPunctaj INTO Tmp FROM PUNCTAJE WHERE CodPunctaj = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_punctaje_sp_postrecords</obj_name>
  <obj_hashval>061d3b5bc13e8b33c52a577b2adafe73</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_punctaje_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  vCOD  numeric;
  NR    numeric;
  IDX   numeric := 0;
begin
  IF  Operation = 0 THEN
    SELECT CodPunctaj INTO RecId FROM TMP_Punctaje;

    UPDATE Punctaje
    SET
    (codpunctaj, denumire, datastart, dataend, tip, casademarcat, facturare)
    =
    (SELECT codpunctaj, denumire, datastart, dataend, tip, casademarcat, facturare FROM TMP_Punctaje)
    WHERE
     CodPunctaj = RecID;

    DELETE FROM PunctajValDoc WHERE CodPunctaj = RecID AND Cod NOT IN (SELECT Cod FROM TMP_PunctajValDoc);
    DELETE FROM PuncteUse     WHERE CodPunctaj = RecID AND Cod NOT IN (SELECT Cod FROM TMP_PuncteUse);

    FOR V_REC IN (SELECT cod, codpunctaj, LIMITAVAL, puncte FROM TMP_PunctajValDoc) LOOP
      IF  v_rec.Cod &gt; 0 THEN
        UPDATE PunctajValDoc
        SET
        CodPunctaj = v_rec.CodPunctaj,
        LIMITAVAL  = v_rec.LIMITAVAL,
        Puncte     = v_rec.Puncte
        WHERE
         Cod = v_rec.Cod;
      ELSE
        SELECT NEXTVAL('SEQ_PUNCTAJVALDOC_COD') INTO vCod;

        INSERT INTO PunctajValDoc(cod, codpunctaj, LIMITAVAL, puncte)
        VALUES(vCod, RecID, v_rec.LIMITAVAL, v_rec.Puncte);
      END IF;
    END LOOP;

    FOR V_REC IN (SELECT cod, codpunctaj, puncte, valacordata FROM TMP_PuncteUse) LOOP
      IF  v_rec.Cod &gt; 0 THEN
        UPDATE PuncteUse
        SET
        Puncte      = v_rec.Puncte,
        ValAcordata = v_rec.ValAcordata
        WHERE
         Cod = v_rec.Cod;
      ELSE
        SELECT NEXTVAL('SEQ_PUNCTEUSE_COD') INTO vCod;

        INSERT INTO PuncteUse(cod, codpunctaj, puncte, valacordata)
        VALUES(vCod, RecID, v_rec.Puncte, v_rec.ValAcordata);
      END IF;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_PUNCTAJE_CODPUNCTAJ') INTO RecId;

    INSERT INTO Punctaje(codpunctaj, denumire, datastart, dataend, tip, casademarcat, facturare)
    SELECT RecId, denumire, datastart, dataend, tip, casademarcat, facturare FROM TMP_Punctaje;

    INSERT INTO PunctajValDoc(cod, codpunctaj, LIMITAVAL, puncte)
    SELECT NEXTVAL('SEQ_PUNCTAJVALDOC_COD'), RecID, LIMITAVAL, puncte FROM TMP_PunctajValDoc;

    INSERT INTO PuncteUse(cod, codpunctaj, puncte, valacordata)
    SELECT NEXTVAL('SEQ_PUNCTEUSE_COD'), RecID, puncte, valacordata FROM TMP_PuncteUse;
  END IF;

  PERFORM NotifyModif( Operation, RecId, 'PUNCTAJE');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_catp_sp_deleterecord</obj_name>
  <obj_hashval>9980566fc6dc3fa109ddcdb7113ee6d2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_catp_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_RAC_CATP_SP_LOCKRECORD( RecId);
  DELETE FROM RAC_CATP  WHERE CodRAC_CATP = RecId;
  DELETE FROM RAC_CATP1 WHERE CodRAC_CATP = RecId;
  DELETE FROM RAC_CATP2 WHERE CodRAC_CATP = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_catp_sp_gotorecord</obj_name>
  <obj_hashval>baa6fdec7f2a2b55af45dc1b6a75ee81</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_catp_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_RAC_CATP(CODRAC_CATP, CODPARTENER, CODSEDIU, CODGEST, CODSUBUNITATE, OBS, CodContract, DATASTART, DATASTOP, Abonament)
  SELECT CODRAC_CATP, CODPARTENER, CODSEDIU, CODGEST, CODSUBUNITATE, OBS, CodContract, DATASTART, DATASTOP, Abonament
  FROM RAC_CATP WHERE CodRAC_CATP = RECID;

  INSERT INTO TMP_RAC_CATP1(CODRAC_CATP1, CODRAC_CATP, CODRAC_P, OBS, TIP)
  SELECT R.CODRAC_CATP1, R.CODRAC_CATP, R.CODRAC_P, P.OBS, P.TIP
  FROM RAC_CATP1 R INNER JOIN RAC_P P ON  R.CODRAC_P = P.CODRAC_P
  WHERE CodRAC_CATP = RecId;

  INSERT INTO TMP_RAC_CATP2(codrac_catp2, codrac_catp, codGest, codSubunitate)
  SELECT codrac_catp2, codrac_catp, codGest, codSubunitate FROM RAC_CATP2 WHERE CodRac_CatP = RECID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_catp_sp_lockrecord</obj_name>
  <obj_hashval>66a67530f3546b637106e51352b3ffe9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_catp_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodRAC_CATP INTO Tmp FROM RAC_CATP WHERE CodRAC_CATP = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_catp_sp_postrecords</obj_name>
  <obj_hashval>19d501bafb24a13b55324a283e16aee8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_catp_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  Cod   numeric;
BEGIN
  --Florin 19.09.2023 - fixat 5947059471
  IF  Operation = 0 THEN
    BEGIN
      SELECT CodRAC_CATP INTO RECID FROM TMP_RAC_CATP;
    EXCEPTION WHEN OTHERS THEN
      RECID := 0;
    END;

    UPDATE RAC_CATP
    SET
    (CODPARTENER, CODSEDIU, CODGEST, CODSUBUNITATE, OBS, CodContract, DATASTART, DATASTOP, Abonament)
    =
    (SELECT CODPARTENER, CODSEDIU, CODGEST, CODSUBUNITATE, OBS, CodContract, DATASTART, DATASTOP, Abonament FROM TMP_RAC_CATP)
    WHERE
     CodRAC_CATP = RECID;

    DELETE FROM RAC_CATP2 WHERE CODRAC_CATP = RecID and CodRAC_CATP2 NOT IN (SELECT CODRAC_CATP2 FROM TMP_RAC_CATP2);
    DELETE FROM RAC_CATP1 WHERE CODRAC_CATP = RecID and CodRAC_CATP1 NOT IN (SELECT CODRAC_CATP1 FROM TMP_RAC_CATP1);

    FOR v_rec IN (SELECT * FROM TMP_RAC_CATP1) LOOP
      IF  V_Rec.Codrac_CATP1 &lt; 0 THEN
        INSERT INTO RAC_CATP1(CODRAC_CATP1, CODRAC_CATP, CODRAC_P)
        VALUES(NEXTVAL('SEQ_RAC_CATP1_COD'), RecId, V_REC.CODRAC_P);
      ELSE
        UPDATE RAC_CATP1 SET CODRAC_P = V_REC.CODRAC_P WHERE CODRAC_CATP1 = v_rec.CODRAC_CATP1;
      END IF;
    END LOOP;

    FOR v_rec IN (SELECT * FROM TMP_RAC_CATP2) LOOP
      IF  V_Rec.Codrac_CATP2 &lt; 0 THEN
        INSERT INTO RAC_CATP2(CODRAC_CATP2, CODRAC_CATP, codGest, codSubunitate)
        VALUES(NEXTVAL('SEQ_RAC_CATP2_COD'), RecId, V_REC.CODGEST, V_REC.Codsubunitate);
      ELSE
        UPDATE RAC_CATP2
        SET
        CODRAC_CatP   = V_REC.CODRAC_CatP,
        CodGest       = V_Rec.Codgest,
        CodSubunitate = V_Rec.CodSubunitate
        WHERE
         CODRAC_CATP2 = v_rec.CODRAC_CATP2;
      END IF;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_RAC_CATP_COD') INTO RecId;

    INSERT INTO RAC_CATP(CODRAC_CATP, CODPARTENER, CODSEDIU, CODGEST, CODSUBUNITATE, OBS, CodContract, DATASTART, DATASTOP, Abonament)
    SELECT RECID, CODPARTENER, CODSEDIU, CODGEST, CODSUBUNITATE, OBS, CodContract, DATASTART, DATASTOP, Abonament FROM TMP_RAC_CATP;

    INSERT INTO RAC_CATP1(CODRAC_CATP1, codRAC_CATP, CODRAC_P)
    SELECT NEXTVAL('SEQ_RAC_CATP1_COD'), RecId, CODRAC_P FROM TMP_RAC_CATP1;

    INSERT INTO RAC_CATP2(CODRAC_CATP2, codRAC_CATP, CODGest, CODSubunitate)
    SELECT NEXTVAL('SEQ_RAC_CATP2_COD'), RecId, CODGest, CODSubunitate FROM TMP_RAC_CATP2;
  END IF;

  PERFORM NotifyModif( Operation, RecId, 'RAC_CATP');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_p_sp_deleterecord</obj_name>
  <obj_hashval>094e9107b8429f0b25113f2f34ae64f6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_p_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_RAC_P_SP_LOCKRECORD( RecId);
  DELETE FROM RAC_P  WHERE CodRAC_P = RecId;
  DELETE FROM RAC_P1 WHERE CodRAC_P0 IN (SELECT CodRac_P0 FROM Rac_P0 WHERE CodRac_P = RecId);
  DELETE FROM RAC_P0 WHERE CodRAC_P = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_p_sp_gotorecord</obj_name>
  <obj_hashval>a796f4714ab4c3fe5346e98e4a682e50</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_p_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 06.07.2023 - fixat 58797
  INSERT INTO TMP_RAC_P(CODRAC_P, obs, tip, Moneda, ValFixa, i1, i2, i3, i4, i5, i6)
  SELECT CODRAC_P, obs, tip, Moneda, ValFixa, i1, i2, i3, i4, i5, i6 FROM RAC_P WHERE CodRAC_P = RECID;

  INSERT INTO TMP_RAC_P0(CODRAC_P0, codRAC_P, DATASTART)
  SELECT CODRAC_P0, codRAC_P, DATASTART FROM RAC_P0 WHERE CodRAC_P = RECID;

  INSERT INTO TMP_RAC_P1(CODRAC_P1, codRAC_P0, codgrupa, p1, p2, p3, p4, p5, P6, Fix, GARANTIE, DEN_GRUPA)
  SELECT CODRAC_P1, codRAC_P0, codgrupa, p1, p2, p3, p4, p5, P6, Fix, GARANTIE, G.DENUMIRE
  FROM RAC_P1 R INNER JOIN GrEchiv G ON  G.CODGRECHIV = R.CodGrupa
  WHERE R.CodRAC_P0 IN (SELECT CodRAC_P0 FROM TMP_RAC_P0) ORDER by CODRAC_P1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_p_sp_insertrecord</obj_name>
  <obj_hashval>4b330332937c7f74f3ac4e42e568bbd5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_p_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_RAC_P (CodRAC_P) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_p_sp_lockrecord</obj_name>
  <obj_hashval>af119a281fa1b947d8acb9bd5fc80ca0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_p_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodRAC_P INTO Tmp FROM RAC_P WHERE CodRAC_P = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_p_sp_postrecords</obj_name>
  <obj_hashval>e820a4dfdf5a5c7cfec3c25a4cc07c4c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_p_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  V_R   RECORD;
  Cod   numeric;
BEGIN
  --Florin 06.07.2023 - fixat 58787
  IF  Operation = 0 THEN
    BEGIN
      SELECT CodRAC_P INTO RECID FROM TMP_RAC_P;
    EXCEPTION WHEN OTHERS THEN
      RECID := 0;
    END;

    UPDATE RAC_P
    SET (obs, tip, Moneda, ValFixa, i1, i2, i3, i4, i5, i6) = (SELECT obs, tip, Moneda, ValFixa, i1, i2, i3, i4, i5, i6 FROM TMP_RAC_P)
    WHERE CodRAC_P = RECID;

    FOR V_Rec IN (SELECT CODRAC_P0 FROM RAC_P0 WHERE CODRAC_P = RecID and Codrac_P0 NOT IN (SELECT CODRAC_P0 FROM TMP_RAC_P0) ) LOOP
      DELETE FROM RAC_P0 WHERE CODRAC_P0 = V_Rec.CODRAC_P0;
      DELETE FROM RAC_P1 WHERE CODRAC_P0 = V_Rec.CODRAC_P0;
    END LOOP;

    FOR V_Rec IN (SELECT CODRAC_P0 FROM TMP_RAC_P0 WHERE CODRAC_P0 &gt; 0) LOOP
      DELETE FROM RAC_P1 WHERE CODRAC_P0 = v_Rec.Codrac_P0 and CodRac_P1 NOT IN (SELECT CODRAC_P1 FROM TMP_RAC_P1);
    END LOOP;

    FOR v_rec IN (SELECT * FROM TMP_RAC_P0) LOOP
      IF  V_Rec.Codrac_P0 &lt; 0 THEN
        SELECT NEXTVAL('SEQ_RAC_P0_COD') INTO COD;

        INSERT INTO RAC_P0(CODRAC_P0, codRAC_P, DATASTART) VALUES(COD, RecId, V_REC.DATASTART);

        INSERT INTO RAC_P1(CODRAC_P1, codRAC_P0, codgrupa, p1, p2, p3, p4, p5, P6, GARANTIE, Fix)
        SELECT NEXTVAL('SEQ_RAC_P1_COD'), Cod, codgrupa, p1, p2, p3, p4, p5, P6, GARANTIE, Fix FROM TMP_RAC_P1 WHERE CodRAC_P0 = V_Rec.Codrac_P0;
      ELSE
        UPDATE RAC_P0 SET DATASTART = V_REC. DATASTART WHERE CODRAC_P0 = v_rec.CODRAC_P0;
        Cod := V_Rec.CodRAC_P0;

        FOR v_r IN (SELECT * FROM TMP_RAC_P1 WHERE CODRAC_P0 = Cod and  CODRAC_P1 &gt; 0) LOOP
          UPDATE RAC_P1
          SET
          codgrupa = V_R.codgrupa,
          p1       = V_R. p1,
          p2       = V_R. p2,
          p3       = V_R. p3,
          p4       = V_R. p4,
          p5       = V_R. p5,
          P6       = V_R. P6,
          GARANTIE = V_R. GARANTIE,
          Fix = V_R.Fix
          WHERE
           CODRAC_P1 = v_r.CODRAC_P1;
        END LOOP;

        FOR v_r IN (SELECT * FROM TMP_RAC_P1 WHERE CODRAC_P0 = Cod and  CODRAC_P1 &lt; 0) LOOP
          INSERT INTO RAC_P1(CODRAC_P1, codRAC_P0, codgrupa, p1, p2, p3, p4, p5, P6, GARANTIE, Fix)
          VALUES(NEXTVAL('SEQ_RAC_P1_COD'), Cod, v_r.codgrupa, v_r.p1, v_r.p2, v_r.p3, v_r.p4, v_r.p5, v_r.P6, v_r.GARANTIE, v_r.Fix);
        END LOOP;
      END IF;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_RAC_P_COD') INTO RecId;

    INSERT INTO RAC_P(CODRAC_P, obs, tip, Moneda, ValFixa, i1, i2, i3, i4, i5, i6)
    SELECT RECID, obs, tip, Moneda, ValFixa, i1, i2, i3, i4, i5, i6 FROM TMP_RAC_P;

    FOR v_rec IN (SELECT * FROM TMP_RAC_P0) LOOP
      SELECT NEXTVAL('SEQ_RAC_P0_COD') INTO COD;

      INSERT INTO RAC_P0(CODRAC_P0, codRAC_P, DATASTART) VALUES(COD, RecId, V_REC.DATASTART);

      INSERT INTO RAC_P1(CODRAC_P1, codRAC_P0, codgrupa, p1, p2, p3, p4, p5, P6, GARANTIE, Fix)
      SELECT NEXTVAL('SEQ_RAC_P1_COD'), Cod, codgrupa, p1, p2, p3, p4, p5, P6, GARANTIE, Fix FROM TMP_RAC_P1 WHERE CodRAC_P0 = V_Rec.Codrac_P0;
    END LOOP;
  END IF;

  PERFORM NotifyModif( Operation, RecId, 'RAC_P');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_rez_ct_monitor</obj_name>
  <obj_hashval>c0bc47b2e692b1532df0d357794f6bb8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_rez_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_RAC_REZ.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_14';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_rez_datapornire</obj_name>
  <obj_hashval>7999de38e59e3e961806c7f0a27f5a28</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_rez_datapornire(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_RAC_REZ.DataPornire'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_rez_fill_rac_tmp</obj_name>
  <obj_hashval>674e4180decd08cac4ff1bb8f9dbf2b0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_rez_fill_rac_tmp()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 16.08.2021 - sinc.Oracle din 14.08.2021
  DELETE FROM TMP_RAC_CARS;
  DELETE FROM TMP_RAC_AUTO_CEN;
  DELETE FROM TMP_RAC_AUTO;
  DELETE FROM TMP_RAC_EMU;

  INSERT INTO TMP_RAC_CARS     SELECT * FROM RAC_CARS WHERE Extern = 0 and  Generic = 0 and  CodGest &gt; 0 and  Ind = 1;
  INSERT INTO TMP_RAC_AUTO_CEN SELECT * FROM RAC_AUTO_CEN;
  INSERT INTO TMP_RAC_AUTO     SELECT * FROM RAC_AUTO;
  INSERT INTO TMP_RAC_EMU      SELECT * FROM RAC_EMU;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_rez_getct_monitor</obj_name>
  <obj_hashval>6f430b3674d6b9a3e064f06c0cab6b83</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_rez_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_RAC_REZ.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_14';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_rez_getisdatacuora</obj_name>
  <obj_hashval>2944245cbd46e69a6e7dea57526f13fe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_rez_getisdatacuora(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_RAC_REZ.IsDataCuOra')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_rez_init_reparaparcg</obj_name>
  <obj_hashval>ede0787fae3a0d1786689d4604d06c19</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_rez_init_reparaparcg()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 16.08.2021 - sinc.Oracle din 14.08.2021
  PERFORM pkg_rac_rez_SET_RAC_DATASTART( '17.08.2016 01:01');
  DELETE FROM TMP_V_Auto;
  INSERT INTO TMP_V_Auto(CodAuto, CodGest, q)
  SELECT * FROM (SELECT CodAuto, CodGest, CodClasa, Sum( Q) q FROM V_AUTO GROUP BY CodAuto, codgest, CodClasa) A_PG
  WHERE q = -1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_rez_init_tmp_v_auto</obj_name>
  <obj_hashval>4569f62a8fcc7cda53363ccb915526c7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_rez_init_tmp_v_auto(zi1 character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 16.08.2021 - sinc.Oracle din 14.08.2021
  PERFORM pkg_rac_rez_SET_RAC_DATASTART( Zi1);
  DELETE FROM TMP_V_Auto;
  INSERT INTO TMP_V_Auto
  SELECT * FROM (SELECT CodAuto, CodGest, CodClasa, Q, DATASTART, DATASTOP FROM V_AUTO) A_PG;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_rez_rac_datacuora</obj_name>
  <obj_hashval>e0a8260c42f65b68747da1e1a63bdcb2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_rez_rac_datacuora(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  WME_Result :=  TO_NUMBER(current_setting('PKG_RAC_REZ.IsDataCuOra',true),'999999999999999999');
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_rez_rac_datastart</obj_name>
  <obj_hashval>b9002a31693b1e875f8be61ebc397c35</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_rez_rac_datastart(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  WME_Result :=  to_date(current_setting('PKG_RAC_REZ.DATAPORNIRE',true), 'DD.MM.YYYY hh24:mi');
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_rez_rac_libere</obj_name>
  <obj_hashval>6911354b74d2abea86aa6b7ac2ba49cb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_rez_rac_libere(INOUT wme_result refcursor, INOUT acodcomanda numeric, INOUT acodcomanda1 numeric, INOUT acodobiect numeric, INOUT zi1 character varying, INOUT zi2 character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  crs       REFCURSOR;
  aInd      numeric;
  GrupaAuto numeric;
begin
  GrupaAuto := (SELECT WME_RESULT FROM PKG_RAC_REZ_IndexGrupaAuto(NULL,NULL));
  BEGIN
    SELECT COALESCE( G.Ind, 0)
    INTO aInd
    FROM NEchiv E INNER JOIN GrEchiv G ON  G.CODGRECHIV = E.CodGrupa
    WHERE E.Codobiect = aCodObiect;
  EXCEPTION WHEN others THEN
    aInd := 0;
  END;

  IF  aInd = GrupaAuto THEN
    BEGIN
      PERFORM PKG_RAC_REZ_Init_Tmp_V_Auto( zi1);

      OPEN crs FOR
      WITH
      Masini AS ( SELECT X.CodGest, COALESCE( E.CodGrupa, 0) CodGrupa, Sum( X.Q) Total
                  FROM TMP_V_AUTO X
                      INNER JOIN NParcAut P ON  P.Codnparcaut = X.CodAuto
                      LEFT  JOIN NEchiv   E ON  E.Codobiect   = P.CodArt
                  WHERE x.Q &lt;&gt; 0
                  GROUP BY X.CodGest, COALESCE( E.CodGrupa, 0)
                ),
      ComenziRAC AS ( SELECT c.codcomanda, R.CodGestSursa CodGestTransf, R.CodGestSursa, R.TipRezervare, COALESCE( C.MijlTransp, 0) CodAuto
                      FROM Comanda c
                          LEFT  JOIN NGest   G2 ON  G2.CodGest   = C.CodGest
                          INNER JOIN RAC_REZ R  ON  R.codcomanda = c.codcomanda
                      WHERE c.codcomanda &gt; 0 and  c.tipdoc = 94 and  C.CodComanda &lt;&gt; aCodComanda and  COALESCE( C.Operat, 0) = 1 and  COALESCE( R.Predat, 0) = 0 and  COALESCE( R.CodPartExt, 0) = 0 and (  (  TO_DATE( Zi1, 'DD.MM.YYYY hh24:mi') BETWEEN R.DataStart AND R.DataStop)  or (  TO_DATE( Zi2, 'DD.MM.YYYY hh24:mi') BETWEEN R.DataStart AND R.DataStop)  or (  R.DataStart BETWEEN TO_DATE( Zi1, 'DD.MM.YYYY hh24:mi') AND TO_DATE( Zi2, 'DD.MM.YYYY hh24:mi'))  or (  R.DataStop BETWEEN TO_DATE( Zi1, 'DD.MM.YYYY hh24:mi') AND TO_DATE( Zi2, 'DD.MM.YYYY hh24:mi')) )
                      ),
      Rezervari AS ( SELECT x.CodGestTransf, x.CodGestSursa, x.CodGrupa, COALESCE( M1.Total, 0) TotalS, COALESCE( M2.Total, 0) TotalT, Sum( x.Ocupate) Ocupate
                     FROM ( SELECT CodGestTransf, CodGestSursa, E.CodGrupa, C1.Cantacceptat Ocupate
                            FROM comanda1 c1
                                INNER JOIN comenzirac c ON  c.codcomanda = c1.codcomanda
                                INNER JOIN NEchiv     E ON  E.Codobiect  = c1.CodObiect
                            WHERE C.CodAuto = 0 and (NOT (C.TipRezervare IN (1, 6)) )  and  C1.CANTACCEPTAT = 1
                            union ALL
                            SELECT CodGestTransf, CodGestSursa, E.CodGrupa, 1 Ocupate
                            FROM comenzirac c
                                INNER JOIN NParcAut p ON  p.CodNparcAut = c.CodAuto
                                INNER JOIN NEchiv   E ON  E.Codobiect   = p.CodArt
                            WHERE C.CodAuto &gt; 0
                          ) X
                          LEFT JOIN Masini M1 ON  M1.CodGrupa = x.CodGrupa and  M1.CodGest = COALESCE( x.CodGestSursa, 0)
                          LEFT JOIN Masini M2 ON  M2.CodGrupa = x.CodGrupa and  M2.CodGest = COALESCE( x.CodGestTransf, 0)
                      GROUP BY x.CodGestTransf, x.CodGestSursa, x.CodGrupa, COALESCE( M1.Total, 0), COALESCE( M2.Total, 0)
                    )
      SELECT aCodComanda1 AS CodComanda1, TO_DATE( Zi1, 'DD.MM.YYYY hh24:mi') DataStart, TO_DATE( Zi2, 'DD.MM.YYYY hh24:mi') DataStop, NG.CodSubunit,
             X.CodGest, X.CodGrupa, X.Total, COALESCE( X.Ocupate, 0) Ocupate, X.Total - COALESCE( X.Ocupate, 0) Libere, S.Den_Subunit, NG.Den_Gest, G.DENUMIRE DenClasa
      FROM (SELECT CodGest, CodGrupa, Total, Sum( Ocupate) Ocupate
            FROM (SELECT CodGest, CodGrupa, Total, 0 Ocupate FROM Masini
                  union ALL
                  SELECT CodGestSursa CodGest , CodGrupa, TotalS Total,  Ocupate FROM REZERVARI
                  union ALL
                  SELECT CodGestTransf CodGest, CodGrupa, TotalT Total,  Ocupate FROM REZERVARI WHERE CodGestTransf &lt;&gt; 0
                  union ALL
                  SELECT CodGestSursa CodGest , CodGrupa, TotalS Total, -Ocupate FROM REZERVARI WHERE CodGestTransf &lt;&gt; 0
                 ) A_PG
            GROUP BY CodGest, CodGrupa, Total
            ) X
          INNER JOIN GrEchiv  G  ON  G.CODGRECHIV = X.CodGrupa
          INNER JOIN NGest    NG ON  NG.CodGest   = X.CodGest
          INNER JOIN NSubunit S  ON  s.CodSubunit = NG.CodSubunit
      WHERE COALESCE( G.Ind, 0) = aInd;
    EXCEPTION WHEN others THEN
      OPEN crs FOR SELECT -1 CodCfg;
    END;
  ELSE
    BEGIN
      OPEN crs FOR
      WITH
      Masini AS ( SELECT NG.CodGest, E.CodGrupa, Sum( NS.Rest) Total
                  FROM nirstoc ns
                      INNER JOIN Nir     N   ON  N.CodNir       = NS.CodNir
                      INNER JOIN NGest   NG  ON  N.Gest         = NG.CodGest
                      INNER JOIN NEchiv  E   ON  E.Codobiect    = ns.CodObiect
                      INNER JOIN GrEchiv GrE ON  GrE.CODGRECHIV = E.CodGrupa
                  WHERE COALESCE( GrE.Ind, 0) = aInd
                  GROUP BY NG.CodGest, E.CodGrupa
                ),
      ComenziRAC AS ( SELECT c.codcomanda, COALESCE( C.CodGest, 0) CodGestTransf, R.CodGestSursa, R.TipRezervare, COALESCE( C.MijlTransp, 0) CodAuto
                      FROM Comanda c
                      LEFT  JOIN NGest G2 ON  G2.CodGest = C.CodGest
                      INNER JOIN RAC_REZ R ON  R.codcomanda = c.codcomanda
                      WHERE c.codcomanda &gt; 0 and  c.tipdoc = 94 and  C.CodComanda &lt;&gt; aCodComanda and  COALESCE( C.Operat, 0) = 1 and  COALESCE( R.Predat, 0) = 0 and  COALESCE( R.CodPartExt, 0) = 0 and (  (  TO_DATE( Zi1, 'DD.MM.YYYY hh24:mi') BETWEEN R.DataStart AND R.DataStop)  or (  TO_DATE( Zi2, 'DD.MM.YYYY hh24:mi') BETWEEN R.DataStart AND R.DataStop)  or (  R.DataStart BETWEEN TO_DATE( Zi1, 'DD.MM.YYYY hh24:mi') AND TO_DATE( Zi2, 'DD.MM.YYYY hh24:mi'))  or (  R.DataStop BETWEEN TO_DATE( Zi1, 'DD.MM.YYYY hh24:mi') AND TO_DATE( Zi2, 'DD.MM.YYYY hh24:mi')) )
                    ),
      Rezervari AS (SELECT x.CodGestTransf, x.CodGestSursa, x.CodGrupa, COALESCE( M1.Total, 0) TotalS, COALESCE( M2.Total, 0) TotalT, Sum( x.Ocupate) Ocupate
                    FROM (SELECT CodGestTransf, CodGestSursa, E.CodGrupa, C1.Cantacceptat Ocupate
                          FROM comanda1 c1
                              INNER JOIN comenzirac c ON  c.codcomanda = c1.codcomanda
                              INNER JOIN NEchiv     E ON  E.Codobiect  = c1.CodObiect
                          WHERE NOT (  C.TipRezervare IN (1, 8))
                          union ALL
                          SELECT CodGestTransf, CodGestSursa, E.CodGrupa, 1 Ocupate
                          FROM comenzirac c
                              INNER JOIN NParcAut p ON  p.CodNparcAut = c.CodAuto
                              INNER JOIN NEchiv   E ON  E.Codobiect   = p.CodArt
                          WHERE C.CodAuto &gt; 0 and C.TipRezervare IN (1, 8)
                         ) X
                        LEFT JOIN Masini M1 ON  M1.CodGrupa = x.CodGrupa and  M1.CodGest = COALESCE( x.CodGestSursa, 0)
                        LEFT JOIN Masini M2 ON  M2.CodGrupa = x.CodGrupa and  M2.CodGest = COALESCE( x.CodGestTransf, 0)
                    GROUP BY x.CodGestTransf, x.CodGestSursa, x.CodGrupa, COALESCE( M1.Total, 0), COALESCE( M2.Total, 0)
                   )
      SELECT aCodComanda1 AS CodComanda1, TO_DATE( Zi1, 'DD.MM.YYYY hh24:mi') DataStart, TO_DATE( Zi2, 'DD.MM.YYYY hh24:mi') DataStop, NG.CodSubunit,
             X.CodGest, X.CodGrupa, X.Total, COALESCE( X.Ocupate, 0) Ocupate, X.Total - COALESCE( X.Ocupate, 0) Libere, S.Den_Subunit, NG.Den_Gest, G.DENUMIRE DenClasa
      FROM (SELECT CodGest, CodGrupa, Total, Sum( Ocupate) Ocupate
            FROM (SELECT CodGest, CodGrupa, Total, 0 Ocupate FROM Masini
                  union ALL
                  SELECT CodGestSursa CodGest, CodGrupa, TotalS Total, Ocupate FROM REZERVARI
                  union ALL
                  SELECT CodGestTransf CodGest, CodGrupa, TotalT Total, Ocupate FROM REZERVARI WHERE CodGestTransf &lt;&gt; 0
                  union ALL
                  SELECT CodGestSursa CodGest, CodGrupa, TotalS Total, -Ocupate FROM REZERVARI WHERE CodGestTransf &lt;&gt; 0
                 ) B_PG
            GROUP BY CodGest, CodGrupa, Total
            ) X
          INNER JOIN GrEchiv  G  ON  G.CODGRECHIV = X.CodGrupa
          INNER JOIN NGest    NG ON  NG.CodGest   = X.CodGest
          INNER JOIN NSubunit S  ON  s.CodSubunit = NG.CodSubunit
      WHERE COALESCE( G.Ind, 0) = aInd;
    EXCEPTION WHEN others THEN
      OPEN crs FOR SELECT -1 CodCfg;
    END;
  END IF;

  WME_Result :=  crs;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_rez_rac_ocupate</obj_name>
  <obj_hashval>36299f9a5ed133e08952afc08951adbb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_rez_rac_ocupate(INOUT wme_result refcursor, INOUT acodcomanda numeric, INOUT acodcomanda1 numeric, INOUT acodobiect numeric, INOUT zi character varying, INOUT atip numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  crs  REFCURSOR;
  aInd numeric;
begin
  BEGIN
    SELECT COALESCE( G.Ind, 0)
    INTO aInd
    FROM NEchiv E INNER JOIN GrEchiv G ON  G.CODGRECHIV = E.CodGrupa
    WHERE E.Codobiect = aCodObiect;
  EXCEPTION WHEN others THEN
    aInd := 0;
  END;

  BEGIN
    OPEN crs FOR
    SELECT aCodComanda1 AS CodComanda1, C.Seriadoc || C.Nrdoc || '/' || C.Datadoc Cmd, C1.CANTACCEPTAT Ocupate, R.DataStart, R.DataStop,
           TO_DATE( Zi, 'DD.MM.YYYY hh24:mi') Ziua, S1.CodSubunit CodSubunitPrel, S2.CodSubunit CodSubunitLivr, S1.Den_Subunit SubunitPrel,
           S2.Den_Subunit SubunitLivr, G1.Den_Gest GestPrel, G2.Den_Gest GestLivr, G1.CodGest CodGestPrel, G2.CodGest CodGestLivr, G.DENUMIRE DenClasa
    FROM comanda1 c1
        INNER JOIN Comanda  c  ON  c.codcomanda  = c1.codcomanda
        INNER JOIN RAC_REZ  R  ON  R.codcomanda  = c.codcomanda
        INNER JOIN NGest    G1 ON  G1.codGest    = COALESCE( R.CodGestSursa, 0)
        INNER JOIN NGest    G2 ON  G2.codGest    = COALESCE( R.CodGestDest, 0)
        INNER JOIN Nsubunit S1 ON  S1.codSubunit = G1.CodSubunit
        INNER JOIN Nsubunit S2 ON  S2.codSubunit = G2.CodSubunit
        INNER JOIN NEchiv   E  ON  E.Codobiect   = c1.CodObiect
        INNER JOIN GrEchiv  G  ON  G.CODGRECHIV  = E.CodGrupa
    WHERE c.codcomanda &gt; 0 and  c.Operat = 1 and  c.tipdoc = 94 and  COALESCE( G.Ind, 0) = aInd and  C.CodComanda &lt;&gt; aCodComanda and  COALESCE( R.Predat, 0) = 0
      and (  (aTip = 0 and  Trunc(TO_DATE( Zi, 'DD.MM.YYYY hh24:mi')) = Trunc(R.DataStart))
              or
             (aTip = 1 and  Trunc( TO_DATE( Zi, 'DD.MM.YYYY hh24:mi')) = Trunc( R.DataStop))
          ) ;
  EXCEPTION WHEN others THEN
    OPEN crs FOR SELECT -1 CodCfg;
  END;

  WME_Result :=  crs;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_rez_rac_reparatii</obj_name>
  <obj_hashval>993ab2e86d3e0a877d06edf39912b9d0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_rez_rac_reparatii(INOUT wme_result refcursor, INOUT acodauto numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  crs  REFCURSOR;
  aInd numeric;
begin
  BEGIN
    OPEN crs FOR
    SELECT CODCOMANDA3, c2.CODCOMANDA2, CANT, PRET, C3.TIP, EXECUTAT, garantie, CODLUCRARE, CODOPERATIE, c2.CodRezervare, Data, Op.CodServiciu
    FROM COMANDA2 c2
        INNER JOIN COMANDA3 C3 ON  C2.CodComanda2 = C3.CodComanda2
        INNER JOIN NOper    Op ON  Op.CodOp       = C3.CodOperatie
    WHERE c2.codNParcAut = aCodAuto and  COALESCE( Executat, 0) &lt;&gt; 1;
  EXCEPTION WHEN others THEN
    OPEN crs FOR SELECT -1 CodCfg;
  END;

  WME_Result :=  crs;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_rez_refacereparcg</obj_name>
  <obj_hashval>8d57d37e6a23c020adc3cbf06647ecf1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_rez_refacereparcg()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aData date := TO_DATE( '01.07.2014 00:01', 'DD.MM.YYYY hh24:mi');
  N     numeric;
begin
  DELETE FROM nparcg;
  INSERT INTO NParcG(CODNParcG, CODNPARCAUT, CodGest, Status, Data)
  SELECT NEXTVAL('SEQ_NPARCG_CODNPARCG'), CodNParcAut, CodGest, Inactiv, aData FROM nparcaut;

  FOR v_rec IN (SELECT P.Inactiv, C.Mijltransp, R.*
                FROM Rac_rez r
                    INNER JOIN Comanda  c ON  c.codcomanda  = r.codcomanda
                    INNER JOIN NParcAut p ON  P.Codnparcaut = C.Mijltransp
                WHERE c.codcomanda &gt; 0 and  r.TipRezervare = 7 and  COALESCE( c.Tiptranzactie, 0) = 1 and  COALESCE( r.predat, 0) = 1
                ORDER BY r.datapred
               )
  LOOP
    DELETE FROM NParcG WHERE CodNparcAut = v_rec.mijltransp;
  END LOOP;

  FOR v_rec IN (SELECT P.Inactiv, C.Mijltransp, R.*
                FROM Rac_rez r
                    INNER JOIN Comanda  c ON  c.codcomanda  = r.codcomanda
                    INNER JOIN NParcAut p ON  P.Codnparcaut = C.Mijltransp
                WHERE c.codcomanda &gt; 0 and  r.TipRezervare = 7 and  COALESCE( r.predat, 0) = 1
                ORDER BY r.datapred
               )
  LOOP
    SELECT Count( *) INTO N FROM NParcG WHERE CodNparcAut = v_rec.mijltransp;
    IF  N = 0 THEN
      INSERT INTO NParcG(CODNParcG, CODNPARCAUT, CodGest, Status, Data)
      VALUES(NEXTVAL('SEQ_NPARCG_CODNPARCG'), v_rec.Mijltransp, v_rec.CodGestSursa, v_rec.Inactiv, aData);
    END IF;

    INSERT INTO NParcG(CODNParcG, CODNPARCAUT, CodGest, Status, Data, CODCMD)
    VALUES(NEXTVAL('SEQ_NPARCG_CODNPARCG'), v_rec.Mijltransp, v_rec.CodGestDest, v_rec.Inactiv, v_rec.DataPred, v_rec.CodComanda);

    UPDATE nparcAut SET CodGest = v_rec.CodGestDest WHERE CodNparcAut = v_rec.mijltransp;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_rez_reparaparcg</obj_name>
  <obj_hashval>cf46a431b9f22ea1be42fc45ff173324</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_rez_reparaparcg()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  X_REC RECORD;
  n     numeric;
begin
  PERFORM PKG_RAC_REZ_Init_ReparaParcG();

  FOR x_rec IN (SELECT * FROM TMP_V_AUTO) LOOP
    UPDATE nparcaut SET codgest = x_rec.Codgest WHERE codnparcaut = x_rec.codauto;
    UPDATE nparcg   SET codgest = x_rec.Codgest WHERE codnparcaut = x_rec.codauto
      and  Data = (SELECT Min( Data) FROM nparcg WHERE codnparcaut = x_rec.codauto);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_rez_set_rac_datastart</obj_name>
  <obj_hashval>7773ce22f7365a14957aa8589b3dff29</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_rez_set_rac_datastart(adata character varying, dotmp integer DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  IndGrupa     NUMERIC;
  DATAPORNIRE timestamp;
BEGIN
  --Adina 16.08.2021 - sinc.Oracle din 14.08.2021
  --Adina 02.10.2020
  perform set_config('PKG_RAC_REZ.DATAPORNIRE',to_char(TO_DATE( aData, 'DD.MM.YYYY hh24:mi'), 'DD.MM.YYYY hh24:mi'),false);
  perform set_config('PKG_RAC_REZ.IsDataCuOra',to_char(1,'999999999999999999'),false);

  DATAPORNIRE := to_timestamp(current_setting('PKG_RAC_REZ.DATAPORNIRE',true), 'DD.MM.YYYY hh24:mi');

  IF  DATAPORNIRE = Date_Trunc('day', DATAPORNIRE) THEN
    perform set_config('PKG_RAC_REZ.IsDataCuOra',to_char(0,'999999999999999999'),false);
  END IF;

  IndGrupa := (SELECT WME_RESULT FROM PKG_RAC_REZ_IndexGrupaAuto(NULL,NULL));

  if DoTmp = 1 then
    DELETE FROM TMP_V_RAC_CARS;

    INSERT INTO TMP_V_RAC_CARS
    SELECT A.CodAuto, S.Den_Subunit Subunitate, G.Den_Gest Gestiune, A.Clasa, A.NrAuto, A.Marca, A.Model, A.Inactiv, A.CodGest, G.CODCLASA, A.CodGrEchiv, A.AnF, A.Data
    FROM   V_RAC_CARS A
          INNER JOIN NGest G    ON  G.codGest    = A.CodGest
          INNER JOIN Nsubunit S ON  S.codSubunit = G.CodSubunit
    WHERE A.Extern = 0 and  A.Generic = 0 and  A.CodGest &gt; 0 and  Ind = IndGrupa;
  end if;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_rez_set_rac_datastart_xx</obj_name>
  <obj_hashval>c0d680308cdb673ed97dae3f1142f1cb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_rez_set_rac_datastart_xx(adata character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  IndGrupa     NUMERIC;
  DATAPORNIRE date;
BEGIN
  --Adina 02.10.2020
  perform set_config('PKG_RAC_REZ.DATAPORNIRE',to_char(TO_DATE( aData, 'DD.MM.YYYY hh24:mi'), 'DD.MM.YYYY hh24:mi'),false);
  perform set_config('PKG_RAC_REZ.IsDataCuOra',to_char(1,'999999999999999999'),false);

  DATAPORNIRE := to_date(current_setting('PKG_RAC_REZ.DataPornire',true), 'DD.MM.YYYY hh24:mi');

  IF  DATAPORNIRE = Date_Trunc('day', DATAPORNIRE) THEN
    perform set_config('PKG_RAC_REZ.IsDataCuOra',to_char(0,'999999999999999999'),false);
  END IF;

  IndGrupa := (SELECT WME_RESULT FROM PKG_RAC_REZ_IndexGrupaAuto(NULL,NULL));

  DELETE FROM TMP_V_RAC_CARS;

  INSERT INTO TMP_V_RAC_CARS
  SELECT A.CodAuto, S.Den_Subunit Subunitate, G.Den_Gest Gestiune, A.Clasa, A.NrAuto, A.Marca, A.Model, A.Inactiv, A.CodGest, A.CodGrEchiv, A.AnF, A.Data
  FROM   V_RAC_CARS A
        INNER JOIN NGest G    ON  G.codGest = A.CodGest
        INNER JOIN Nsubunit S ON  S.codSubunit = G.CodSubunit
  WHERE A.Extern = 0 and  A.Generic = 0 and  A.CodGest &gt; 0 and  Ind = IndGrupa;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_rez_sp_deleterecord</obj_name>
  <obj_hashval>8095ba315e0b8856f36af6d724d8dce0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_rez_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_RAC_REZ_SP_LOCKRECORD( RecId);
  DELETE FROM RAC_REZ WHERE CodRAC_REZ = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_rez_sp_gotorecord</obj_name>
  <obj_hashval>69f606134d002632e4c2e82ca3fbea0f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_rez_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_RAC_REZ(CODRAC_REZ, CodComanda, Telefon)
  SELECT CODRAC_REZ, CodComanda, Telefon FROM RAC_REZ WHERE CodRAC_REZ = RECID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_rez_sp_insertrecord</obj_name>
  <obj_hashval>2e4b35db0526777b31532c63ee4f5786</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_rez_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_RAC_REZ (CodRAC_REZ) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_rez_sp_lockrecord</obj_name>
  <obj_hashval>14e273dc00981a29d29c1c955ad6cce0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_rez_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodRAC_REZ INTO Tmp FROM RAC_REZ WHERE CodRAC_REZ = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_rez_sp_postrecords</obj_name>
  <obj_hashval>ac874a775ed7a5cc588fd71f21405126</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_rez_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    BEGIN
      SELECT CodRAC_REZ INTO RECID FROM TMP_RAC_REZ;
    EXCEPTION WHEN OTHERS THEN
      RECID := 0;
    END;

    UPDATE RAC_REZ
    SET
    (CodComanda, Telefon) = (SELECT CodComanda, Telefon FROM TMP_RAC_REZ)
    WHERE CodRAC_REZ = RECID;
  ELSE
    SELECT NEXTVAL('SEQ_RAC_REZ_COD') INTO RecId;

    INSERT INTO RAC_REZ(CodRAC_REZ, CodComanda, CodTIPASIG)
    SELECT RECID, CodComanda, CodTIPASIG FROM TMP_RAC_REZ;
  END IF;

  PERFORM NotifyModif( Operation, RecId, 'RAC_REZ');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_raportp_carnetdoc_i</obj_name>
  <obj_hashval>80f5add756f84c8e7e7b1f6478f6b57a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_raportp_carnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_RAPORTP.CARNETDOC_I', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_raportp_ct_monitor</obj_name>
  <obj_hashval>a60ba9f1af1b952b2553c204195ab9ab</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_raportp_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_RAPORTP.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_xx';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_raportp_getcarnetdoc_i</obj_name>
  <obj_hashval>69af46d16c72de96ac011cab9d95fba2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_raportp_getcarnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_RAPORTP.CARNETDOC_I', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_raportp_getct_monitor</obj_name>
  <obj_hashval>cea95febfc92c076bc64bda9785a027e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_raportp_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_RAPORTP.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_xx';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_raportp_getnrdoc_i</obj_name>
  <obj_hashval>eda9fd68d70a9bacf07ab058bc200909</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_raportp_getnrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_RAPORTP.NRDOC_I', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_raportp_mutacant</obj_name>
  <obj_hashval>b2453f50d746457393bff7c7328ff545</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_raportp_mutacant()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM tmp_comanda1;
  INSERT INTO tmp_comanda1(codcomanda1, cantcomandat, cantacceptat)
  SELECT codraportp2, realizat, rebut FROM raportp2;

  UPDATE raportp2
  SET
  realizat = null,
  rebut    = null;

  BEGIN
    EXECUTE 'alter table raportp2 ALTER column realizat TYPE numeric(13,7)';
    EXECUTE 'alter table raportp2 ALTER column rebut TYPE numeric(13,7)';
  EXCEPTION WHEN others THEN
    null;
  END;

  UPDATE raportp2 r2
  SET
  realizat = (SELECT t2.cantcomandat FROM tmp_comanda1 t2 WHERE r2.codraportp2 = t2.codcomanda1);

  UPDATE raportp2 r2
  SET
  rebut = (SELECT t2.cantacceptat FROM tmp_comanda1 t2 WHERE r2.codraportp2 = t2.codcomanda1);

  DELETE FROM tmp_comanda1;

  BEGIN
    EXECUTE 'alter table tmp_raportp2 ALTER column realizat TYPE numeric(13,7)';
    EXECUTE 'alter table tmp_raportp2 ALTER column rebut TYPE numeric(13,7)';
  EXCEPTION WHEN others THEN
    null;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_raportp_setnrdoc_i</obj_name>
  <obj_hashval>38d97930ff2804251a6c4512eb7e0aa7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_raportp_setnrdoc_i(anrdoc numeric, acarnet numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_RAPORTP.CARNETDOC_I',to_char(aCARNET,'999999999999999999'),false);
perform set_config('PKG_RAPORTP.NRDOC_I',to_char(aNRDOC,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_raportp_sp_deleterecord</obj_name>
  <obj_hashval>3ac482595bd2195a540231ef407ebffa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_raportp_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  aNrDoc      numeric;
  aCodSubunit numeric;
  aDataDoc    date;
  aDoc        varchar;
  aCarnetDoc  numeric;
  aCount      numeric := 0;
BEGIN
  --Florin 02.04.2024 - sinc. Oracle
  --Florin 01.06.2023 - monitor
  --Florin 15.02.2021 - fixat 41936
  perform pkg_raportp_setct_monitor('MON_xx');
  PERFORM PKG_RAPORTP_SP_LOCKRECORD(RecId);
  PERFORM PKG_CFGTABLES_EXT_DELETERECORD (recId, 63);

  SELECT NrDoc, Subunitatea, DataI, 'RaportP ' || coalesce(NrDoc::varchar ,'') || '/' || coalesce(To_Char(dataI,'dd.mm.yyyy'),'') || '-' || coalesce(To_Char(DataS,'dd.mm.yyyy'),''), CarnetDoc
  INTO aNrDoc, aCodSubunit, aDataDoc, aDoc, aCarnetDoc
  FROM RaportP WHERE CodRaportP = recId;

  IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_RAPORTP.CT_MONITOR', true)))
  THEN
    PERFORM pkg_userfirme_postlogcucommit('RaportP', current_setting('PKG_GLOBALS.USERNAME', true), 'S', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), aCodSubunit, aDataDoc, aDoc, null, current_setting('PKG_GLOBALS.EXE_VERSION', true));
  END IF;

  FOR v_rec IN (SELECT coalesce(l.codcmdprodman, 0) CODCMDPRODMAN, P2.codraportp2
                FROM RAPORTP2 P2
                    INNER JOIN RAPORTP1    P1 ON  P2.CODRAPORTP1 = P1.CODRAPORTP1
                    LEFT  JOIN manprodlink l  ON  l.codraportp2  = P2.codraportp2
                WHERE P1.CODRAPORTP = RecID
                )
  LOOP
    DELETE FROM raportp2 WHERE codraportp2 = v_rec.codraportp2;

    IF  v_rec.codcmdprodman &gt; 0 THEN
      DELETE FROM manprodlink WHERE codraportp2 = v_rec.codraportp2;

      select coalesce(sum(il.cant),0) INTO aCount FROM MANPRODLINK IL WHERE il.codcmdprodman = v_rec.codcmdprodman;
      UPDATE cmdprodman SET rest = cant - acount WHERE codcmdprodman = v_rec.codcmdprodman;

--  UPDATE CMDPRODMAN man
--  SET
--  REST = man.cant - (
--  SELECT COALESCE(SUM(IL.CANT), 0)
--  FROM MANPRODLINK IL
--  INNER JOIN raportp2 r2 ON  il.codraportp2 = r2.codraportp2
--  INNER JOIN raportp1 r1 ON  r1.codraportp1 = r2.codraportp1
--  INNER JOIN raportp r ON  r.codraportp = r1.codraportp
--  WHERE
--     man.codcmdprodman = il.codcmdprodman
--  )
--  WHERE
--   man.codcmdprodman = v_rec.codcmdprodman
--  ;
    END IF;
  END LOOP;

  DELETE FROM RaportP3 WHERE CodRaportP = RecId;
  DELETE FROM RaportP1 WHERE CodRaportP = RecId;
  DELETE FROM RaportP0 WHERE CodRaportP = RecId;
  DELETE FROM RaportP  WHERE CodRaportP = RecId;

  IF  aCarnetDoc &gt; 0 THEN
    PERFORM PKG_CARNETEDOC_RELEASENUMARDOC(ACARNETDOC, ANRDOC);
    PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE(ACARNETDOC);
  END IF;

  PERFORM NotifyModif(2, RecId, 'RAPORTP');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_raportp_sp_insertrecord</obj_name>
  <obj_hashval>f6a3eebd7ddb8f02671bf7fff8f5e8c5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_raportp_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 02.04.2024 - sinc. Oracle
  INSERT INTO TMP_RaportP (CodRaportP) VALUES(0);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(63);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_raportp_sp_lockrecord</obj_name>
  <obj_hashval>6b0be28c128d3204f13e141b0e9dcccf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_raportp_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodRaportP INTO Tmp FROM RaportP WHERE CodRaportP = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rapstocmed_getraport</obj_name>
  <obj_hashval>dcccf22c452f09b063532d72abc55747</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rapstocmed_getraport()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  EXECUTE 'TRUNCATE TABLE TMP_RAPSTOCMED_CUMULAT' ;

  INSERT INTO TMP_RAPSTOCMED_CUMULAT
  SELECT
    CodWorkplace, CIM, NUMARLOT, DATAEXPIRARELOT, 0 Ordine, 'STOC ANTERIOR' Tip, STOCANT CANT,
    NULL TIPPART,
    NULL TIPDOC,
    NULL PART, NULL NRDOC, NULL DATADOC, NULL CODTARA
  FROM TMP_RAPSTOCMED1
  WHERE ARETRANZ &gt; 0;

  INSERT INTO TMP_RAPSTOCMED_CUMULAT
  SELECT
    CodWorkplace, CIM, NUMARLOT, DATAEXPIRARELOT, 1 Ordine, 'INTRARI' Tip, Sum(CANT),
    CASE CodTipPart
      WHEN 1 THEN 'intern'
      WHEN 2 THEN 'extern'
    END TIPPART,
    CASE CodTipDoc
      WHEN 1 THEN 'achizitie'
      WHEN 2 THEN 'retur'
      WHEN 3 THEN 'retragere'
      WHEN 4 THEN 'reglare stoc prin inventar'
    END TIPDOC,
    PART, Coalesce(NRFACTURA, NRAVIZ) NRDOC, DATADOC, NULL CODTARA
  FROM TMP_RAPSTOCMED
  WHERE TIP = 1
  GROUP BY CodWorkplace, CIM, NUMARLOT, DATAEXPIRARELOT, CodTipPart, CodTipDoc, PART, NRFACTURA, NRAVIZ, DATADOC, CODTARA;

  INSERT INTO TMP_RAPSTOCMED_CUMULAT
  SELECT
    CodWorkplace, CIM, NUMARLOT, DATAEXPIRARELOT, 2 Ordine, 'IESIRI' Tip, Sum(CANT),
    CASE CodTipPart
      --Pentru farmaciile cu circuit închis si pentru farmaciile private - nsubunit.TIPUNITJURIDICA = 1
      WHEN  1 THEN 'persoana fizica'
      WHEN  2 THEN 'persoana juridica'
      --Pentru unitatile de distributie angro a medicamentelor, importatori sau fabricanti autorizati
      WHEN  3 THEN 'unitate de distributie angro a medicamentelor, importator sau fabricant autorizat'
      WHEN  4 THEN 'farmacie comunitara'
      WHEN  5 THEN 'farmacie cu circuit inchis'
      WHEN  6 THEN 'altele'
      --Pentru farmaciile cu circuit închis si pentru farmaciile private - nsubunit.TIPUNITJURIDICA = 1 -&gt; completare SER 1.18
      WHEN  7 THEN 'Persoana fizica (cetatean roman sau strain)  identificata cu CNP (cumparator de antibiotic)'
      WHEN  8 THEN 'Persoana fizica (cetatean roman sau strain) identificata cu CID (cumparator de antibiotic)'
      WHEN  9 THEN 'Persoana fizica cetatean strain identificat cu pasaport (cumparator de antibiotic)'
      WHEN 10 THEN 'Persoana fizica cetatean strain identificat cu Card EU (CE) (cumparator de antibiotic)'
      WHEN 11 THEN 'Unitate medicala'
    END TIPPART,
    CASE CodTipDoc
      WHEN 2 THEN 'retur'
      WHEN 3 THEN 'retragere'
      WHEN 4 THEN 'reglare stoc prin inventar'
      WHEN 5 THEN 'vanzare'
      WHEN 6 THEN 'expirare'
      --completare SER 1.18
      WHEN 7 THEN 'vanzare antibiotice fara reteta'
      WHEN 8 THEN 'vanzare antibiotice cu reteta emisa in Romania'
      WHEN 9 THEN 'vanzare antibiotice cu reteta emisa in strainatate'
    END TIPDOC,
    PART, Coalesce(NRFACTURA, NRAVIZ) NRDOC, DATADOC, CODTARA
  FROM TMP_RAPSTOCMED
  WHERE TIP = 2
  GROUP BY CodWorkplace, CIM, NUMARLOT, DATAEXPIRARELOT, CodTipPart, CodTipDoc, PART, NRFACTURA, NRAVIZ, DATADOC, CODTARA;

  INSERT INTO TMP_RAPSTOCMED_CUMULAT
  SELECT
    CodWorkplace, CIM, NUMARLOT, DATAEXPIRARELOT, 3 Ordine, 'STOC RAPORTAT' Tip, STOC CANT,
    NULL TIPPART,
    NULL TIPDOC,
    NULL PART, NULL NRDOC, NULL DATADOC, NULL CODTARA
  FROM TMP_RAPSTOCMED1;

  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rapstocmed_getvnewdata</obj_name>
  <obj_hashval>98db52756e049c0683121a68350f048c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rapstocmed_getvnewdata(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_RAPSTOCMED.vNewData', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rapstocmed_goleste_tmp</obj_name>
  <obj_hashval>3d011d20ed95166008757d4e04bf86af</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rapstocmed_goleste_tmp()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  EXECUTE 'TRUNCATE TABLE TMP_RAPSTOCMED_CUMULAT' ;
  EXECUTE 'TRUNCATE TABLE TMP_RAPSTOCMED_NAO' ;
  EXECUTE 'TRUNCATE TABLE TMP_RAPSTOCMED_SUB' ;
  EXECUTE 'TRUNCATE TABLE TMP_RAPSTOCMED';
  EXECUTE 'TRUNCATE TABLE TMP_RAPSTOCMED0';
  EXECUTE 'TRUNCATE TABLE TMP_RAPSTOCMED1';
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rapstocmed_setvnewdata</obj_name>
  <obj_hashval>fa03767b08f5e344ef470be3b88878ae</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rapstocmed_setvnewdata(avnewdata date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_RAPSTOCMED.vNewData',avNewData,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_trasfactinc_processlist</obj_name>
  <obj_hashval>52f84ad32afe4f7a156594db8e2717ab</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_trasfactinc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sWith           varchar := '';
  sSelect         varchar := '';
  gSuplCols       VARCHAR := 'npart p';
  gUserFields     VARCHAR := '';
  gUserAlias      VARCHAR := '';
  gNullAlias      VARCHAR := '';
  gSuplJoins      VARCHAR := '';
BEGIN
  --Adina 16.10.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_TRASFACTINC.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '
   (DENPERSF,
    NRINREGF,
    DENTRASEUF,
    PREFIXDOCF,
    NRDOCF,
    DATADOCF,
    DEN_PART,
    VALDOCF,
    SERIEDOCF,
    SIMBOLMONEDA,
    ORAF,
    DENTRASEUP,
    DENPERSI,
    NRINREGI,
    DENTRASEUI,
    PREFIXDOCI,
    NRDOCI,
    DATADOCI,
    VALDOCI,
    SERIEDOCI,
    ORAI,
    DENTRASEU,
    SOLDPART,
    SEDIU  ' || gUserFields || ')';

  sWith :=
    'with st_in_zi as ( ' ||
      'select di.codtrezor1, i.codies ' ||
      'from ' ||
            'tmp_distrib_inc di ' ||
            'inner join trezor1 t1          on di.codtrezor1      = t1.codtrezor1 ' ||
            'inner join trezor t            on t1.codtrezor       = t.codtrezor '   ||
            'inner join general gi          on gi.coddoc          = t1.codtrezor1 and gi.tipdoc = t.tipdoc ' ||
            'inner join obligpif oi         on oi.codgeneral      = gi.codgeneral '     ||
            'inner join stingere st         on st.codstingatorpif = oi.codobligpif '    ||
            'inner join obligpif ofact      on st.codstinspif     = ofact.codobligpif ' ||
            'inner join general gf          on ofact.codgeneral   = gf.codgeneral '     ||
            'inner join iesiri i            on gf.coddoc          = i.codies and gf.tipdoc = i.tipdoc ' ||
            'inner join tmp_distrib_fact df on df.codies          = i.codies) ';
  sWith := sWith ||
    ', st_alta_zi as ( ' ||
        'select di.codtrezor1, i.codies ' ||
        'from ' ||
              'tmp_distrib_inc di ' ||
              'inner join trezor1 t1     on di.codtrezor1      = t1.codtrezor1 ' ||
              'inner join trezor t       on t1.codtrezor       = t.codtrezor '   ||
              'inner join general gi     on gi.coddoc          = t1.codtrezor1 and gi.tipdoc = t.tipdoc ' ||
              'inner join obligpif oi    on oi.codgeneral      = gi.codgeneral '     ||
              'inner join stingere st    on st.codstingatorpif = oi.codobligpif '    ||
              'inner join obligpif ofact on st.codstinspif     = ofact.codobligpif ' ||
              'inner join general gf     on ofact.codgeneral   = gf.codgeneral '     ||
              'inner join iesiri i       on gf.coddoc          = i.codies and gf.tipdoc = i.tipdoc ' ||
              'where not exists (select df.codies from tmp_distrib_fact df where df.codies = i.codies)) ';
  sWith := sWith ||
    ', docs as (SELECT '         ||
                'i.codies, '     ||
                'i.codlocatie, ' ||
                'df.DEN_PERS denpersf, ' ||
                'i.nrtransp nrinregf, '  ||
                'd1f.dentraseu dentraseuf, ' ||
                'df.PREFIXDOC prefixdocf, '  ||
                'df.NRDOC nrdocf, '    ||
                'i.DATADOC datadocf, ' ||
                'df.Den_Part, '        ||
                'df.ValDoc valdocf, '  ||
                'df.seriedoc seriedocf, ' ||
                'df.simbolmoneda, ' ||
                'df.ora oraf, '     ||
                'TL.DENTRASEU dentraseuP, '  ||
                'di.DEN_PERS denpersi, '     ||
                'd1i.nrinreg nrinregi, '     ||
                'd1i.dentraseu dentraseui, ' ||
                'di.PREFIXDOC prefixdoci, '  ||
                'di.NRDOC nrdoci, '       ||
                'di.DATADOC datadoci, '   ||
                'di.ValDoc valdoci, '     ||
                'di.seriedoc seriedoci, ' ||
                'di.ora orai, '  ||
                'TZ.DENTRASEU, ' ||
                'coalesce(d2.sold, 0) SOLDPART, ' ||
                'df.codpers, ' ||
                'i.partener '  ||
              ' FROM tmp_distrib_fact df ' ||
                    'inner join st_in_zi st           on df.codies     = st.codies '        ||
                    'inner join tmp_distrib_inc di    on di.codtrezor1 = st.codtrezor1 '    ||
                    'inner join iesiri i              on df.codies     = i.codies '         ||
                    'inner join tmp_distrib1 d1f      on i.agent       = d1f.codpers '      ||
                    'inner join nagenda ag            on i.codlocatie  = ag.codagenda '     ||
                    'inner join traseulivr TL         on ag.codtraseu  = tl.codtraseulivr ' ||
                    'inner join trezor1 t1            on di.codtrezor1 = t1.codtrezor1 '    ||
                    'inner join trezor t              on t1.codtrezor  = t.codtrezor '      ||
                    'inner join tmp_distrib1 d1i      on di.CodPers    = d1i.codpers '      ||
                    'inner join tmp_manevra_liste man on d1i.codtraseu::varchar = man.valoare and man.filtru = ''CODTRASEU'' '    ||
                    '                                 and df.codpers::varchar = man.valoare1 and man.filtru1 = ''CODPERS'' '      ||
                    'inner join traseulivr TZ         on man.valoare = TZ.CodTraseuLivr::varchar and man.filtru = ''CODTRASEU'' ' ||
                    'inner join tmp_distrib2 d2       on d2.codpart  = i.partener and i.codlocatie = d2.codagenda ';
  sWith := sWith ||
               'UNION ALL ' ||
                'SELECT '   ||
                  'i.codies, '     ||
                  'i.codlocatie, ' ||
                  'df.DEN_PERS denpersf, ' ||
                  'i.nrtransp nrinregf, '  ||
                  'd1f.dentraseu dentraseuf, ' ||
                  'df.PREFIXDOC prefixdocf, '  ||
                  'df.NRDOC nrdocf, '    ||
                  'i.DATADOC datadocf, ' ||
                  'df.Den_Part, '        ||
                  'df.ValDoc valdocf, '  ||
                  'df.seriedoc seriedocf, '   ||
                  'df.simbolmoneda, ' ||
                  'df.ora oraf, '     ||
                  'TL.DENTRASEU DENTRASEUP, ' ||
                  'null DENPERSI, '   ||
                  'null NRINREGI, '   ||
                  'null DENTRASEUI, ' ||
                  'null PREFIXDOCI, ' ||
                  'null NRDOCI, '     ||
                  'null DATADOCI, '   ||
                  'null VALDOCI, '    ||
                  'null SERIEDOCI, '  ||
                  'null ORAI, '       ||
                  'TZ.DENTRASEU, '    ||
                  'coalesce(d2.sold, 0) SOLDPART, ' ||
                  'df.codpers, ' || 'i.partener '   ||
              ' FROM tmp_distrib_fact df '          ||
                    'left join iesiri i              on df.codies    = i.codies '         ||
                    'left join tmp_distrib1 d1f      on i.agent      = d1f.codpers '      ||
                    'left join nagenda ag            on i.codlocatie = ag.codagenda '     ||
                    'left join traseulivr TL         on ag.codtraseu = tl.codtraseulivr ' ||
                    'left join tmp_manevra_liste man on d1f.codtraseu::varchar = man.valoare  and man.filtru  = ''CODTRASEU'' '  ||
                    '                                 and df.codpers::varchar  = man.valoare1 and man.filtru1 = ''CODPERS'' '    ||
                    'left join traseulivr TZ         on man.valoare = TZ.CodTraseuLIVR::varchar and man.filtru = ''CODTRASEU'' ' ||
                    'left join tmp_distrib2 d2       on d2.codpart  = i.partener and i.codlocatie = d2.codagenda ' ||
               'where not exists (select st.codies from st_in_zi st where st.codies = i.codies) ';
  sWith := sWith ||
            'UNION ALL ' ||
            'SELECT '    ||
              'i.codies, '     ||
              'i.codlocatie, ' ||
              'pers.NUME||'' ''||pers.prenume denpersf, ' ||
              'i.nrtransp nrinregf, '     ||
              'TL.DENTRASEU dentraseuf, ' ||
              'i.PREFIXDOC prefixdocf, '  ||
              'i.NRDOC nrdocf, '     ||
              'i.DATADOC datadocf, ' ||
              'part.Den_Part, '      ||
              'i.ValDoc valdocf, '   ||
              'doc.serie, '  ||
              'mon.simbol, ' ||
              'case
                 when EXTRACT(HOUR FROM i.datainreg) &lt; 10 then ''0''||(EXTRACT(HOUR FROM i.datainreg))::varchar
                 else (EXTRACT(HOUR FROM i.datainreg))::varchar
               end||'':''||
               case
                 when EXTRACT(MINUTE FROM i.datainreg) &lt; 10 then ''0''||(EXTRACT(MINUTE FROM i.datainreg))::varchar
                 else (EXTRACT(MINUTE FROM i.datainreg))::varchar
               end||'':''||
               case
                 when EXTRACT(SECOND FROM i.datainreg) &lt; 10 then ''0''||(EXTRACT(SECOND FROM i.datainreg))::varchar
                 else (EXTRACT(SECOND FROM i.datainreg))::varchar
               end oraf, '                 ||
              'TL.DENTRASEU dentraseui, '  ||
               'di.DEN_PERS denpersi, '    ||
              'd1i.nrinreg nrinregi, '     ||
              'd1i.dentraseu dentraseui, ' ||
              'di.PREFIXDOC prefixdoci, '  ||
              'di.NRDOC nrdoci, '          ||
              'di.DATADOC datadoci, '      ||
              'di.ValDoc valdoci, '        ||
              'di.seriedoc seriedoci, '    ||
              'EXTRACT(HOUR FROM T.DataInreg)||'' : ''|| EXTRACT(MINUTE FROM T.DataInreg)||'' : ''||EXTRACT(SECOND FROM T.DataInreg) orai, ' ||
              'TZ.DENTRASEU, '                  ||
              'coalesce(d2.sold, 0) SOLDPART, ' ||
              'di.codpers, '                    ||
              'i.partener '                     ||
          ' FROM tmp_distrib_inc di '           ||
                'inner join st_alta_zi st         on di.codtrezor1 = st.codtrezor1 '    ||
                'inner join iesiri i              on st.codies     = i.codies '         ||
                'inner join doccarnete doc        on doc.codcarnet = i.carnetdoc '      ||
                'inner join npart part            on i.partener    = part.codpart '     ||
                'inner join nmonede mon           on mon.codmoneda = i.moneda '         ||
                'inner join nagenda ag            on i.codlocatie  = ag.codagenda '     ||
                'inner join traseulivr TL         on ag.codtraseu  = tl.codtraseulivr ' ||
                'inner join trezor1 t1            on di.codtrezor1 = t1.codtrezor1 '    ||
                'inner join trezor t              on t1.codtrezor  = t.codtrezor '      ||
                'inner join tmp_distrib1 d1i      on di.CodPers    = d1i.codpers '      ||
                'inner join tmp_manevra_liste man on d1i.codtraseu::varchar = man.valoare  and man.filtru  = ''CODTRASEU'' '  ||
                '                                 and di.codpers::varchar   = man.valoare1 and man.filtru1 = ''CODPERS'' '    ||
                'inner join traseulivr TZ         on man.valoare = TZ.CodTraseuLivr::varchar and man.filtru = ''CODTRASEU'' ' ||
                'left  join npers pers            on i.agent     = pers.codpers ' ||
                'left  join tmp_distrib2 d2       on d2.codpart  = i.partener and i.codlocatie = d2.codagenda  ) ';

  sSelect := 'select
                docs.DENPERSF,
                docs.NRINREGF,
                docs.DENTRASEUF,
                docs.PREFIXDOCF,
                docs.NRDOCF,
                docs.DATADOCF,
                p.DEN_PART,
                docs.VALDOCF,
                docs.SERIEDOCF,
                docs.SIMBOLMONEDA,
                docs.ORAF,
                docs.DENTRASEUP,
                docs.DENPERSI,
                docs.NRINREGI,
                docs.DENTRASEUI,
                docs.PREFIXDOCI,
                docs.NRDOCI,
                docs.DATADOCI,
                docs.VALDOCI,
                docs.SERIEDOCI,
                docs.ORAI,
                tmp1.DENTRASEU,
                tmp2.SOLD,
                tmp2.obs SEDIU ' || gUserAlias ||
            ' from docs
                   inner join tmp_distrib1 tmp1     on tmp1.codpers     = docs.codpers
                   inner join tmp_manevra_liste man on tmp1.codtraseu::varchar = man.valoare  and man.filtru  = ''CODTRASEU''
                                                    and tmp1.codpers::varchar  = man.valoare1 and man.filtru1 = ''CODPERS''
                   left join tmp_distrib2 tmp2      on tmp1.coddistrib1 = tmp1.coddistrib1 and tmp2.codagenda = docs.codlocatie
                   left join npart p                on docs.partener    = p.codpart' || gSuplJoins || '
              union all
              select
                tmp1.DENPERS DENPERSF,
                null NRINREGF,
                null DENTRASEUF,
                null PREFIXDOCF,
                null NRDOCF,
                null DATADOCF,
                p.DEN_PART,
                null VALDOCF,
                null SERIEDOCF,
                null SIMBOLMONEDA,
                null ORAF,
                null DENTRASEUP,
                null DENPERSI,
                null NRINREGI,
                null DENTRASEUI,
                null PREFIXDOCI,
                null NRDOCI,
                null DATADOCI,
                null VALDOCI,
                null SERIEDOCI,
                null ORAI,
                tmp1.DENTRASEU,
                tmp2.SOLD,
                tmp2.obs SEDIU ' || gUserAlias ||
            ' from tmp_distrib2 tmp2
                   inner join tmp_distrib1 tmp1     on tmp1.coddistrib1 = tmp2.coddistrib1
                   inner join tmp_manevra_liste man on tmp1.codtraseu::varchar = man.valoare  and man.filtru  = ''CODTRASEU''
                                                   and tmp1.codpers::varchar   = man.valoare1 and man.filtru1 = ''CODPERS''
                   left join npart p                on tmp2.codpart   = p.codpart
                   left join docs                   on tmp2.codagenda = docs.codlocatie' || gSuplJoins || '
               where coalesce(docs.codies, 0) = 0 ';
--  insert into x values('rr',sWith ||sSelect);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sWith || sSelect, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmaecli_processlist</obj_name>
  <obj_hashval>b9bdb6842c5f17f6cccec40f3183ba99</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmaecli_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert      varchar := '';
  sSelect1      varchar := '';
  sSelect2      varchar := '';
  sPer          varchar := '';
  sNotBcar     varchar := '';
  gSuplCols    VARCHAR :=
    'IESIRI AE, IESIRI1 AE1, IESIRI AX, IESIRI1 AX1, NARTOBJ O, NART ART, NUM1 U, NPART P, IESIRI I, IESIRI1 I1, NCLASEA CLA, NCLASEP CLP, NAGENDA AG, TRASEULIVR T, '||
    'NPART PROD, NCARSUPART CS, NPARTTR D, NARTCLI AC, NLOCALIT LOC, NTARI TARI, NARTOBJTRAD TRAD, NECHIV E, GRECHIV GRE, OFERTA1 O1, BCAR BCAR';
  gUserFields  VARCHAR := '';
  gUserAlias   VARCHAR := '';
  gNullAlias   VARCHAR := '';
  gSuplJoins   VARCHAR := '';
  gDataS       VARCHAR := '';
  gDataF       VARCHAR := '';
  gOpt1        BOOLEAN      ;
  vStornoAvize NUMERIC;
  vAnF         NUMERIC := 0;
  vLunaF       NUMERIC := 0;
BEGIN
  --Florin 06.09.2021 - fixat 51252
  --Adina 19 august 2020
  gOpt1 := current_setting('PKG_LIST_ALEGPERIOADA.gOpt1', true)::boolean;

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT'    , 'OEXT.CODOBIECT     = O.CODOBIECT'     ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR'    , 'OATR.CODOBIECT     = O.CODOBIECT'     ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET'  , 'PD'      , 'PD.CODPART         = P.CODPART'       ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NAGENDA'   , 'SLIVR'   , 'SLIVR.CODAGENDA    = AE.CODLOCATIE'   ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NLOCALIT'  , 'LOCLIVR' , 'LOCLIVR.CODLOCALIT = SLIVR.CODLOCALIT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NTARI'     , 'TARALIVR', 'LOCLIVR.CODTARA    = TARALIVR.CODTARA',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NAGENDA'   , 'SSOC'    , 'SSOC.CODPART       = AE.PARTENER AND SSOC.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(SSOC.INACTIV, 0) = 0');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NLOCALIT'  , 'LOCSOC'  , 'LOCSOC.CODLOCALIT  = SSOC.CODLOCALIT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NTARI'     , 'TARASOC' , 'LOCSOC.CODTARA     = TARASOC.CODTARA',NULL);

  IF  coalesce(fnc_GetValConstanta('CumulezBcar', getANLUCRU(), getLUNALUCRU()),'0') = '2' THEN
    call pkg_list_struct_addsupltabs(gSuplCols, 'BCAR'   , 'BCAR'   , 'BCAR.CODDOC1 = AE1.CODIES1 AND BCAR.TIPDOC = AE.TIPDOC',NULL);
    call pkg_list_struct_addsupltabs(gSuplCols, 'BCAREXT', 'BCAREXT', 'BCAREXT.CODBCAR = BCAR.CODBCAR',NULL);
  END IF;

  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);

  PERFORM set_config('PKG_LIST_BASE_URMAECLI.gSuplCols',   gSuplCols            ,false);
  PERFORM set_config('PKG_LIST_BASE_URMAECLI.vAnF',        vAnF::varchar        ,false);
  PERFORM set_config('PKG_LIST_BASE_URMAECLI.vLunaF',      vLunaF::varchar      ,false);
  PERFORM set_config('PKG_LIST_BASE_URMAECLI.vStornoAvize',vStornoAvize::varchar,false);

  sInsert := 'INSERT INTO ' || coalesce(tmpName,'') || '(
    NAV_CodDoc,NAV_TipDoc, Ae, Doc, Part,
    Art, UM, Cant, CantAe,
    CantPrel,
    RestC,
    RestV,
    PUAE,
    NrLinAe, Ordine,
    DenLaCli, CodLaCli,
    CodListat, ValAchiz' || gUserFields || ')';

  gDataS := COALESCE(current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true),'');
  gDataF := COALESCE(current_setting('PKG_LIST_ALEGPERIOADA.gDataF', true),'');

  IF  to_date(gDataS,'dd.mm.yyyy') = to_date(gDataF,'dd.mm.yyyy') THEN
    sPer := '= TO_DATE(''' || gDataS || ''',''dd.mm.yyyy'')';
  ELSE
    sPer := 'BETWEEN TO_DATE(''' || gDataS || ''',''dd.mm.yyyy'') AND TO_DATE(''' || gDataF || ''',''dd.mm.yyyy'')';
  END IF;

  sSelect1 := '
  SELECT
    ae.Codies, ae.tipdoc,
    CASE WHEN ax.codies IS NOT NULL THEN ax.PrefixDoc||ax.NrDoc||''/''||ax.Datadoc::date ELSE ae.PrefixDoc||ae.NrDoc||''/''||ae.Datadoc::date END,
    ae.PrefixDoc||ae.NrDoc||''/''||ae.Datadoc::date, p.Den_Part,
    o.denumire, u.den_um1, ae1.cant/u.paritate Cant, ae1.cant/u.paritate CantAe,
    CASE WHEN coalesce(ae1.custodieintrare,0) = 1 OR coalesce(ae.TipConsumator,0) = 2 THEN ae1.cant/u.paritate ELSE 0 END CantPrel,
    CASE WHEN coalesce(ae1.custodieintrare,0) = 1 OR coalesce(ae.TipConsumator,0) = 2 THEN 0 ELSE ae1.cant/u.paritate END RestC,
    CASE WHEN coalesce(ae1.custodieintrare,0) = 1 OR coalesce(ae.TipConsumator,0) = 2 THEN 0 ELSE ae1.cant*Coalesce(ax1.pu,ae1.pu,0) END RestV,
    Coalesce(ax1.pu,ae1.pu,0) * u.paritate,
    CASE
      WHEN ax.codies IS NULL
      THEN (SELECT COUNT(1) FROM IESIRI1 X1 WHERE x1.codies = ae.codies AND x1.IndexLocal &lt;= ae1.IndexLocal)
      ELSE (SELECT COUNT(1) FROM IESIRI1 X1 WHERE x1.codies = ax.codies AND x1.IndexLocal &lt;= ax1.IndexLocal)
    END,
    (case when ax.codies is NULL then 0 else 1 end) ,
    COALESCE(ac.denumire,trad.denumiretrad,o.denumire), coalesce(ac.codextern,o.codextern),
    coalesce((case when ac.tipcodafisat=1 then gre.cod when ac.tipcodafisat=2 then ac.codextern when ac.tipcodafisat=3 then o.codextern when ac.tipcodafisat=4 then o.codintern when ac.tipcodafisat=5 then o.codvamal when ac.tipcodafisat=6 then o.codplu::varchar when ac.tipcodafisat=7 then o1.codextofe end),o.codextern),
    pkg_list_base_urmaecli_GetValAchiz(ae1.codies1) ' || gUserAlias || '
  FROM iesiri ae
    INNER JOIN iesiri1     ae1  ON ae1.codies      = ae.codies
    INNER JOIN nartobj     o    ON o.codobiect     = ae1.codobiect
    INNER JOIN nart        art  ON o.codarticol    = art.codarticol
    INNER JOIN num1        u    ON u.codum1        = ae1.umsec
    INNER JOIN npart       p    ON p.codpart       = ae.partener
    LEFT  JOIN iesiri1     ax1  ON ax1.codies1     = (case when ae1.codies1storno=0 then ae1.codliniedocimp when ae1.codies1storno is NULL then ae1.codliniedocimp else ae1.codies1storno end)
    LEFT  JOIN iesiri      ax   ON ax.codies       = ax1.codies
    LEFT  JOIN iesiri1     i1   ON i1.codies1      = ax1.codies1
    LEFT  JOIN iesiri      i    ON i.codies        = i1.codies
    LEFT  JOIN nclasea     cla  on cla.codclasea   = art.clasa
    LEFT  JOIN nclasep     clp  on clp.codclasep   = p.codclasa
    LEFT  JOIN nagenda     ag   on ag.codagenda    = ae.codlocatie
    LEFT  JOIN traseulivr  t    on t.codtraseulivr = ag.codtraseu
    LEFT  JOIN npart       prod ON prod.codpart    = o.codproducator
    LEFT  JOIN ncarsupart  cs   ON cs.codcarsupart = o.codcaract
    LEFT  JOIN nparttr     d    ON d.codparttr     = ae.delegat
    LEFT  JOIN nartcli     ac   ON ac.codobiect    = ae1.codobiect AND ac.codpart = ae.partener
    LEFT  JOIN nlocalit    loc  ON loc.codlocalit  = ag.codlocalit
    LEFT  JOIN ntari       tari ON tari.codtara    = loc.codtara
    LEFT  JOIN nartobjtrad trad ON trad.codlimba   = tari.codlimba and trad.codobiect = ae1.codobiect
    LEFT  JOIN nechiv      e    ON e.codobiect     = ae1.codobiect
    LEFT  JOIN grechiv     gre  ON gre.codgrechiv  = e.codgrupa
    LEFT  JOIN oferta1     o1   ON o1.codoferta1   = ae1.codoferta1' || gSuplJoins || '
  WHERE ae.tipdoc = 20 AND ae.operat = 1 AND ae.anulat = 0 ' || PKG_LIST_BASE_UTILS_COND_SUBUNIT('AE',NULL,NULL,NULL) || '
    AND ae.DataDoc ' || sPer;

  sSelect2 := '
  SELECT
    i.codies, i.tipdoc,
    CASE WHEN ax.codies IS NOT NULL THEN ax.PrefixDoc||ax.NrDoc||''/''||ax.Datadoc::date ELSE ae.PrefixDoc||ae.NrDoc||''/''||ae.Datadoc::date END,
    --ae.PrefixDoc||ae.NrDoc||''/''||ae.Datadoc::date Com,
    i.PrefixDoc||i.NrDoc||''/''||i.Datadoc::date, p.Den_Part,
    o.denumire, u.den_um1, il.cant/u.paritate Cant, 0 CantAe,
    il.cant/u.paritate CantPrel,
    -il.cant/u.paritate RestC,
    -il.cant*coalesce(ae1.pu,0) RestV,
    coalesce(ae1.pu,0) * u.paritate,
    CASE
      WHEN ax.codies IS NULL
      THEN (SELECT COUNT(1) FROM IESIRI1 X1 WHERE x1.codies = ae.codies AND x1.IndexLocal &lt;= ae1.IndexLocal)
      ELSE (SELECT COUNT(1) FROM IESIRI1 X1 WHERE x1.codies = ax.codies AND x1.IndexLocal &lt;= ax1.IndexLocal)
    END,
    --(SELECT COUNT(1) FROM IESIRI1 X1 WHERE x1.codies = ae.codies AND x1.IndexLocal &lt;= ae1.IndexLocal),
    1 + ROW_NUMBER() OVER (PARTITION BY ae.Codies, ae1.IndexLocal ORDER BY I.DataDoc, I.NrDoc, I.CodIes),
    COALESCE(ac.denumire,trad.denumiretrad,o.denumire), coalesce(ac.codextern,o.codextern),
    coalesce((case when ac.tipcodafisat=1 then gre.cod when ac.tipcodafisat=2 then ac.codextern when ac.tipcodafisat=3 then o.codextern when ac.tipcodafisat=4 then o.codintern when ac.tipcodafisat=5 then o.codvamal when ac.tipcodafisat=6 then o.codplu::varchar when ac.tipcodafisat=7 then o1.codextofe end),o.codextern),
    CASE WHEN il.cant = 0 THEN 0 WHEN ae1.cant = 0 THEN 0 ELSE pkg_list_base_urmaecli_GetValAchiz(ae1.codies1,i1.cant,i.an,i.luna) END ' || gUserAlias || '
  FROM iesiri ae
    INNER JOIN iesiri1     ae1  ON ae1.codies      = ae.codies
    INNER JOIN nartobj     o    ON o.codobiect     = ae1.codobiect
    INNER JOIN nart        art  ON o.codarticol    = art.codarticol
    INNER JOIN num1        u    ON u.codum1        = ae1.umsec
    INNER JOIN npart       p    ON p.codpart       = ae.partener
    INNER JOIN ieslink     il   ON il.codlinieaviz = ae1.codies1
    INNER JOIN iesiri1     i1   ON i1.codies1      = il.codies1
    INNER JOIN iesiri      i    ON i.codies        = i1.codies
    LEFT  JOIN iesiri1     ax1  ON ax1.codies1     = (case when ae1.codies1storno=0 then ae1.codliniedocimp when ae1.codies1storno is NULL then ae1.codliniedocimp else ae1.codies1storno end)
    LEFT  JOIN iesiri      ax   ON ax.codies       = ax1.codies
    LEFT  JOIN nclasea     cla  on cla.codclasea   = art.clasa
    LEFT  JOIN nclasep     clp  on clp.codclasep   = p.codclasa
    LEFT  JOIN nagenda     ag   on ag.codagenda    = ae.codlocatie
    LEFT  JOIN traseulivr  t    on t.codtraseulivr = ag.codtraseu
    LEFT  JOIN npart       prod ON prod.codpart    = o.codproducator
    LEFT  JOIN ncarsupart  cs   ON cs.codcarsupart = o.codcaract
    LEFT  JOIN nparttr     d    ON d.codparttr     = ae.delegat
    LEFT  JOIN nartcli     ac   ON ac.codobiect    = ae1.codobiect AND ac.codpart = ae.partener
    LEFT  JOIN nlocalit    loc  ON loc.codlocalit  = ag.codlocalit
    LEFT  JOIN ntari       tari ON tari.codtara    = loc.codtara
    LEFT  JOIN nartobjtrad trad ON trad.codlimba   = tari.codlimba and trad.codobiect = ae1.codobiect
    LEFT  JOIN nechiv      e    ON e.codobiect     = ae1.codobiect
    LEFT  JOIN grechiv     gre  ON gre.codgrechiv  = e.codgrupa
    LEFT  JOIN oferta1     o1   ON o1.codoferta1   = ae1.codoferta1' || gSuplJoins || '
  WHERE ae.tipdoc = 20 AND ae.operat = 1 AND ae.anulat = 0 AND il.cant &lt;&gt; 0 ' || PKG_LIST_BASE_UTILS_COND_SUBUNIT('AE',NULL,NULL,NULL) || '
    AND i.operat = 1 AND i.anulat = 0
    AND ae.DataDoc ' || sPer || coalesce(CASE WHEN gOpt1 THEN ' AND i.DataDoc ' || coalesce(sPer,'') END,'');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect1, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect2, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmofe_processlist</obj_name>
  <obj_hashval>b2662949c60a0eb3feefb8ed8e7a31d7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmofe_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplCols   VARCHAR := '';
  gSuplJoins  VARCHAR := '';

  sInsert    varchar;
  sSelect    varchar;
  sFiltru    varchar := '';
  sPASubunit varchar := '';
  sPAFiltru  varchar := '';
  sJoinPA    varchar := '';
  sCursPA    varchar := '';
  vTipDoc    NUMERIC;
  aSitV      numeric;
  aBancaV    numeric;
  aMonedaV   numeric;
  sInsAchiz  varchar;
  sSelAchiz  varchar;
  bInfSitVal boolean;
begin
  --Bogdan 09.09.2020
  gSuplCols := 'Oferta O, Oferta1 O1, NArtObj AO, NPart P, NUM1 UM, NMonede M, NartCli AC, NClaseA CLSA, NClaseAS CLSS, PretM PM, Oportunitati OPORT ';

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_AddSuplTabs(gSuplCols, 'NARTOBJEXT', 'OEXT',   'OEXT.CODOBIECT = O1.CODOBIECT');
  call pkg_list_struct_AddSuplTabs(gSuplCols, 'NARTOBJATR', 'OATR',   'OATR.CODOBIECT = O1.CODOBIECT');
  call pkg_list_struct_AddSuplTabs(gSuplCols, 'OFERTAEXT' , 'OFEXT',  'OFEXT.CODOFERTA = O1.CODOFERTA');
  call pkg_list_struct_AddSuplTabs(gSuplCols, 'OFERTA1EXT', 'OF1EXT', 'OF1EXT.CODOFERTA1 = O1.CODOFERTA1');
  call pkg_list_struct_AddSuplTabs(gSuplCols, 'NARTOBJ1'  , 'AO1',    'AO1.CODOBIECT = O1.CODOBIECT AND O.An*12+O.Luna BETWEEN AO1.ALSTART AND AO1.ALSTOP');
  call pkg_list_struct_AddSuplTabs(gSuplCols, 'NARTOBJ1'  , 'AO1M',   'AO1M.CODOBIECT = O1.CODOBIECT AND '||getanlunalucru()::varchar||' BETWEEN AO1M.ALSTART AND AO1M.ALSTOP');

  CALL pkg_list_struct_getsuplcols( aLISTID, aLISTVER, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config ('PKG_LIST_BASE_URMOFE.gSuplCols',gSuplCols,false);

  IF InStr (gSuplJoins , 'NARTOBJ1 ') &gt; 0 THEN
    CALL PRC_AL_CHECK('NARTOBJ1');
  END IF;

  IF (fnc_GetValConstantaLucru ('PretAchizSubunit') = '2') THEN
    sPASubunit := ', NG.CODSUBUNIT';
    sPAFiltru  := ' AND PA.CODSUBUNIT = O.SUBUNITATEA';
    sJoinPA    := '
            INNER JOIN NGEST NG ON NG.CODGEST = N.GEST';
  END IF;

  SELECT pkg_list_base_utils_GetInfoSitValuta.WME_RESULT,pkg_list_base_utils_GetInfoSitValuta.psitvaluta,
         pkg_list_base_utils_GetInfoSitValuta.pbancavaluta,pkg_list_base_utils_GetInfoSitValuta.pmonedavaluta
  FROM pkg_list_base_utils_GetInfoSitValuta (bInfSitVal,aSitV, aBancaV, aMonedaV) into bInfSitVal,aSitV, aBancaV, aMonedaV;

  IF (bInfSitVal) THEN
    sCursPA := '/ (select wme_result from PKG_LIST_BASE_UTILS_GETCURSREFERINTA( null, '
          || coalesce (aMonedaV::varchar,'')|| ','
          || coalesce (aBancaV::varchar,'')
          || ', to_char(pa.dataachizlast,''dd.mm.yyyy'') ))';
  END IF;

  IF NOT (PKG_LIST_SELURMOFE_TotiPart())  THEN
    sFiltru := '
          AND O.Partener IN (SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODPART'')';
  END IF;

  sInsAchiz := '';
  sSelAchiz := '';
  IF aLISTID = 144 THEN
    vTipDoc   := 50;
    sInsAchiz := ',PretAchiz,ValAchiz,Marja,ValMarja';
    sSelAchiz := ',O1.PretAchiz,O1.PretAchiz*O1.CantMin,case when coalesce(O1.PretAchiz,0) &gt; 0 then (O1.Pret - O1.PretAchiz)/O1.Pret*100
                        else 0 end, case when coalesce(O1.PretAchiz,0) &gt; 0 then O1.Pret - O1.PretAchiz else 0 end';
  ELSE
    vTipDoc := 51;
  END IF;

  sInsert := 'INSERT INTO '|| tmpName
            || ' (NAV_CodDoc,
            NAV_TipDoc,
            Art,
            Part,
            UM,
            CantMin,
            Pret,
            DataStart,
            DataEnd,
            Moneda,
            NrDoc,
            ZileL,
            ZileC,
            PjAdaos,
            PjDisc,
            Agent,
            PRACHIZLAST,
            PRACHIZLASTV,
            PRACHIZMAX,
            PRINREGLAST '
            || coalesce (sInsAchiz,'')
            || coalesce (gUserFields ,'')
            || ') ';
    sSelect := '
        WITH PA AS
          (SELECT DISTINCT NS.CODOBIECT'
            || coalesce (sPASubunit,'')|| ',
              LAST_VALUE (NS.PRET - COALESCE (NS.ADAOS,0)) OVER (PARTITION BY NS.CODOBIECT '|| coalesce (sPASubunit,'')|| ' ORDER BY N.DATANIR
                         range between unbounded preceding and unbounded following) PRACHIZLAST,
              LAST_VALUE (NS.PRET) OVER (PARTITION BY NS.CODOBIECT '|| coalesce (sPASubunit,'')|| ' ORDER BY N.DATANIR
                         range between unbounded preceding and unbounded following) PRINREGLAST,
              MAX (N.DATANIR) OVER (PARTITION BY NS.CODOBIECT '||coalesce (sPASubunit,'') ||') DATAACHIZLAST,
              MAX (NS.PRET - NS.ADAOS)  OVER (PARTITION BY NS.CODOBIECT '||coalesce (sPASubunit,'') ||') PRACHIZMAX
            FROM NIRSTOC      NS
              INNER JOIN NIR  N ON N.CODNIR = NS.CODNIR'
            || coalesce (sJoinPA,'')|| '
            WHERE
              N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 15)
              AND N.OPERAT = 1
              AND N.ANULAT = 0
          )
        SELECT O.CodOferta,
          O.TipDoc,
          AO.Denumire,
          P.Den_Part,
          UM.Den_UM1,
          O1.CantMin / UM.Paritate,
          O1.Pret    * UM.Paritate,
          O.DataStart,
          O.DataEnd,
          M.Den_Moneda,
          O.NrDoc,
          O1.ZileL,
          O1.ZileC,
          O1.ProcAdaos,
          O1.ProcDiscount,
          (case when AG.CodPers = 0 then AG.Nume else AG.NUME ||'' '' ||AG.PRENUME end) ,
          pa.prachizlast,
          pa.prachizlast '
            || coalesce (sCursPA,'')|| ',
          pa.prachizmax,
          pa.prinreglast '
            || coalesce (sSelAchiz,'')
            || coalesce (gUserAlias,'')|| '
        FROM Oferta              O
          INNER JOIN Oferta1     O1    ON O1.CodOferta    = O.CodOferta
          INNER JOIN NArtObj     AO    ON AO.CodObiect    = O1.CodObiect
          INNER JOIN NArt        A     ON AO.CodArticol   = A.CodArticol
          LEFT JOIN NClaseA      CLSA  ON A.Clasa         = CLSA.CodClaseA
          LEFT JOIN NClaseAS     CLSS  ON A.CLASASTATIST  = CLSS.CodClaseAS
          LEFT JOIN NPart        P     ON P.CodPart       = O.Partener
          LEFT JOIN NUM1         UM    ON UM.CodUM1       = O1.UMSec
          LEFT JOIN NMonede      M     ON M.CodMoneda     = O.Moneda
          LEFT JOIN NartCli      AC    ON AC.CodObiect    = O1.CodObiect AND AC.CodPart = O.Partener
          LEFT JOIN NPERS        AG    ON AG.CODPERS      = coalesce (O.AGENT,0)
          LEFT JOIN PRETM        PM    ON PM.CodObiect    = O1.CodObiect AND PM.Subunitatea = O.Subunitatea AND PM.Implicit = 1
          LEFT JOIN OPORTUNITATI OPORT ON OPORT.CodOferta = O.CodOferta
          LEFT JOIN PA                 ON PA.CodObiect    = O1.CodObiect'
            || coalesce (sPAFiltru,'')
            || coalesce (gSuplJoins ,'')|| '
        WHERE
          O.TipDoc = '|| coalesce (vTipDoc::varchar,'')|| '
          AND O.DataEnd   &gt;= to_date ('''|| coalesce (To_Char (PKG_LIST_SELURMOFE_DataIni() ,'dd.mm.yyyy') ,'')|| ''',''dd.mm.yyyy'')
          AND O.DataStart &lt;= to_date ('''|| coalesce (To_Char (PKG_LIST_SELURMOFE_DataFin() ,'dd.mm.yyyy') ,'')|| ''',''dd.mm.yyyy'') '
            || coalesce (sFiltru,'');
  PERFORM LIST_EXECUTE_IMMEDIATE (coalesce (sInsert,'') || coalesce (sSelect,'') , aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmplatiart_processlist</obj_name>
  <obj_hashval>3eb23a61ac78c7e024f67d1cd92007ed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmplatiart_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert       varchar := '';
  sSelect       varchar := '';
  sTipJoin       varchar := 'INNER';
  sAnS           numeric := EXTRACT( YEAR  FROM to_date(current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true),'dd.mm.yyyy') );
  sLunaS         numeric := EXTRACT( MONTH FROM to_date(current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true),'dd.mm.yyyy') );
  sDataS         varchar := current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true);
  sDataF         varchar := current_setting('PKG_LIST_ALEGPERIOADA.gDataF', true);
  AnLunaLucru   numeric;
  AnLunaIni     numeric;
  sCurs         varchar := ', 1, 1, 1, 1';
  aBancaV       numeric;
  aMonedaV       numeric;
  gSuplCols     VARCHAR :=  'tmp_lst_urmplartiart un, intrari1 i1, intrari i, nartobj o, npers agp, npart npart, nclasep clsp, nagenda ag, nlocalit loc, njudet jud, nmonede mon, nmonede monprest, pretm pm, nsubunit SubSting, nsubunit SubStins, '||
                             'npart prod, nart a, nclasea ca, nartcli ac, ncont c, nbankcont bc, nbank b';
   gUserFields   VARCHAR := '';
  gUserAlias     VARCHAR := '';
  gNullAlias     VARCHAR := '';
  gSuplJoins     VARCHAR := '';
  gOpt3          boolean := current_setting('PKG_LIST_ALEGPERIOADA.gOpt3', true)::boolean;
  ConstCC       NUMERIC(5);
BEGIN
  --Florin 13.05.2024 - fixat 61921
  --Florin 10.05.2024 - sinc. Oracle
  --Adina 28.04.2021 - alstart,alstop
  --Adina 08 septembrie 2020
  ConstCC  := CASE WHEN fnc_getvalconstantalucru('ScadenteAutomateCost') = '' THEN 0 ELSE fnc_getvalconstantalucru('ScadenteAutomateCost')::NUMERIC END;
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = O.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = O.CODOBIECT',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_URMPLATIART.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  CALL PRC_AL_CHECK('nartobj1',0);

  SELECT getANLUCRU() * 12 + getLUNALUCRU(), ANINITIAL * 12 + LUNAINITIALA
  INTO AnLunaLucru, AnLunaIni
  FROM FIRMALUNI;

  aBancaV  := (fnc_GetValConstanta('BancaCursPUV', getANLUCRU(), getLunaLucru()) )::numeric;
  aMonedaV := (SELECT WME_RESULT FROM pkg_list_base_utils_GET_Cod_MonedaFactInValuta(NULL, getANLUCRU(), getLunaLucru()));

  IF  COALESCE(aMonedaV, 0) &lt;&gt; 0 AND  COALESCE(aBancaV, 0) &lt;&gt; 0 THEN
    sCurs := ',
    (Select wme_result From PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null,' || coalesce(aMonedaV::varchar,'') || ',' || coalesce(aBancaV::varchar,'') || ', to_char(un.dstinsdata,''dd.mm.yyyy'') ) ),
    (Select wme_result From PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null,' || coalesce(aMonedaV::varchar,'') || ',' || coalesce(aBancaV::varchar,'') || ', to_char(un.dstingdata,''dd.mm.yyyy'') ) )';
  ELSE
    sCurs := ',1, 1';
  END IF;

  IF  COALESCE(aBancaV, 0) &lt;&gt; 0 THEN
    sCurs := sCurs || ',
    (Select wme_result From PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null,N1.CODMONEDA,' || coalesce(aBancaV::varchar,'') || ', to_char(un.dstinsdata,''dd.mm.yyyy'') ) ),
    (Select wme_result From PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null,N1.CODMONEDA,' || coalesce(aBancaV::varchar,'') || ', to_char(un.dstingdata,''dd.mm.yyyy'') ) )';
  ELSE
    sCurs := sCurs || ',1, 1';
  END IF;

  IF current_setting('PKG_LIST_ALEGPERIOADA.gOpt1', true)::boolean THEN
    sTipJoin := 'LEFT';
  END IF;

  sInsert := 'INSERT INTO ' || tmpName || '(
    NAV_CodDoc, NAV_CodDoc1, NAV_TipDoc,
    DSTINSPR, DSTINSNR, DSTINSDATA, TOTAL_DOCUMENT, VAL_NESTINSA_DOC, VAL_STINGATOR, VAL_STINGFTVA,
    SOLD_LIN, SOLD_LINF, ORDINE,
    SOLD_DOC, SOLD_DOCF, ORDDOC,
    DSTINGPR, DSTINGNR, DSTINGDATA, PARTENER, LOCATIE, DATADECONT, DATA, DATAPLATA, DATA_STINS, TERMEN, MONEDA, SUBUNIT, SUBUNIT_ST,
    SCADENTA, DIFZILE, DEPZILE, DEPZILEDEC, DEPZILEPLATA, CONT, ARTICOL, CODEXTERN, CODINTERN, PRODUCATOR, CLASAARTICOL,
    DSTINSCURS, DSTINSAN, DSTINSLUNA, DSTINGCURS, DSTINGAN, DSTINGLUNA, GESTDEN, GESTSIMB, NRCONT,
    DSTINSCURS_REF, DSTINGCURS_REF, DSTINSCURS_PREST, DSTINGCURS_PREST' || gUserFields || ')';

  sSelect := '
  WITH crs_sold as (
    SELECT
      g.coddoc, g.tipdoc,
      SUM(
        (ol.rest - (
          SELECT coalesce(sum(s.valoare), 0)
          FROM stingere s
            INNER JOIN obligpif os ON os.codobligpif = s.codstingatorpif
            INNER JOIN general  gs ON gs.codgeneral  = os.codgeneral
            LEFT  JOIN trezor1  t1 on gs.coddoc = t1.codtrezor1 AND gs.tipdoc &lt;&gt; 28 AND t1.luna = ' || coalesce(sLunaS::varchar,'') || ' AND t1.an = ' || coalesce(sAnS::varchar,'') || ' AND t1.datadoc &lt; TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'')
            LEFT  JOIN compens  c  ON gs.coddoc = c.codcompens  AND gs.tipdoc = 28  AND c.luna  = ' || coalesce(sLunaS::varchar,'') || ' AND c.an  = ' || coalesce(sAnS::varchar,'') || ' AND c.datadoc  &lt; TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'')
          WHERE s.codstinspif = ol.codobligpif
            AND coalesce(t1.codtrezor,c.codcompens) IS NOT NULL
        )) * (case when g.semnificatie=310 then -1 else 1 end)
      ) rest
    FROM obligpifluna ol
      INNER JOIN obligpif op on ol.codobligpif = op.codobligpif
      INNER JOIN general  g  on op.codgeneral  = g.codgeneral
    WHERE (g.tipdoc BETWEEN 1 AND 7 OR g.tipdoc = 35)
      AND ol.luna + ol.an*12 = ' || coalesce((sAnS * 12 + sLunaS - 1)::varchar,'') || '
    GROUP BY g.coddoc, g.tipdoc),
  stinsi as(
    SELECT
      coddoc1, coddoc, tipdoc, indexlocal, codobiect, codgeneral, prefixdoc, nrdoc, datadoc, subunitatea, curs, moneda, codobligpif,
      valoarelinie, valdoc,
      CASE
        WHEN valoare = 0 THEN 0
        WHEN valoarelinie = 0 THEN 0
        WHEN Sum( valoarelinie ) OVER (PARTITION BY codobligpif, codcentrui) = 0 THEN 0
        ELSE valoarelinie * valoare/ Sum( valoarelinie ) OVER (PARTITION BY codobligpif, codcentrui)
      END valobliglinie,
      COEFTVA,
      valoare, codpart, codlocatie, termen, an, luna, codcont, codbanca
    FROM (
      SELECT
        i1.codintr1 coddoc1, i.codintr coddoc, i.tipdoc, i1.indexlocal,i1.codobiect, o.codgeneral,i.prefixdoc, i.nrdoc, i.datadoc, i.subunitatea, Coalesce(NULLIF(coalesce(g.curs,0),0),1) curs, coalesce(g.moneda,0) moneda, o.codobligpif,
        (i1.pu*i1.cant+(case when i.tipdoc=3 then 0 else i1.tva end))*coalesce(i1.coefdiscmaj,1)*(case when i1.pu=i1.pretorig then 1 when i1.pu=0 then 0 else i1.pretorig/i1.pu end) valoarelinie, i.valdoc,
        CASE
          WHEN i.tipdoc = 3 and I1.PU * I1.CANT &lt;&gt; 0 THEN (I1.PU * I1.CANT-I1.TVA)/(I1.PU * I1.CANT)
          WHEN i.tipdoc &lt;&gt; 3 AND I1.PU * I1.CANT+I1.TVA &lt;&gt; 0 THEN (I1.PU * I1.CANT)/(I1.PU * I1.CANT+I1.TVA)
          ELSE 1
        END COEFTVA,
        o.valoare, o.codpart, i.codlocatie, o.termen, i.an, i.luna, PKG_LIST_BASE_UTILS_iCont_CodCont(o.icont,o.codpart,i.an*12+i.luna,o.semnificatie) codcont, 0 codbanca,
        coalesce(O.CodCentru,0) CodCentruO, coalesce(i1.codcentru,0) CodCentruI, Max( coalesce(O.CodCentru,0) ) OVER (PARTITION BY i.codintr) CodCentruM
      FROM intrari i
        INNER JOIN intrari1 i1  ON i.codintr    = i1.codintr
        INNER JOIN nartobj  obj ON i1.codobiect = obj.codobiect
        INNER JOIN general  g   ON g.coddoc     = i.codintr and g.tipdoc = i.tipdoc and g.semnificatie &lt;&gt; 600
        INNER JOIN obligpif o   ON g.codgeneral = o.codgeneral'; --AND coalesce(o.codcentru,0) = coalesce(i1.codcentru,0)

    if ConstCC = 1 then
      sSelect := sSelect|| ' AND Nvl(o.codcentru,0) = Nvl(i1.codcentru,0)';
    END IF;
    sSelect := sSelect|| ' WHERE NVL(i.anulat, 0) = 0 and nvl(i.initializari, 0) = 0 AND NVL(i1.codobiect,0) &lt;&gt; 0 AND i.datadoc &lt;= TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')'||COALESCE(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', NULL, NULL, NULL ), '')||
    ') A_PG
    WHERE CodCentruO = (case when CodCentruM=0 then 0 else CodCentruI end)
    UNION ALL
    SELECT
      0 coddoc1, i.codintr coddoc, i.tipdoc, 0 indexlocal, -1 codobiect, o.codgeneral, ''sold initial '' prefixdoc, i.nrdoc, i.datadoc, i.subunitatea, Coalesce(NULLIF(coalesce(g.curs,0),0),1) curs, coalesce(g.moneda,0) moneda, o.codobligpif,
      o.valoare valoarelinie, o.valoare valdoc,
      o.valoare valobliglinie,
      1 COEFTVA,
      o.valoare, o.codpart, i.codlocatie, o.termen, i.an, i.luna, PKG_LIST_BASE_UTILS_iCont_CodCont(o.icont,o.codpart,' || coalesce(AnLunaIni::varchar,'') || ',o.semnificatie) codcont, 0 codbanca
    FROM intrari i
      INNER JOIN general  g ON g.coddoc     = i.codintr and g.tipdoc = i.tipdoc and g.semnificatie &lt;&gt; 600 and g.semnificatie &lt;&gt; 140
      INNER JOIN obligpif o ON g.codgeneral = o.codgeneral
    WHERE coalesce(i.anulat, 0) = 0 and coalesce(i.initializari, 0) = 1 AND i.datadoc &lt;= TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || '
    UNION ALL
    SELECT
      t1.CodTrezor1 CodDoc1, t.CodTrezor CodDoc, t.TipDoc, t1.indexlocal, -2 codobiect, o.codgeneral, t1.doc prefixdoc, t1.nrdoc, t1.datadoc, t.subunitatea, Coalesce(NULLIF(coalesce(g.curs,0),0),1) curs, coalesce(g.moneda,0) moneda, o.codobligpif,
      -o.valoare valoarelinie, -o.valoare valdoc,
      -o.valoare valobliglinie,
      CASE WHEN coalesce(o.valoare,0) = 0 THEN 1 ELSE (o.valoare-coalesce(g.tva,0))/o.valoare END COEFTVA,
      -o.valoare, o.codpart, t1.codlocatie, o.termen, t.An, t.Luna, PKG_LIST_BASE_UTILS_iCont_CodCont(o.icont,o.codpart,t1.an*12+t1.luna,o.semnificatie) cont, t.codbanca
    FROM trezor1 t1
      INNER JOIN general  g ON g.coddoc     = t1.codtrezor1 AND g.semnificatie = 310
      INNER JOIN obligpif o ON g.codgeneral = o.codgeneral
      INNER JOIN trezor   t ON t1.codtrezor = t.codtrezor
    WHERE coalesce(t1.anulat, 0) = 0 AND t1.datadoc &lt;= TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('t',NULL,NULL,NULL),'') || '),
  stingatori as (
    SELECT
      o.CodObligPIF, o.Codgeneral, t.codtrezor CodDoc, t1.codtrezor1 CodDoc1, g.TipDoc, t1.doc PrefixDoc, t1.nrdoc, t1.datadoc, t1.DATADECONT, t1.datadoc as DATA, COALESCE(t1x.datadoc, t1.datadecont, t1.datadoc) DATAPLATA,
      t1.agent, t.Subunitatea, s.codstinspif, s.valoare s_valoare, s.valoare-coalesce(g.tva,0) s_valftva, Coalesce(NULLIF(coalesce(t1.curs,0),0),1) curs, COALESCE(t.monedapers, bc.codmoneda, 0) moneda, t.an, t.luna, t.codbanca
    FROM trezor1 t1
      INNER JOIN trezor    t   ON t1.codtrezor      = t.codtrezor
      INNER JOIN general   g   ON t1.codtrezor1     = g.coddoc and g.tipdoc = t.tipdoc
      INNER JOIN obligpif  o   ON o.codgeneral      = g.codgeneral
      INNER JOIN stingere  s   ON s.codstingatorpif = o.codobligpif
      LEFT  JOIN nbankcont bc  ON bc.codbankcont    = t.codbanca
      LEFT  JOIN general   gc  ON gc.coddoc         = g.coddoc AND gc.semnificatie = 600 AND gc.semnificatie &lt;&gt; g.semnificatie
      LEFT  JOIN obligpif  oc  ON oc.codgeneral     = gc.codgeneral
      LEFT  JOIN stingere  sx  ON sx.codstinspif    = coalesce(oc.codobligpif, o.codobligpif)
      LEFT  JOIN obligpif  ox  ON ox.codobligpif    = sx.codstingatorpif
      LEFT  JOIN general   gx  ON gx.codgeneral     = ox.codgeneral
      LEFT  JOIN trezor1   t1x ON t1x.codtrezor1    = gx.coddoc
    WHERE T1.DATADOC BETWEEN TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'') AND TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')
      AND ((G.TipDoc IN (29, 30, 31, 33) AND t1.TipTranz = 0) OR (t1.TipTranz = 0 AND t1.ObiectTranz = 1)) AND g.semnificatie &lt;&gt; 800' ||
      coalesce(CASE WHEN  NOT gOpt3 THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL) ELSE NULL END ,'') || '
    UNION ALL
    SELECT
      o.CodObligPIF, o.Codgeneral, c.codcompens CodDoc, NULL CodDoc1, g.TipDoc, ''PV'', c.nrdoc, c.datadoc, null DATADECONT, c.datadoc as DATA, c.datadoc DATAPLATA,
      0 Agent, c.Subunitatea, s.codstinspif, s.valoare s_valoare, s.valoare-coalesce(g.tva,0) s_valftva, Coalesce(NULLIF(coalesce(g.curs,0),0),1) curs, coalesce(g.moneda,0) moneda, c.an, c.luna, 0 codbanca
    FROM compens c
      INNER JOIN general  g ON g.coddoc          = c.codcompens
      INNER JOIN obligpif o ON o.codgeneral      = g.codgeneral
      INNER JOIN stingere s ON s.codstingatorpif = o.codobligpif
    WHERE C.DATADOC BETWEEN TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'') AND TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')
      AND G.TipDoc = 28 ' ||
      coalesce(CASE WHEN  NOT gOpt3 THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL) ELSE NULL END ,'') || '),
--  NOBJ1 AS (
--    SELECT codobiect, Max(codobiect1) codobiect1
--    FROM (SELECT codobiect, codobiect1, dense_rank() over(partition by codobiect order by anstart desc, lunastart desc) NR
--          FROM nartobj1 n1
--          WHERE anstart * 12 + lunastart &lt;= ' || coalesce(AnLunaLucru::varchar,'') || '
--         ) aa
--    WHERE NR=1
--    GROUP BY codobiect
--  ),
  UN AS ( --*** structura la fel ca tmp_lst_urmplartiart pt coloane suplimentare ***
    SELECT
      stingatori.coddoc NAV_CodDoc, stingatori.coddoc1 NAV_CodDoc1, stingatori.tipdoc NAV_TipDoc, stinsi.prefixdoc DSTINSPR, stinsi.nrdoc DSTINSNR, stinsi.datadoc DSTINSDATA, stinsi.valoarelinie TOTAL_DOCUMENT,
      sign(stinsi.valoare)*coalesce(stingatori.s_valoare,0)*stinsi.valobliglinie/(case when coalesce(stinsi.valoare, 0)= 0 then 1 else stinsi.valoare end) VAL_STINGATOR,
      sign(stinsi.valoare)*coalesce(stingatori.s_valftva,0)*stinsi.valobliglinie/(case when coalesce(stinsi.valoare, 0)= 0 then 1 else stinsi.valoare end) VAL_STINGFTVA,
      stinsi.coeftva,
      CASE WHEN coalesce(crs_sold.rest, 0) = 0 THEN coalesce(stinsi.valdoc,0) ELSE crs_sold.rest END -
      coalesce(
        SUM(sign(stinsi.valoare)*coalesce(stingatori.s_valoare,0)*stinsi.valobliglinie/(case when coalesce(stinsi.valoare,0)=0 then 1 else stinsi.valoare end))
        OVER (PARTITION BY stinsi.coddoc, stinsi.tipdoc ORDER BY stinsi.indexlocal, stinsi.coddoc1, stinsi.termen, stinsi.codobligpif, stingatori.codobligpif ROWS BETWEEN unbounded preceding AND CURRENT ROW )
        , 0
      ) SOLD_DOC,
      ROW_NUMBER() OVER (PARTITION BY stinsi.coddoc, stinsi.tipdoc ORDER BY stinsi.indexlocal, stinsi.coddoc1, stinsi.termen, stinsi.codobligpif, stingatori.codobligpif) ORDDOC,
      CASE WHEN coalesce(crs_sold.rest, 0) = 0 THEN coalesce(stinsi.valoarelinie,0) WHEN coalesce(stinsi.valdoc,0) = 0 THEN 0 ELSE crs_sold.rest*stinsi.valoarelinie/stinsi.valdoc END -
      coalesce(
        SUM(sign(stinsi.valoare)*coalesce(stingatori.s_valoare,0)*stinsi.valobliglinie/(case when coalesce(stinsi.valoare,0)=0 then 1 else stinsi.valoare end))
        OVER (PARTITION BY stinsi.coddoc, stinsi.tipdoc, stinsi.coddoc1 ORDER BY stinsi.termen, stinsi.codobligpif, stingatori.codobligpif ROWS BETWEEN unbounded preceding AND CURRENT ROW )
        , 0
      ) SOLD_LIN,
      COUNT(1)     OVER (PARTITION BY stinsi.coddoc, stinsi.tipdoc) ORDDOCMAX,
      ROW_NUMBER() OVER (PARTITION BY stinsi.coddoc, stinsi.tipdoc, stinsi.coddoc1 ORDER BY stinsi.termen, stinsi.codobligpif, stingatori.codobligpif) ORDLIN,
      COUNT(1)     OVER (PARTITION BY stinsi.coddoc, stinsi.tipdoc, stinsi.coddoc1) ORDLINMAX,
      stingatori.prefixdoc DSTINGPR, stingatori.nrdoc DSTINGNR, stingatori.datadoc DSTINGDATA, stingatori.DATADECONT, stingatori.DATA, stingatori.DATAPLATA, stinsi.datadoc DATA_STINS,
      stinsi.TERMEN, stinsi.termen SCADENTA, trunc(stingatori.Data - stinsi.datadoc) DIFZILE, CASE WHEN trunc(stingatori.data - stinsi.termen) &gt; 0 then trunc(stingatori.data - stinsi.termen) ELSE 0 END DEPZILE,
      case when trunc(COALESCE(stingatori.datadecont,stingatori.data) - stinsi.termen) &gt; 0 then trunc(COALESCE(stingatori.datadecont,stingatori.data) - stinsi.termen) else 0 end DEPZILEDEC,
      case when trunc(stingatori.dataplata - stinsi.termen) &gt; 0 then trunc(stingatori.dataplata - stinsi.termen) else 0 end DEPZILEPLATA,
      stinsi.codpart, coalesce(stingatori.agent,0) agent_sting, stinsi.codcont, coalesce(stinsi.codlocatie,0) codlocatie, stinsi.coddoc, stinsi.coddoc1, stinsi.tipdoc, stinsi.codobiect,
      stinsi.curs dstinscurs, stinsi.moneda, stinsi.subunitatea dstinssub, stingatori.subunitatea dstingsub,
      stinsi.an dstinsan, stinsi.luna dstinsluna, stingatori.an dstingan, stingatori.luna dstingluna, stingatori.curs dstingcurs, CASE WHEN stinsi.codobiect = -2 THEN stinsi.codbanca ELSE stingatori.codbanca  END codbanca
    FROM stinsi
      ' || sTipJoin || ' JOIN stingatori ON stingatori.codstinspif = stinsi.codobligpif
      LEFT JOIN crs_sold ON crs_sold.coddoc = stinsi.coddoc AND crs_sold.tipdoc = stinsi.tipdoc
    WHERE (coalesce(crs_sold.rest,0) &lt;&gt; 0 OR crs_sold.rest IS NULL) AND stinsi.valobliglinie &lt;&gt; 0)
  SELECT
    (case when ts.codsubunit is NULL then NULL else UN.NAV_CodDoc  end) NAV_CodDoc,
    (case when ts.codsubunit is NULL then NULL else UN.NAV_CodDoc1 end) NAV_CodDoc1,
    (case when ts.codsubunit is NULL then NULL else UN.NAV_TipDoc  end) NAV_TipDoc,
    UN.DSTINSPR, UN.DSTINSNR, UN.DSTINSDATA, (case when UN.ORDLIN=1 then UN.TOTAL_DOCUMENT else 0 end) TOTAL_DOCUMENT, UN.SOLD_LIN + UN.VAL_STINGATOR VAL_NESTINSA_DOCUMENT, UN.VAL_STINGATOR, UN.VAL_STINGATOR * UN.COEFTVA VAL_STINGFTVA,
    UN.SOLD_LIN, (case when UN.ORDLIN=UN.ORDLINMAX then UN.SOLD_LIN end) SOLD_LINF, UN.ORDLIN,
    UN.SOLD_DOC, (case when UN.ORDDOC=UN.ORDDOCMAX then UN.SOLD_DOC end) SOLD_DOCF, UN.ORDDOC,
    UN.DSTINGPR, UN.DSTINGNR, UN.DSTINGDATA, NPART.DEN_PART, AG.OBS, UN.DATADECONT, UN.DATA, UN.DATAPLATA, UN.DATA_STINS, UN.TERMEN, mon.den_moneda, SubStins.den_subunit, SubSting.den_subunit,
    UN.SCADENTA, UN.DIFZILE, UN.DEPZILE, UN.DEPZILEDEC, UN.DEPZILEPLATA, C.SIMBOL, (case un.codobiect when -1 then ''INITIALIZARE'' when -2 then ''AVANS TREZORERIE'' else o.denumire end), O.CODEXTERN, O.CODINTERN, PROD.DEN_PART, CA.SIMBOL,
    UN.DSTINSCURS, UN.DSTINSAN, UN.DSTINSLUNA, UN.DSTINGCURS, UN.DSTINGAN, UN.DSTINGLUNA, (case when I1.TIPLINIE=''='' then G2.DEN else G1.DEN_GEST end), (case when I1.TIPLINIE=''='' then G2.SIMB else G1.SIMBOL end), BC.NRCONT ' || sCurs || gUserAlias || '
  FROM UN
    LEFT JOIN intrari             i        on i.codintr     = un.coddoc AND i.tipdoc = un.tipdoc
    LEFT JOIN intrari1            i1       on i1.codintr1   = un.coddoc1 AND i1.codintr = i.codintr
    LEFT JOIN nartobj             o        ON o.codobiect   = un.codobiect
    LEFT JOIN npers               agp      ON agp.codpers   = un.agent_sting
    LEFT JOIN npart               npart    ON npart.codpart = un.codpart
    LEFT JOIN nclasep             clsp     on coalesce(npart.codclasa, 0) = clsp.codclasep
    LEFT JOIN nagenda             ag       ON UN.codlocatie = ag.codagenda
    LEFT JOIN nlocalit            loc      on ag.codlocalit = loc.codlocalit
    LEFT JOIN njudet              jud      on loc.codjudet  = jud.codjudet
    LEFT JOIN nmonede             mon      ON mon.codmoneda = coalesce(UN.moneda,0)
    LEFT JOIN pretm               pm       on pm.codobiect  = o.CodObiect and pm.implicit = 1 and pm.subunitatea = ' || getSUBUNITATE()::varchar || '
    LEFT JOIN nsubunit            SubSting ON SubSting.codsubunit = UN.dstingsub
    LEFT JOIN nsubunit            SubStins ON SubStins.codsubunit = UN.dstinssub
    LEFT JOIN tmp_subunitdedicate ts       ON ts.codsubunit = UN.dstingsub
    LEFT JOIN npart               prod     ON prod.codpart  = o.codproducator
    LEFT JOIN nart                a        ON a.codarticol  = o.codarticol
    LEFT JOIN nclasea             ca       ON ca.codclasea  = a.clasa
     --LEFT JOIN nobj1       on nobj1.codobiect  = o.codobiect
     --LEFT JOIN nartobj1 n1 on nobj1.codobiect1 = n1.codobiect1
    LEFT JOIN nartobj1            n1       on n1.codobiect   = o.codobiect AND ' || coalesce(AnLunaLucru::varchar,'') || ' BETWEEN n1.ALStart and n1.ALStop
    LEFT JOIN nmonede             monprest ON monprest.codmoneda = coalesce(n1.codmoneda,0)
    LEFT JOIN nartcli             ac       ON ac.codobiect   = un.codobiect AND ac.codpart = un.codpart
    LEFT JOIN ncont               c        ON c.codcont      = un.codcont
    LEFT JOIN nbankcont           bc       ON bc.codbankcont = un.codbanca
    LEFT JOIN nbank               b        ON b.codbank  = bc.codbank
    LEFT JOIN ngest               g1       ON g1.codgest = i1.gestact
    LEFT JOIN (
                SELECT ns.codintr1, n.codintr, n.tipnir,
                       --vc2_nt_to_vc3200(CAST(COLLECT(DISTINCT ng.den_gest) AS vc2_nt)) DEN,
                       fnc_array_to_vc3200(array_agg(DISTINCT ng.den_gest)) DEN,
                       --vc2_nt_to_vc3200(CAST(COLLECT(DISTINCT ng.simbol) AS vc2_nt)) SIMB
                       fnc_array_to_vc3200(array_agg(DISTINCT ng.simbol)) SIMB
                FROM nirstoc ns
                  INNER JOIN nir   n  ON n.codnir   = ns.codnir
                  INNER JOIN ngest ng On ng.codgest = n.gest
                WHERE ng.codgest &lt;&gt; 0
                GROUP BY ns.codintr1, n.codintr, n.tipnir
              ) g2 ON g2.codintr1 = i1.codintr1 AND g2.codintr = i.codintr AND g2.tipnir = i.tipdoc' || gSuplJoins;

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utilaje_processlist</obj_name>
  <obj_hashval>27b1edf23bb5b34778c9b58cf4ab1e28</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utilaje_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sWhere           varchar := '';
  gSuplCols        VARCHAR :=   'NIRSTOC NS, NIR NIR, NARTOBJ NOBJ, NGEST NG, NPART NP, NARTAMB AA, NAGENDA NAG, NLOCALIT LAG, NJUDET JAG, TMP_UTILIZATOR UTILIZATOR,'||
                               'UTILAJE U, UTILAJE1 U1';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  gAllUtilaje      boolean := current_setting('PKG_LIST_SELUTILAJE.gAllUtilaje', true)::boolean;
BEGIN
  --Florin 09.04.2024 - fixat 61627
  --Florin 12.09.2023 - sinc. Oracle
  --Adina 16 septembrie 2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = NOBJ.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = NOBJ.CODOBIECT',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_UTILAJE.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sWhere := '
  WHERE U.CODUTILAJ::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODUTILAJ'')';

  IF gAllUtilaje THEN
    sWhere := '';
  END IF;

  sWhere := sWhere || '
   AND CASE
         WHEN U.TIP IS NULL AND U.CODPART &gt; 0 THEN 2
         ELSE
           CASE
             WHEN (SELECT COUNT(*) FROM UTILAJE1 WHERE CODUTILAJ = U.CODUTILAJ) &gt; 0 AND U.TIP IS NULL THEN 1
             ELSE coalesce(U.TIP,0)
           END
       END = 1 ';

  sInsert :=
  'INSERT INTO ' || tmpName || ' (
    DENUMIRE,NRINVENTAR,ETICHETA,TIPUTILAJ,FLOTA,NRCONTR,CARNETCONTR,DATA,
    STATUS_DEPO,
    ACTIV,
    STATUS_SERVICE,
    OBS, Sed_Adr, Sed_Loc, Sed_Jud,
    Operator, DEN_PART,DEN_GEST,OBS_UTILAJ,INDEXLOCAL,
    MAXIM, STARE_ESTETICA ' || gUserFields || ')
  SELECT
    NOBJ.DENUMIRE, U.NRINVENTAR,U.ETICHETA,U.TIPUTILAJ,U.FLOTA, U1.NRCONTR,U1.CARNETCONTR,U1.DATA,
    (case U1.STATUS_DEPO
        when 1 then ''plasat la partener''
        when 2 then ''Plasabil''
        when 3 then ''Defect/Reparatii''
        when 4 then ''Casabil''
        when 5 then ''Donatie''
        when 6 then ''Plasat la partener pt vanzare''
        when 7 then ''Plasat la partener pt depozitare''
     end) STATUS_DEPO,
    (case U1.STATUS_PART when 1 then ''...'' when 2 then ''Da'' when 3 then ''Nu'' end) Activ,
    (case U1.STATUS_SERVICE when 1 then ''Initial'' when 2 then ''Revizie anuala'' when 3 then ''Incident'' else ''...'' end) STATUS_SERVICE,
    NAG.OBS, fnc_GETADRESA(NAG.SECTOR, NAG.STRADA, NAG.NR1, NAG.NR2, NAG.BLOC, NAG.SCARA, NAG.ETAJ, NAG.APART, NAG.CODPOSTAL), LAG.DEN_LOCALIT, JAG.DEN_JUDET,
    UTILIZATOR.Nume, NP.DEN_PART,NG.DEN_GEST,U1.OBS OBS_UTILAJ, u1.indexlocal,
    max(u1.indexlocal) over (partition by u1.codutilaj) maxim,
    (case U1.ESTETIC
        when 1 then ''Ok''
        when 2 then ''De colantat integral''
        when 3 then ''De colantat fata''
        when 4 then ''De colantat spate''
        when 5 then ''De colantat laterale''
     end) ' || gUserAlias || '
  FROM UTILAJE U
    INNER JOIN NARTOBJ NOBJ             ON U.CODOBIECT    = NOBJ.CODOBIECT
    INNER JOIN UTILAJE1 U1               ON U1.CODUTILAJ   = U.CODUTILAJ
    LEFT JOIN MIFIX M                   ON M.NRINVENTAR   = U.NRINVENTAR AND M.TIP = ''MF''
    LEFT JOIN (SELECT DISTINCT CODMIFIX,CODNIRSTOC FROM MIFIX1 ) M1 ON M1.CODMIFIX = M.CODMIFIX
    LEFT JOIN NIRSTOC NS                 ON NS.CODNIRSTOC  = M1.CODNIRSTOC
    LEFT JOIN NIR NIR                   ON NIR.CODNIR     = NS.CODNIR
    LEFT JOIN NGEST NG                   ON NG.CODGEST     = NIR.GEST
    LEFT JOIN NPART NP                   ON NP.CODPART     = U1.CODPART
    LEFT JOIN NAGENDA NAG               ON NAG.CODAGENDA  = U1.CODLOCATIE
    LEFT JOIN NLOCALIT LAG               ON LAG.CODLOCALIT = NAG.CODLOCALIT
    LEFT JOIN NJUDET JAG                 ON JAG.CODJUDET   = LAG.CODJUDET
    LEFT JOIN NARTAMB AA                 ON AA.CODOBIECT   = U.CODOBIECT AND AA.UMSEC = NS.UMSEC
    LEFT JOIN TMP_UTILIZATOR UTILIZATOR ON UTILIZATOR.CODUTILIZATOR = U1.USERID' || gSuplJoins || sWhere;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_esteobiectvalid</obj_name>
  <obj_hashval>a4796f7706ba42f22eefd9059b374db6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_esteobiectvalid(INOUT wme_result numeric, INOUT acodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  iResult numeric := 0;
  cnt     numeric;
begin
 SELECT count( *) INTO cnt FROM tmp_manevra_liste WHERE filtru = 'CODOBIECT';
 IF  cnt = 0 THEN
   WME_Result :=  1;
   RETURN;
 ELSE
   SELECT count( *) INTO cnt FROM tmp_manevra_liste WHERE filtru = 'CODOBIECT' and  valoare = aCodObiect::varchar;
   IF  cnt = 0 THEN
     WME_Result :=  0;
     RETURN;
   ELSE
     WME_Result :=  1;
     RETURN;
   END IF;
 END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_extractanluna</obj_name>
  <obj_hashval>351bcfb51d7e797f513d8bf547ded672</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_extractanluna(INOUT panluna numeric, INOUT pan numeric, INOUT pluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  pLuna := Mod( pAnLuna, 12);
  pLuna := CASE pLuna WHEN 0 THEN 12 ELSE pLuna END ;
  pAn   := (pAnLuna - pLuna)  / 12;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_get_part</obj_name>
  <obj_hashval>11989acfa02da650574a83019df09d15</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_get_part(INOUT wme_result character varying, INOUT v_cod numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_den varchar;
begin
  SELECT den_part INTO v_den FROM npart WHERE codpart = v_cod;
  WME_Result :=  v_den;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getcoefdiscmonetar</obj_name>
  <obj_hashval>925dd00e99cb8b6ccd7dc9e80b0536b6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getcoefdiscmonetar(pcodies numeric, ptiplinie character varying, pcodobiect numeric, pcontserv numeric, pcodioart numeric, ptipcoef numeric, pvallin numeric DEFAULT 0, ptvalin numeric DEFAULT 0)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vRes            NUMERIC;
  vAn             NUMERIC;
  vLuna           NUMERIC;
  vAVD            NUMERIC;
  vATD            NUMERIC;
  vProcTva        NUMERIC;
  vCDMCodIes      NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMCodIes'     , TRUE),'')::numeric;
  vCDMNr          NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMNr'         , TRUE),'')::numeric;
  vCDMAn          NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMAn'         , TRUE),'')::numeric;
  vCDMLuna        NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMLuna'       , TRUE),'')::numeric;
  vCDMValDoc      NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMValDoc'     , TRUE),'')::NUMERIC;
  vCDMTvaDoc      NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMTvaDoc'     , TRUE),'')::numeric;
  vCDMValDisc     NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMValDisc'    , TRUE),'')::numeric;
  vCDMTvaDisc     NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMTvaDisc'    , TRUE),'')::numeric;
  sCDMArtExcl     VARCHAR := NULLIF(current_setting('PKG_LIST_BASE_UTILS.sCDMArtExcl'    , TRUE),'');
  vCDMValLin      NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMValLin'     , TRUE),'')::numeric;
  vCDMTvaLin      NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMTvaLin'     , TRUE),'')::numeric;
  vCDMCIntermedCM NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMCIntermedCM', TRUE),'')::numeric;
  vCDMConIncFact  NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMConIncFact' , TRUE),'')::numeric;
  vCDMCoteDisc    NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMCoteDisc'   , TRUE),'')::numeric;
  vCDMProc1       NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMProc1'      , TRUE),'')::numeric;
  vCDMProc2       NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMProc2'      , TRUE),'')::numeric;
  vCDMProc3       NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMProc3'      , TRUE),'')::numeric;
  vCDMProc4       NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMProc4'      , TRUE),'')::numeric;
  vCDMProc5       NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMProc5'      , TRUE),'')::numeric;
  vCDMValDisc1    NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMValDisc1'   , TRUE),'')::numeric;
  vCDMValDisc2    NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMValDisc2'   , TRUE),'')::numeric;
  vCDMValDisc3    NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMValDisc3'   , TRUE),'')::numeric;
  vCDMValDisc4    NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMValDisc4'   , TRUE),'')::numeric;
  vCDMValDisc5    NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMValDisc5'   , TRUE),'')::numeric;
  vCDMTvaDisc1    NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMTvaDisc1'   , TRUE),'')::numeric;
  vCDMTvaDisc2    NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMTvaDisc2'   , TRUE),'')::numeric;
  vCDMTvaDisc3    NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMTvaDisc3'   , TRUE),'')::numeric;
  vCDMTvaDisc4    NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMTvaDisc4'   , TRUE),'')::numeric;
  vCDMTvaDisc5    NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMTvaDisc5'   , TRUE),'')::numeric;
  vCDMValLin1     NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMValLin1'    , TRUE),'')::numeric;
  vCDMValLin2     NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMValLin2'    , TRUE),'')::numeric;
  vCDMValLin3     NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMValLin3'    , TRUE),'')::numeric;
  vCDMValLin4     NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMValLin4'    , TRUE),'')::numeric;
  vCDMValLin5     NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMValLin5'    , TRUE),'')::numeric;
  vCDMTvaLin1     NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMTvaLin1'    , TRUE),'')::numeric;
  vCDMTvaLin2     NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMTvaLin2'    , TRUE),'')::numeric;
  vCDMTvaLin3     NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMTvaLin3'    , TRUE),'')::numeric;
  vCDMTvaLin4     NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMTvaLin4'    , TRUE),'')::numeric;
  vCDMTvaLin5     NUMERIC := NULLIF(current_setting('PKG_LIST_BASE_UTILS.vCDMTvaLin5'    , TRUE),'')::numeric;
  vRec record;
BEGIN
  --Florin 11.11.2025 - fixat 67253
  --Florin 22.05.2023 - fixat 58365
  --Florin 16.05.2023 - fixat 58287
  --Florin 09.05.2022 - sinc. Oracle
  --Florin 28.04.2022 - sinc. Oracle (27.04.2022)
  --Stef  21.12.2020 Curatenie
  --Adina 22.10.2020; 23.11.2020
  vRes := 1;
  IF  Coalesce(vCDMCodIes, 0) &lt;&gt; Coalesce(pCodIes, 0) THEN
    SELECT Count(1) INTO vCDMCoteDisc
    FROM discmonetar
    WHERE codies = pCodIes;

    SELECT
      Sum(Coalesce(i1.valdiscpret, 0)),
      Sum(CASE WHEN Coalesce(i1.pu * i1.cant, 0) = 0 THEN 0 ELSE Coalesce(i1.tva * i1.valdiscpret / (  i1.pu * i1.cant) , 0) END)
    INTO vAVD, vATD
    FROM iesiri1 i1
    WHERE i1.codies = pCodIes;

    SELECT i.CodIes, i.An, i.Luna, i.ValDoc, i.TvaDoc, Round((i.ValDiscount - vAVD), 7), Round((i.TvaDiscount - vATD), 7)
    INTO vCDMCodIes, vAn, vLuna, vCDMValDoc, vCDMTvaDoc, vCDMValDisc, vCDMTvaDisc
    FROM iesiri i
    WHERE codies = pCodIes;
    IF  Coalesce(vCDMAn, 0) &lt;&gt; vAn OR  Coalesce(vCDMLuna, 0) &lt;&gt; vLuna THEN
      PERFORM pkg_globals_SetSeparator(',');

      SELECT STRING_AGG(x,',')
      INTO sCDMArtExcl
      FROM (
              SELECT Coalesce(fnc_GetValConstanta('ArtFaraDiscMonetar', vAn, vLuna),'0') X
        UNION SELECT Coalesce(fnc_GetValConstanta('ArtIncasUlterior',   vAn, vLuna),'0') X
      ) A_PG;
      sCDMArtExcl     := ',' || COALESCE(sCDMArtExcl,'') || ',';
      vCDMCIntermedCM := nullif(fnc_GetValConstanta('CIntermedCM',         vAn, vLuna), '')::numeric;
      vCDMConIncFact  := nullif(fnc_GetValConstanta('ContIncasareFactura', vAn, vLuna), '')::numeric;
      vCDMAn          :=vAn;
      vCDMLuna        :=vLuna;
    END IF;
    SELECT SUM(i1.pu * i1.cant) VALLIN, SUM(i1.tva) TVALIN
    INTO vCDMValLin, vCDMTvaLin
    FROM iesiri1 i1
    WHERE i1.codies = pCodIes AND  i1.tiplinie &lt;&gt; 'V'
      AND  Coalesce(i1.ContServ, -1) &lt;&gt; vCDMCIntermedCM
      AND  position(','||coalesce(i1.CodObiect::varchar ,'')||',' in sCDMArtExcl) = 0
      AND  Coalesce(i1.valdiscpret, 0) = 0;

  vCDMProc1 := 0; vCDMValDisc1 := 0; vCDMTvaDisc1 := 0; vCDMValLin1 := 0; vCDMTvaLin1 := 0;
  vCDMProc2 := 0; vCDMValDisc2 := 0; vCDMTvaDisc2 := 0; vCDMValLin2 := 0; vCDMTvaLin2 := 0;
  vCDMProc3 := 0; vCDMValDisc3 := 0; vCDMTvaDisc3 := 0; vCDMValLin3 := 0; vCDMTvaLin3 := 0;
  vCDMProc4 := 0; vCDMValDisc4 := 0; vCDMTvaDisc4 := 0; vCDMValLin4 := 0; vCDMTvaLin4 := 0;
  vCDMProc5 := 0; vCDMValDisc5 := 0; vCDMTvaDisc5 := 0; vCDMValLin5 := 0; vCDMTvaLin5 := 0;

  IF vCDMCoteDisc &gt; 0 THEN vCDMNr := 0;
      FOR vRec IN (
        SELECT
          gm.ProcTVA, gm.ValLin, gm.TvaLin,
          Round(dm.Discount    - gm.AVD,7) ValDisc,
          Round(dm.TvaDiscount - gm.ATD,7) TvaDisc
        FROM (
          SELECT ProcTVA, SUM(ValLin) ValLin, SUM(TvaLin) TvaLin, Sum(AVD) AVD, Sum(ATD) ATD
          FROM (
            SELECT
              PKG_LIST_BASE_UTILS_MATCH_TVA_PROC(i1.tva*100/(i1.cant*i1.pu-i1.tva), vAn*12+vLuna) ProcTVA,
              CASE WHEN Coalesce(i1.valdiscpret, 0) = 0 THEN i1.pu*i1.cant ELSE 0 END ValLin,
              CASE WHEN Coalesce(i1.valdiscpret, 0) = 0 THEN i1.tva        ELSE 0 END TvaLin,
              Coalesce(i1.valdiscpret,0) AVD,
              CASE WHEN Coalesce(i1.pu*i1.cant,0) = 0 THEN 0 ELSE Coalesce(i1.tva * i1.valdiscpret/(i1.pu*i1.cant),0) END ATD
            FROM iesiri1 i1
            WHERE i1.codies = pCodIes
              AND i1.tiplinie &lt;&gt; 'V'
              AND Coalesce(i1.ContServ,-1) &lt;&gt; vCDMCIntermedCM
              AND position(','||i1.CodObiect||',' in sCDMArtExcl) = 0
              AND Coalesce(i1.cant*i1.pu, 0) &lt;&gt; Coalesce(i1.tva, 0)
          ) ssub
          GROUP BY ProcTVA
        ) gm
        INNER JOIN (
          SELECT DM.PROCTVA, DM.DISCOUNT, DM.TVADISCOUNT
          FROM DISCMONETAR DM
          WHERE DM.codies = pCodIes
        ) dm ON DM.ProcTVA = GM.ProcTVA
        ORDER BY gm.ProcTVA
      ) LOOP
        vCDMNr := vCDMNr + 1;
        CASE vCDMNr
          WHEN 1 THEN vCDMProc1 := vRec.ProcTVA; vCDMValDisc1 := vRec.ValDisc; vCDMTvaDisc1 := vRec.TvaDisc; vCDMValLin1 := vRec.ValLin; vCDMTvaLin1 := vRec.TvaLin;
          WHEN 2 THEN vCDMProc2 := vRec.ProcTVA; vCDMValDisc2 := vRec.ValDisc; vCDMTvaDisc2 := vRec.TvaDisc; vCDMValLin2 := vRec.ValLin; vCDMTvaLin2 := vRec.TvaLin;
          WHEN 3 THEN vCDMProc3 := vRec.ProcTVA; vCDMValDisc3 := vRec.ValDisc; vCDMTvaDisc3 := vRec.TvaDisc; vCDMValLin3 := vRec.ValLin; vCDMTvaLin3 := vRec.TvaLin;
          WHEN 4 THEN vCDMProc4 := vRec.ProcTVA; vCDMValDisc4 := vRec.ValDisc; vCDMTvaDisc4 := vRec.TvaDisc; vCDMValLin4 := vRec.ValLin; vCDMTvaLin4 := vRec.TvaLin;
          WHEN 5 THEN vCDMProc5 := vRec.ProcTVA; vCDMValDisc5 := vRec.ValDisc; vCDMTvaDisc5 := vRec.TvaDisc; vCDMValLin5 := vRec.ValLin; vCDMTvaLin5 := vRec.TvaLin;
        END CASE;
      END LOOP;
    END IF;
  end if;

  vProcTva := 0;
  IF (Coalesce(pValLin, 0) &lt;&gt; 0) AND (Coalesce(pTVALin, 0) &lt;&gt; 0) AND (Coalesce(pValLin, 0) - Coalesce(pTVALin, 0) &lt;&gt; 0) THEN
    vProcTva := PKG_LIST_BASE_UTILS_MATCH_TVA_PROC(pTVALin*100/(pValLin-pTVALin), vCDMAn*12+vCDMLuna);
  END IF;

  vRes :=
    CASE
      WHEN vCDMValDisc = 0 AND vCDMTvaDisc = 0          THEN 1
      WHEN pTipLinie = 'V'                              THEN 1
      WHEN pContServ = vCDMCIntermedCM                  THEN 1
      WHEN pCodIOArt = vCDMConIncFact                   THEN 1
      WHEN position(','||pCodObiect||',' in sCDMArtExcl) &gt; 0 THEN 1
      -- pTipCoef = 0 -- pret/val unitar incl.TVA
      WHEN pTipCoef = 0 AND vCDMValLin=0                THEN 1
      WHEN pTipCoef = 0 AND vCDMCoteDisc = 0 AND (vCDMValLin) &lt;&gt; 0 THEN 1 + vCDMValDisc/vCDMValLin

      WHEN pTipCoef = 0 AND vCDMProc1 = vProcTva AND (vCDMValLin1) &lt;&gt; 0       THEN 1 + vCDMValDisc1/vCDMValLin1
      WHEN pTipCoef = 0 AND vCDMProc2 = vProcTva AND (vCDMValLin2) &lt;&gt; 0       THEN 1 + vCDMValDisc2/vCDMValLin2
      WHEN pTipCoef = 0 AND vCDMProc3 = vProcTva AND (vCDMValLin3) &lt;&gt; 0       THEN 1 + vCDMValDisc3/vCDMValLin3
      WHEN pTipCoef = 0 AND vCDMProc4 = vProcTva AND (vCDMValLin4) &lt;&gt; 0       THEN 1 + vCDMValDisc4/vCDMValLin4
      WHEN pTipCoef = 0 AND vCDMProc5 = vProcTva AND (vCDMValLin5) &lt;&gt; 0       THEN 1 + vCDMValDisc5/vCDMValLin5

      -- pTipCoef = 1 -- pret/unitar excl.TVA
      WHEN pTipCoef = 1 AND vCDMValLin-vCDMTvaLin=0     THEN 1
      WHEN pTipCoef = 1 AND vCDMCoteDisc = 0  AND  (vCDMValLin-vCDMTvaLin)  &lt;&gt; 0           THEN 1 + (vCDMValDisc - vCDMTvaDisc)/(vCDMValLin-vCDMTvaLin)

      WHEN pTipCoef = 1 AND vCDMProc1 = vProcTva  AND (vCDMValLin1-vCDMTvaLin1)  &lt;&gt; 0      THEN 1 + (vCDMValDisc1 - vCDMTvaDisc1)/(vCDMValLin1-vCDMTvaLin1)
      WHEN pTipCoef = 1 AND vCDMProc2 = vProcTva  AND (vCDMValLin2-vCDMTvaLin2)  &lt;&gt; 0      THEN 1 + (vCDMValDisc2 - vCDMTvaDisc2)/(vCDMValLin2-vCDMTvaLin2)
      WHEN pTipCoef = 1 AND vCDMProc3 = vProcTva  AND (vCDMValLin3-vCDMTvaLin3)  &lt;&gt; 0      THEN 1 + (vCDMValDisc3 - vCDMTvaDisc3)/(vCDMValLin3-vCDMTvaLin3)
      WHEN pTipCoef = 1 AND vCDMProc4 = vProcTva  AND (vCDMValLin4-vCDMTvaLin4)  &lt;&gt; 0      THEN 1 + (vCDMValDisc4 - vCDMTvaDisc4)/(vCDMValLin4-vCDMTvaLin4)
      WHEN pTipCoef = 1 AND vCDMProc5 = vProcTva  AND (vCDMValLin5-vCDMTvaLin5)  &lt;&gt; 0      THEN 1 + (vCDMValDisc5 - vCDMTvaDisc5)/(vCDMValLin5-vCDMTvaLin5)

      -- pTipCoef = 2 -- TVA
      WHEN pTipCoef = 2 AND vCDMTvaLin = 0              THEN 1
      WHEN pTipCoef = 2 AND vCDMCoteDisc = 0 AND (vCDMValLin) &lt;&gt; 0           THEN 1 + vCDMTvaDisc/vCDMTvaLin

      WHEN pTipCoef = 2 AND vCDMProc1 = vProcTva AND (vCDMTvaLin1) &lt;&gt; 0       THEN 1 + vCDMTvaDisc1/vCDMTvaLin1
      WHEN pTipCoef = 2 AND vCDMProc2 = vProcTva AND (vCDMTvaLin2) &lt;&gt; 0       THEN 1 + vCDMTvaDisc2/vCDMTvaLin2
      WHEN pTipCoef = 2 AND vCDMProc3 = vProcTva AND (vCDMTvaLin3) &lt;&gt; 0       THEN 1 + vCDMTvaDisc3/vCDMTvaLin3
      WHEN pTipCoef = 2 AND vCDMProc4 = vProcTva AND (vCDMTvaLin4) &lt;&gt; 0       THEN 1 + vCDMTvaDisc4/vCDMTvaLin4
      WHEN pTipCoef = 2 AND vCDMProc5 = vProcTva AND (vCDMTvaLin5) &lt;&gt; 0       THEN 1 + vCDMTvaDisc5/vCDMTvaLin5
      ELSE 1
  END ;

  perform set_config('PKG_LIST_BASE_UTILS.vCDMCodIes'     ,vCDMCodIes::varchar     ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMNr'         ,vCDMNr::varchar         ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMAn'         ,vCDMAn::varchar         ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMLuna'       ,vCDMLuna::varchar       ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMValDoc'     ,vCDMValDoc::varchar     ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMTvaDoc'     ,vCDMTvaDoc::varchar     ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMValDisc'    ,vCDMValDisc::varchar    ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMTvaDisc'    ,vCDMTvaDisc::varchar    ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMValLin'     ,vCDMValLin::varchar     ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMTvaLin'     ,vCDMTvaLin::varchar     ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMCIntermedCM',vCDMCIntermedCM::varchar,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMConIncFact' ,vCDMConIncFact::varchar ,false);
  perform set_config('PKG_LIST_BASE_UTILS.sCDMArtExcl'    ,sCDMArtExcl::varchar    ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMCoteDisc'   ,vCDMCoteDisc::varchar   ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMProc1'      ,vCDMProc1::varchar      ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMProc2'      ,vCDMProc2::varchar      ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMProc3'      ,vCDMProc3::varchar      ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMProc4'      ,vCDMProc4::varchar      ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMProc5'      ,vCDMProc5::varchar      ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMValDisc1'   ,vCDMValDisc1::varchar   ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMValDisc2'   ,vCDMValDisc2::varchar   ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMValDisc3'   ,vCDMValDisc3::varchar   ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMValDisc4'   ,vCDMValDisc4::varchar   ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMValDisc5'   ,vCDMValDisc5::varchar   ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMTvaDisc1'   ,vCDMTvaDisc1::varchar   ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMTvaDisc2'   ,vCDMTvaDisc2::varchar   ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMTvaDisc3'   ,vCDMTvaDisc3::varchar   ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMTvaDisc4'   ,vCDMTvaDisc4::varchar   ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMTvaDisc5'   ,vCDMTvaDisc5::varchar   ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMValLin1'    ,vCDMValLin1::varchar    ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMValLin2'    ,vCDMValLin2::varchar    ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMValLin3'    ,vCDMValLin3::varchar    ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMValLin4'    ,vCDMValLin4::varchar    ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMValLin5'    ,vCDMValLin5::varchar    ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMTvaLin1'    ,vCDMTvaLin1::varchar    ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMTvaLin2'    ,vCDMTvaLin2::varchar    ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMTvaLin3'    ,vCDMTvaLin3::varchar    ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMTvaLin4'    ,vCDMTvaLin4::varchar    ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vCDMTvaLin5'    ,vCDMTvaLin5::varchar    ,false);
  RETURN vRes;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getoldal_iopers1</obj_name>
  <obj_hashval>d0597ca623ae4eaa0f045561c83c24de</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getoldal_iopers1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.oldAL_IOPERS1', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getparintenivelclsp</obj_name>
  <obj_hashval>bc79c4b80f0b5144525b7480e7614d57</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getparintenivelclsp(anivel numeric, acodclasea numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vNivel NUMERIC(20);
  vCodParinte NUMERIC(20);
  vRez varchar(100);
  vSimbol varchar(100);
BEGIN
  --Florin 20.03.2023 - sinc. Oracle (17.03.2023)
  --Florin 16.05.2022 - sinc. Oracle
  vrez := '';
  begin
    select codparinte, nivel, Simbol into vCodParinte, vNivel, vSimbol from nclasep where codclasep = acodclasep;
  exception when others then vNivel := 0; vCodParinte := 0;
  end;
  if aNivel = vNivel then vRez := vSimbol;
    else if vCodParinte &gt; 0 then vRez := GetParinteNivelClsp(aNivel, vCodParinte); end if;
  end if;
  return vRez;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getsoldpart</obj_name>
  <obj_hashval>9781ffca42ea288a16cf86d730d704ff</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getsoldpart(pcodpart numeric, pcodlocatie numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vSql   varchar;
  vSold numeric;
BEGIN
  --Adina 23 septembrie 2020
  PERFORM PKG_NOMPART_SET_PART_CURENT( pCodPart);
  PERFORM PKG_MONEDE_SET_MONEDA_CURENTA( -1);

  vSql := '
  WITH OBLIG AS (
    SELECT
      V.CodLocatie, V.Subunitatea,
      -V.REST * Coalesce(NULLIF(coalesce(V.CURS,0),0),1) RESTREAL, -V.VALOARE * Coalesce(NULLIF(coalesce(V.CURS,0),0),1) VALREAL
    FROM ( ' || V_OBLIG_FURN() || ' ) V
    UNION ALL
    SELECT
      V.CodLocatie, V.Subunitatea,
      V.REST * Coalesce(NULLIF(coalesce(V.CURS,0),0),1)  RESTREAL, V.VALOARE * Coalesce(NULLIF(coalesce(V.CURS,0),0),1)  VALREAL
    FROM ( ' || V_INTRARI_ROSU_FURN() || ' ) V
    UNION ALL
    SELECT
      V.CodLocatie, V.Subunitatea,
      V.REST * Coalesce(NULLIF(coalesce(V.CURS,0),0),1)  RESTREAL, V.VALOARE * Coalesce(NULLIF(coalesce(V.CURS,0),0),1)  VALREAL
      FROM ( ' || V_AVANS_FURN_TREZOR() || ' ) V
    UNION ALL
    SELECT
      V.CodLocatie, V.Subunitatea,
      V.REST * Coalesce(NULLIF(coalesce(V.CURS,0),0),1)  RESTREAL, V.VALOARE * Coalesce(NULLIF(coalesce(V.CURS,0),0),1)  VALREAL
    FROM ( ' || V_AVANS_FURN_FACTURABILE() || ' ) V
    UNION ALL
    SELECT
      V.CodLocatie, V.Subunitatea,
      V.REST * Coalesce(NULLIF(coalesce(V.CURS,0),0),1)  RESTREAL, V.VALOARE * Coalesce(NULLIF(coalesce(V.CURS,0),0),1)  VALREAL
    FROM ( ' || V_OBLIG_CLIENT() || ' ) V
    UNION ALL
    SELECT
      V.CodLocatie, V.Subunitatea,
      -V.REST * Coalesce(NULLIF(coalesce(V.CURS,0),0),1) RESTREAL, -V.VALOARE * Coalesce(NULLIF(coalesce(V.CURS,0),0),1) VALREAL
    FROM ( ' || V_IESIRI_ROSU_CLIENT() || ' ) V
    UNION ALL
    SELECT
      V.CodLocatie, V.Subunitatea,
      -V.REST * Coalesce(NULLIF(coalesce(V.CURS,0),0),1) RESTREAL, -V.VALOARE * Coalesce(NULLIF(coalesce(V.CURS,0),0),1) VALREAL
    FROM ( ' || V_AVANS_CLIENT_TREZOR() || ' ) V
    UNION ALL
    SELECT
      V.CodLocatie, V.Subunitatea,
      -V.REST * Coalesce(NULLIF(coalesce(V.CURS,0),0),1) RESTREAL, -V.VALOARE * Coalesce(NULLIF(coalesce(V.CURS,0),0),1) VALREAL
    FROM ( ' || V_AVANS_CLIENT_FACTURABILE() || ' ) V
  )
  SELECT Sum (RESTREAL)
  FROM OBLIG ' || COALESCE(PKG_LIST_BASE_UTILS_COND_SUBUNIT('', 'SUBUNITATEA', '
  WHERE',NULL),'') || coalesce(CASE WHEN  Coalesce( pCodLocatie, 0) &lt;&gt; 0 THEN ' AND CodLocatie = ' || pCodLocatie::varchar END,'') ;

  EXECUTE vSql INTO vSold;
  vSold := Coalesce( vSold, 0);
  RETURN vSold;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvtt0_al</obj_name>
  <obj_hashval>555925ee939d58d92670caf6cedc543c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvtt0_al(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vTT0_AL', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getvtt0_cntjvartneimp</obj_name>
  <obj_hashval>bb2a66e91dd8267b224f81a2a100ac1e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getvtt0_cntjvartneimp(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.vTT0_CntJVARTNEIMP', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_make_idx_tmp_lst_scad</obj_name>
  <obj_hashval>42b4a97334fee5c6a15872a802f24768</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_make_idx_tmp_lst_scad()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  BEGIN
    EXECUTE 'CREATE INDEX idx_tmp_lst_scad_stins ON TMP_LST_SCAD_STINS (codstinspif)';
  EXCEPTION WHEN OTHERS THEN
    NULL;
  END;

  BEGIN
    EXECUTE 'CREATE INDEX idx_tmp_lst_scad_sertar ON TMP_LST_SCAD_SERTAR (codobligpif)';
  EXCEPTION WHEN OTHERS THEN
    NULL;
  END;

  BEGIN
    EXECUTE 'CREATE INDEX idx_tmp_lst_scad_partval ON TMP_LST_SCAD_PARTVAL (partener)';
  EXCEPTION WHEN OTHERS THEN
    NULL;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_match_tva</obj_name>
  <obj_hashval>8bd8510225f4788967f888a7b8dc58e2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_match_tva(p_pjtva numeric, p_anluna numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCazTva  numeric;
  vProcTVA numeric;
BEGIN
  --Florin 21.09.2020
  SELECT out_caztva FROM pkg_list_base_utils_MATCH_TVA_COMBI(p_PJTVA, p_AnLuna, vCazTva, vProcTVA) INTO vCazTva;
  RETURN vCazTva;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setdatedoc</obj_name>
  <obj_hashval>f106d08aea88859548f001fb39df6fb3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setdatedoc(acoddoc numeric, acoddoc1 numeric, atipdoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vSDD_TipDoc   numeric := 0;
  vSDD_CodDoc   numeric := 0;
  vSDD_ObsDoc   VARCHAR := '';
  vSDD_DenDoc   VARCHAR := '';
  vSDD_UserDoc  numeric := 0;
  vSDD_PartDoc  numeric := 0;
  vSDD_TablaDoc VARCHAR := '';
  vSDD_ValDoc   numeric := 0;
  vCodDoc       numeric;
  TaskFirma     varchar;
BEGIN
  --Florin 15.09.2023 - fixat 59435
  --Florin 10.08.2023 - sinc. Oracle
  --Florin 19.05.2022 - sinc. Oracle
  --Florin 13.04.2022 - sinc. Oracle
  --Adina 17.02.2021 - add modif.Oracle din 16.02.2021
  --  insert into X(view_name) values('iaca ');
  vCodDoc := aCodDoc;
  IF aTipDoc IN (11, 29, 30, 31, 33)   THEN
     if aCodDoc1 is not null then vCodDoc := aCodDoc1; end if;
  END IF;

  perform set_config('PKG_LIST_BASE_UTILS.vSDD_TablaDoc','',false);
  BEGIN vSDD_CodDoc := current_setting('PKG_LIST_BASE_UTILS.vSDD_CodDoc', True)::numeric;   EXCEPTION WHEN OTHERS THEN vSDD_CodDoc := -1;   END;
  BEGIN vSDD_TipDoc := current_setting('PKG_LIST_BASE_UTILS.vSDD_TipDoc', True)::numeric;   EXCEPTION WHEN OTHERS THEN vSDD_TipDoc := -1;   END;

  IF COALESCE(vCodDoc,0) &lt;&gt; COALESCE(vSDD_CodDoc,0) OR COALESCE(aTipDoc,0) &lt;&gt; COALESCE(vSDD_TipDoc,0)
  THEN
    perform set_config('PKG_LIST_BASE_UTILS.vSDD_TipDoc','0',false);
    perform set_config('PKG_LIST_BASE_UTILS.vSDD_CodDoc','0',false);
    perform set_config('PKG_LIST_BASE_UTILS.vSDD_ObsDoc','',false);
    perform set_config('PKG_LIST_BASE_UTILS.vSDD_DenDoc','',false);
    perform set_config('PKG_LIST_BASE_UTILS.vSDD_UserDoc','0',false);
    perform set_config('PKG_LIST_BASE_UTILS.vSDD_PartDoc','0',false);
    perform set_config('PKG_LIST_BASE_UTILS.vSDD_ValDoc', '0', FALSE);
  END IF;
--------------------------------------------------
  vSDD_TablaDoc := '';
  vSDD_TipDoc   := aTipDoc;
  vSDD_CodDoc   := vCodDoc;
  vSDD_ObsDoc   := '';
  vSDD_DenDoc   := '';
  vSDD_UserDoc  := 0;
  vSDD_PartDoc  := 0;
  vSDD_ValDoc   := 0;
    -- TipDoc tratate
    -- 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,18,19,20,21,22,23,24,25,26,27,28,29,30,31,33,34,35,36,43,44,45,46,47,53,58,59,60,63,64,65,66,71,92,94
  CASE
    WHEN vSDD_TipDoc IN (1,2,3,4,5,6,7,9) THEN
      BEGIN
        vSDD_TablaDoc := 'INTRARI';
        SELECT Obs, (coalesce(PrefixDoc, '')||coalesce(SeriaDoc, '')||NrDoc::varchar||'/'||To_Char(DataDoc,'dd.mm.yyyy')), UserId, Partener, ValDoc
        INTO vSDD_ObsDoc, vSDD_DenDoc, vSDD_UserDoc, vSDD_PartDoc, vSDD_ValDoc
        FROM intrari
        WHERE codintr = vSDD_CodDoc;
      EXCEPTION WHEN OTHERS THEN  NULL;   --insert into X(view_name) values('err vSDD'); --
      END;
    WHEN vSDD_TipDoc IN (8,18,43,44,53,60,65,66,92,94) THEN
      BEGIN
        vSDD_TablaDoc := 'COMANDA';
        SELECT Obs, PrefixDoc||coalesce(coalesce(SeriaDoc, ''), '')||NrDoc::varchar||'/'||To_Char(DataDoc,'dd.mm.yyyy'), UserId, Partener, Valoare
        INTO vSDD_ObsDoc, vSDD_DenDoc, vSDD_UserDoc, vSDD_PartDoc, vSDD_ValDoc
        FROM comanda WHERE codcomanda = vSDD_CodDoc;
      EXCEPTION WHEN OTHERS THEN NULL;
      END;
    WHEN vSDD_TipDoc IN (10,25,27,34) THEN
      BEGIN
        SELECT Obs, 'NCx'||NrDoc::varchar||'/'||To_Char(DataStart,'dd.mm.yyyy')||'-'||To_Char(DataStop,'dd.mm.yyyy'), UserId, CodPart, Valoare
        INTO vSDD_ObsDoc, vSDD_DenDoc, vSDD_UserDoc, vSDD_PartDoc, vSDD_ValDoc
        FROM notecredit WHERE codncredit = vSDD_CodDoc;
        vSDD_TablaDoc := 'NOTECREDIT';
      EXCEPTION WHEN OTHERS THEN NULL;
      END;
    WHEN vSDD_TipDoc = 11 THEN
      BEGIN
        SELECT '', ds.DenDoc||ds.NrDoc::varchar||'/'||To_Char(ds.DataDoc,'dd.mm.yyyy'), ds.UserId
        INTO vSDD_ObsDoc, vSDD_DenDoc, vSDD_UserDoc
        FROM docsuplim ds INNER JOIN docsuplim1 ds1 ON ds1.coddocsuplim = ds.coddocsuplim
        WHERE ds1.coddocsuplim1 = vSDD_CodDoc;
        vSDD_TablaDoc := 'DOCSUPLIM';
      EXCEPTION WHEN OTHERS THEN NULL;
      END;
    WHEN vSDD_TipDoc IN (12, 13) THEN
      BEGIN
        SELECT Obs, PrefixDoc||coalesce(SeriaDoc, '')||NrDoc::varchar||'/'||To_Char(DataDoc,'dd.mm.yyyy'), UserId, ValDoc
        INTO vSDD_ObsDoc, vSDD_DenDoc, vSDD_UserDoc, vSDD_ValDoc
        FROM transf WHERE codtransf = vSDD_CodDoc;
        vSDD_TablaDoc := 'TRANSF';
      EXCEPTION WHEN OTHERS THEN NULL;
      END;
    WHEN vSDD_TipDoc IN (14,15,16,19,20,21,22,23,24,26) THEN
      BEGIN
        SELECT Obs, PrefixDoc||coalesce(SeriaDoc, '')||NrDoc::varchar||'/'||To_Char(DataDoc,'dd.mm.yyyy'), UserId, ValDoc, Partener
        INTO vSDD_ObsDoc, vSDD_DenDoc, vSDD_UserDoc, vSDD_ValDoc, vSDD_PartDoc
        FROM iesiri WHERE codies = vSDD_CodDoc;
        vSDD_TablaDoc := 'IESIRI';
      EXCEPTION WHEN OTHERS THEN NULL;
      END;
    WHEN vSDD_TipDoc = 28 THEN
      BEGIN
        SELECT 'OBS Debit : '||ObsD||' - OBS Credit : '||ObsC, 'PV'||NrDoc::varchar||'/'||To_Char(DataDoc,'dd.mm.yyyy'), UserId, Coalesce(NUllIF(PartD, 0), NUllIF(PartC, 0))
        INTO vSDD_ObsDoc, vSDD_DenDoc, vSDD_UserDoc, vSDD_PartDoc
        FROM compens WHERE codcompens = vSDD_CodDoc;
        vSDD_TablaDoc := 'COMPENS';
      EXCEPTION WHEN OTHERS THEN NULL;
      END;
    WHEN vSDD_TipDoc IN (29,30,31,33) THEN
      BEGIN
        SELECT t1.Obs, t1.Doc||'/'||t1.NrDoc::varchar||'/'||To_Char(t1.DataDoc,'dd.mm.yyyy'), t.UserId, t1.CodPart, t1.valdoc
        INTO vSDD_ObsDoc, vSDD_DenDoc, vSDD_UserDoc, vSDD_PartDoc, vSDD_ValDoc
        FROM trezor t INNER JOIN trezor1 t1 ON t1.codtrezor = t.codtrezor
        WHERE t1.codtrezor1 = vSDD_CodDoc;
        vSDD_TablaDoc := 'TREZOR';
      EXCEPTION WHEN OTHERS THEN NULL;
      END;
    WHEN vSDD_TipDoc = 35 THEN
      BEGIN
        SELECT Obs, 'NC'||NrDoc::varchar||'/'||To_Char(DataDoc,'dd.mm.yyyy'), UserId, Part, Valoare
        INTO vSDD_ObsDoc, vSDD_DenDoc, vSDD_UserDoc, vSDD_PartDoc, vSDD_ValDoc
        FROM nc WHERE codnc = vSDD_CodDoc;
        vSDD_TablaDoc := 'NC';
      EXCEPTION WHEN OTHERS THEN NULL;
      END;
    WHEN vSDD_TipDoc = 36 THEN
      BEGIN
        SELECT '', 'MF/'||SerieInv||'/'||NrInventar::varchar, NULL UserId
        INTO vSDD_ObsDoc, vSDD_DenDoc, vSDD_UserDoc
        FROM mifix WHERE codmifix = vSDD_CodDoc;
        vSDD_TablaDoc := 'MIFIX';
      EXCEPTION WHEN OTHERS THEN NULL;
      END;
    WHEN vSDD_TipDoc IN (45,46,47) THEN
      BEGIN
        SELECT Obs, 'REG.'||NrDoc::varchar||'/'||To_Char(DataDoc,'dd.mm.yyyy'), NULL UserId
        INTO vSDD_ObsDoc, vSDD_DenDoc, vSDD_UserDoc
        FROM reg WHERE codreg = vSDD_CodDoc;
        vSDD_TablaDoc := 'REG';
      EXCEPTION WHEN OTHERS THEN NULL;
      END;
    WHEN vSDD_TipDoc = 58 THEN
      BEGIN
        SELECT Obs, 'NCC'||NrDoc::varchar||'/'||To_Char(DataStart,'dd.mm.yyyy')||'-'||To_Char(DataStop,'dd.mm.yyyy'), UserId
        INTO vSDD_ObsDoc, vSDD_DenDoc, vSDD_UserDoc
        FROM notecredit WHERE codncredit = vSDD_CodDoc;
        vSDD_TablaDoc := 'NOTECREDIT';
      EXCEPTION WHEN OTHERS THEN NULL;
      END;
    WHEN vSDD_TipDoc = 59 THEN
      BEGIN
        SELECT Obs, 'NCF'||NrDoc::varchar||'/'||To_Char(DataStart,'dd.mm.yyyy')||'-'||To_Char(DataStop,'dd.mm.yyyy'), UserId, CodPart
        INTO vSDD_ObsDoc, vSDD_DenDoc, vSDD_UserDoc, vSDD_PartDoc
        FROM notecredit WHERE codncredit = vSDD_CodDoc;
        vSDD_TablaDoc := 'NOTECREDIT';
      EXCEPTION WHEN OTHERS THEN NULL;
      END;
    WHEN vSDD_TipDoc = 62 THEN
      BEGIN
        SELECT Obs, 'LNP'||NrDoc::varchar||'/'||To_Char(DataDoc,'dd.mm.yyyy'), UserId
        INTO vSDD_ObsDoc, vSDD_DenDoc, vSDD_UserDoc
        FROM lansare WHERE codlansare = vSDD_CodDoc;
        vSDD_TablaDoc := 'LANSARE';
      EXCEPTION WHEN OTHERS THEN NULL;
      END;
    WHEN vSDD_TipDoc = 63 THEN
      BEGIN
        SELECT '', PrefixDoc||coalesce(SeriaDoc, '')||NrDoc::varchar||'/'||To_Char(DataI,'dd.mm.yyyy')||'-'||To_Char(DataS,'dd.mm.yyyy'), UserId
        INTO vSDD_ObsDoc, vSDD_DenDoc, vSDD_UserDoc
        FROM raportp WHERE codraportp = vSDD_CodDoc;
        vSDD_TablaDoc := 'RAPORTP';
      EXCEPTION WHEN OTHERS THEN NULL;
      END;
    WHEN vSDD_TipDoc = 64 THEN
      BEGIN
        SELECT '', 'Bon'||NrBon::varchar||'/'||To_Char(DataBon,'dd.mm.yyyy'), UserId, Valoare
        INTO vSDD_ObsDoc, vSDD_DenDoc, vSDD_UserDoc, vSDD_ValDoc
        FROM Emulare WHERE codEmulare = vSDD_CodDoc;
        vSDD_TablaDoc := 'EMULARE';
      EXCEPTION WHEN OTHERS THEN NULL;
      END;
    WHEN vSDD_TipDoc = 67 THEN
      BEGIN
        SELECT '' Obs, PrefixDoc||NrDoc::varchar||'/'||To_Char(DataDoc,'dd.mm.yyyy'), UserId
        INTO vSDD_ObsDoc, vSDD_DenDoc, vSDD_UserDoc
        FROM BCAR WHERE codbcar = vSDD_CodDoc;
        vSDD_TablaDoc := 'BCAR';
      EXCEPTION WHEN OTHERS THEN NULL;
      END;
    WHEN vSDD_TipDoc in (55,105) THEN
      BEGIN
        SELECT '' Obs, case when vSDD_TipDoc = 55 then 'XPL' else 'O' end||NrDoc::varchar||'/'||To_Char(Data,'dd.mm.yyyy'), UserId, Valoare
        INTO vSDD_ObsDoc, vSDD_DenDoc, vSDD_UserDoc, vSDD_ValDoc
        FROM PLATI WHERE CODPLATA = vSDD_CodDoc;
        vSDD_TablaDoc := 'PLATI';
      EXCEPTION WHEN OTHERS THEN NULL;
      END;
    WHEN vSDD_TipDoc = 97 THEN
      BEGIN
        SELECT Motiv, 'RECL'||coalesce(SeriaDoc, '')||NrDoc::varchar||'/'||To_Char(DataDoc,'dd.mm.yyyy'), CodUtilizator, CodPart
        INTO vSDD_ObsDoc, vSDD_DenDoc, vSDD_UserDoc, vSDD_PartDoc
        FROM Reclamatii WHERE codReclamatie = vSDD_CodDoc;
        vSDD_TablaDoc := 'RECLAMATII';
      EXCEPTION WHEN OTHERS THEN NULL;
      END;
    WHEN vSDD_TipDoc = 70 THEN
      BEGIN
        SELECT '' Obs, 'CANTAR'||coalesce(NrAviz,0)::varchar||'/'||to_char(datacreare,'dd.mm.yyyy'), UserId
        INTO vSDD_ObsDoc, vSDD_DenDoc, vSDD_UserDoc
        FROM cantar WHERE codcantar = vSDD_CodDoc;
        vSDD_TablaDoc := 'CANTAR';
      EXCEPTION WHEN OTHERS THEN NULL;
      END;
    WHEN vSDD_TipDoc = 71 THEN
      BEGIN
        SELECT Obs, '' DenDoc, NULL UserId
        INTO vSDD_ObsDoc, vSDD_DenDoc, vSDD_UserDoc
        FROM prodnet WHERE codprodnet = vSDD_CodDoc;
        vSDD_TablaDoc := 'PRODNET';
      EXCEPTION WHEN OTHERS THEN NULL;
      END;
    WHEN vSDD_TipDoc = 82 THEN
      BEGIN
        SELECT Obs, COALESCE(PrefixDoc,'')||COALESCE(SeriaDoc,'')||COALESCE(NrDoc::varchar,'')||'/'||COALESCE(To_Char(DataDoc,'dd.mm.yyyy'),''), UserID, CodPartener
        INTO vSDD_ObsDoc, vSDD_DenDoc, vSDD_UserDoc, vSDD_PartDoc
        FROM OPORTUNITATI WHERE CodOportunitate = vSDD_CodDoc;
        vSDD_TablaDoc := 'OPORTUNITATI';
      EXCEPTION WHEN OTHERS THEN NULL;
      END;
    WHEN vSDD_TipDoc = 50 THEN
      BEGIN
        SELECT Obs, 'OC'||COALESCE(SeriaDoc,'')||COALESCE(NrDoc::varchar,'')||'/'||COALESCE(To_Char(DataOferta,'dd.mm.yyyy'),''), UserID, Partener
        INTO vSDD_ObsDoc, vSDD_DenDoc, vSDD_UserDoc, vSDD_PartDoc
        FROM OFERTA WHERE CodOferta = vSDD_CodDoc;
        vSDD_TablaDoc := 'OFERTA';
      EXCEPTION WHEN OTHERS THEN NULL;
      END;
    WHEN vSDD_TipDoc = 51 THEN
      BEGIN
        SELECT Obs, 'OF'||COALESCE(SeriaDoc, '')||COALESCE(NrDoc, '')||'/'||COALESCE(To_Char(DataOferta,'dd.mm.yyyy'), ''), UserID, Partener
        INTO vSDD_ObsDoc, vSDD_DenDoc, vSDD_UserDoc, vSDD_PartDoc
        FROM OFERTA WHERE CodOferta = vSDD_CodDoc;
        vSDD_TablaDoc := 'OFERTA';
      EXCEPTION WHEN OTHERS THEN NULL;
    END;
    WHEN vSDD_TipDoc = 27 THEN
      BEGIN
        SELECT Obs, 'CcC'||COALESCE(SeriaDoc,'')||COALESCE(NrDoc::varchar,'')||'/'||COALESCE(To_Char(DataDoc,'dd.mm.yyyy'),''), UserID, Partener
        INTO vSDD_ObsDoc, vSDD_DenDoc, vSDD_UserDoc, vSDD_PartDoc
        FROM CONTRACT WHERE CodContract = vSDD_CodDoc;
        vSDD_TablaDoc := 'CONTRACT';
      EXCEPTION WHEN OTHERS THEN NULL;
      END;
    WHEN vSDD_TipDoc = 54 THEN
      BEGIN
        TaskFirma := Coalesce(fnc_GetValConstantaLucru('TaskFirma'), '0');

        IF TaskFirma = '1' THEN
          SELECT SubString(PROBLEMA,1,200) Obs, MESAJCATRE||'-'||coalesce(SeriaDoc, '')||NrDoc::varchar||'/'||To_Char(DATATASK,'dd.mm.yyyy') DenDoc, NULL UserId
          INTO vSDD_ObsDoc, vSDD_DenDoc, vSDD_UserDoc
          FROM WinMAdmin.SetTask WHERE CODTASK = vSDD_CodDoc;
          vSDD_TablaDoc := 'WinMAdmin.SetTask';
        ELSE
          SELECT SubString(PROBLEMA,1,200) Obs, MESAJCATRE||'-'||coalesce(SeriaDoc, '')||NrDoc::varchar||'/'||To_Char(DATATASK,'dd.mm.yyyy') DenDoc, NULL UserId
          INTO vSDD_ObsDoc, vSDD_DenDoc, vSDD_UserDoc
          FROM SetTask WHERE CODTASK = vSDD_CodDoc;
          vSDD_TablaDoc := 'SetTask';
        END IF;
      EXCEPTION WHEN OTHERS THEN NULL;
      END;
    WHEN vSDD_TipDoc = 69 THEN
      BEGIN
        SELECT Obs, COALESCE(NrDoc::varchar,'')||'/'||COALESCE(to_char(datadoc,'dd.mm.yyyy'),''), UserId
        INTO vSDD_ObsDoc, vSDD_DenDoc, vSDD_UserDoc
        FROM nsertar WHERE codsertar = vSDD_CodDoc;
        vSDD_TablaDoc := 'NSERTAR';
      EXCEPTION WHEN OTHERS THEN NULL;
      END;
    WHEN vSDD_TipDoc = 78 THEN
      BEGIN
        SELECT '', coalesce(NrDoc::varchar, '')||'/'||oalesce(to_char(datap,'dd.mm.yyyy'), ''), UserId
        INTO vSDD_ObsDoc, vSDD_DenDoc, vSDD_UserDoc
        FROM pachete WHERE codpachete = vSDD_CodDoc;
        vSDD_TablaDoc := 'PACHETE';
      EXCEPTION WHEN OTHERS THEN NULL;
    END;
    ELSE NULL;
  END CASE;
  perform set_config('PKG_LIST_BASE_UTILS.vSDD_TipDoc' ,vSDD_TipDoc::varchar ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vSDD_CodDoc' ,vSDD_CodDoc::varchar ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vSDD_ObsDoc' ,vSDD_ObsDoc::varchar ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vSDD_DenDoc' ,vSDD_DenDoc::varchar ,false);
  perform set_config('PKG_LIST_BASE_UTILS.vSDD_UserDoc',vSDD_UserDoc::varchar,false);
  perform set_config('PKG_LIST_BASE_UTILS.vSDD_PartDoc',vSDD_PartDoc::varchar,false);
  perform set_config('PKG_LIST_BASE_UTILS.vSDD_ValDoc',vSDD_ValDoc::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzagent_processlist</obj_name>
  <obj_hashval>25e2aab8846b3b3e3f1fd2db364fa737</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzagent_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sSelect     varchar;
  sUpdate     varchar;
  sWherePer   varchar;
  sWhereAux   varchar;
  gSuplCols   varchar := 'NPERS NPERS, NPART NPART, NAGENDA SSOC, NLOCALIT LSOC, NJUDET JSOC, NTARI TSOC, NPERS AGI, NCLASEP NCP';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 24.08.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_VANZAGENT.gSuplCols', gSuplCols, FALSE);

  IF (current_setting('PKG_LIST_BASE_VANZAGENT.vLunaIni', true)::numeric = current_setting('PKG_LIST_BASE_VANZAGENT.vLunaFin', true)::numeric)
    AND (current_setting('PKG_LIST_BASE_VANZAGENT.vAnIni', true)::numeric = current_setting('PKG_LIST_BASE_VANZAGENT.vAnFin', true)::numeric)
  THEN
    sWherePer := '= ' || coalesce((current_setting('PKG_LIST_BASE_VANZAGENT.vAnFin', true)::numeric * 12 + current_setting('PKG_LIST_BASE_VANZAGENT.vLunaFin', true)::numeric) , 0);
  ELSE
    sWherePer := 'BETWEEN ' || coalesce((current_setting('PKG_LIST_BASE_VANZAGENT.vAnIni', true)::numeric * 12 + current_setting('PKG_LIST_BASE_VANZAGENT.vLunaIni', true)::numeric) ,0)
      || ' AND ' || coalesce((current_setting('PKG_LIST_BASE_VANZAGENT.vAnFin', true)::numeric * 12 + current_setting('PKG_LIST_BASE_VANZAGENT.vLunaFin', true)::numeric) , 0);
  END IF;

  IF NOT (current_setting('PKG_LIST_BASE_VANZAGENT.vAllClient', true)::boolean) THEN
    sWhereAux := coalesce(sWhereAux,'') || '
        AND I.PARTENER::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODPART'')';
  END IF;

  IF NOT (current_setting('PKG_LIST_BASE_VANZAGENT.vAllAgent', true)::boolean) THEN
    sWhereAux := coalesce(sWhereAux,'') || '
        AND COALESCE(I.AGENT,0)::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODPERS'')';
  END IF;
--INSERT INTO x (view_name, test) VALUES ('sWhereAux', sWhereAux);
--INSERT INTO x (view_name, test) VALUES ('vAllClient', current_setting('PKG_LIST_BASE_VANZAGENT.vAllClient', true));
--INSERT INTO x (view_name, test) VALUES ('vAllAgent', current_setting('PKG_LIST_BASE_VANZAGENT.vAllAgent', true));
  sInsert := 'INSERT INTO ' || tmpName || '(Agent, AgentI, Client, DenClasaC, SoldI, SoldF ' || coalesce(PKG_LIST_BASE_VANZAGENT_CAMPURI('INSERT'),'') || gUserFields || ')';
  sSelect := '
    WITH TMP AS (
       SELECT
        0 cod, 0 codaux,
         COALESCE(I.AGENT,0) AGENT, I.PARTENER, 0 AL,
         (OL.REST + CASE WHEN O.SEMNIFICATIE IN (210, 1303) THEN 0 ELSE OL.RESTTVA END) *
         (Case  When G.CURS is NULL then 1 When G.CURS=0 then 1 else G.CURS end) SI,
          0 VV, 0 VI, 0 XV, 0 NV
      FROM OBLIGPIFLUNA OL
          INNER JOIN OBLIGPIF O  ON O.CODOBLIGPIF  = OL.CODOBLIGPIF
          INNER JOIN OBLIGPIF OS ON OS.CODOBLIGPIF = (Case  When O.SEMNIFICATIE=1303 then O.CODOBLIGASOCIAT else O.CODOBLIGPIF end)
          INNER JOIN GENERAL  G  ON G.CODGENERAL   = OS.CODGENERAL
          INNER JOIN IESIRI   I  ON I.CODIES       = G.CODDOC AND I.TIPDOC = G.TIPDOC
        WHERE (OL.AN*12+OL.LUNA) = ' || coalesce((current_setting('PKG_LIST_BASE_VANZAGENT.vAnIni', true)::numeric * 12 + current_setting('PKG_LIST_BASE_VANZAGENT.vLunaIni', true)::numeric - 1) ,0) || '
          AND O.SEMNIFICATIE &lt;&gt; 210
          AND I.TIPDOC IN (19,21,22,26)
          AND I.ANULAT = 0 AND I.OPERAT = 1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || coalesce(sWhereAux,'') || '
        UNION ALL
        SELECT
          i.codies cod, 0 codaux,
          COALESCE(I.AGENT,0) AGENT, I.PARTENER, (I.AN *12 +I.LUNA) AL,
          0 SI, I.VALDOC * (Case  When I.CURS is NULL then 1 When I.CURS=0 then 1 else I.CURS end) VV, CASE WHEN I.TIPFACTURA = 7 THEN I.VALDOC * (Case  When I.CURS is NULL then 1 When I.CURS=0 then 1 else I.CURS end) ELSE 0 END VI,
          ( SELECT SUM(I1.CANT * I1.PU - (Case When I.TIPDOC=21 then I1.TVA else 0 end))
            FROM IESIRI1 I1
            WHERE I1.CODIES = I.CODIES AND I1.TIPLINIE IN (''='',''V'',''S'')
          ) * (Case When I.CURS is NULL then 1 When I.CURS=0 then 1 else I.CURS end) XV,
          (I.VALDOC - I.TVADOC) * (Case When I.CURS is NULL then 1 When I.CURS=0 then 1 else I.CURS end) NV
        FROM IESIRI I
        WHERE I.TIPDOC IN (19,21,22,26)
          AND I.ANULAT = 0 AND I.OPERAT = 1 AND COALESCE(I.INFOCM,0) = 0 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || coalesce(sWhereAux,'') || '
          AND ( I.An * 12 + I.LUNA ) ' || coalesce(sWherePer,'') || '
        UNION ALL
        SELECT
          i.codies cod, 0 codaux,
          COALESCE(I1.CODAGENTEMULARE,0) AGENT, I.PARTENER, (I.AN *12 +I.LUNA) AL,
          0 SI, SUM(I1.CANT * I1.PU) * (Case  When I.CURS is NULL then 1 When I.CURS=0 then 1 else I.CURS end) VV, SUM(I1.CANT * I1.PU) * (Case  When I.CURS is NULL then 1 When I.CURS=0 then 1 else I.CURS end) VI,
          SUM(I1.CANT * I1.PU - I1.TVA) * (Case When I.CURS is NULL then 1 When I.CURS=0 then 1 else I.CURS end) XV,
          SUM(I1.CANT * I1.PU - I1.TVA) * (Case When I.CURS is NULL then 1 When I.CURS=0 then 1 else I.CURS end) NV
        FROM IESIRI I INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
        WHERE I.TIPDOC = 16
          AND I.ANULAT = 0 AND I.OPERAT = 1 AND COALESCE(I.INFOCM,0) = 0 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || coalesce(sWhereAux,'') || '
          AND ( I.An * 12 + I.LUNA ) ' || coalesce(sWherePer,'') || '
        GROUP BY i.codies, COALESCE(I1.CODAGENTEMULARE,0), I.PARTENER, I.AN, I.LUNA, I.CURS
        UNION ALL
        SELECT -- stingeri trezorerie
          i.codies cod, t1.codtrezor1 codaux,
          COALESCE(I.AGENT,0) AGENT, I.PARTENER, t1.an * 12 + t1.luna AL,
          0 SI, 0 VV,
          (S.VALOARE + COALESCE(GS.TVA,0)) * Sign(o.valoare) * (Case When GS.CURS is NULL then 1 When GS.CURS=0 then 1 else GS.CURS end) VI,
          0 XV, 0 NV
        FROM TREZOR T
          INNER JOIN TREZOR1  T1 ON T1.CODTREZOR      = T.CODTREZOR
          INNER JOIN GENERAL  GS ON GS.TIPDOC         = T.TIPDOC AND GS.CODDOC = T1.CODTREZOR1
          INNER JOIN OBLIGPIF OS ON OS.CODGENERAL     = GS.CODGENERAL
          INNER JOIN STINGERE S  ON S.CODSTINGATORPIF = OS.CODOBLIGPIF
          INNER JOIN OBLIGPIF OL ON OL.CODOBLIGPIF    = S.CODSTINSPIF
          INNER JOIN OBLIGPIF O  ON O.CODOBLIGPIF     = (Case When OL.SEMNIFICATIE=1303 then OL.CODOBLIGASOCIAT else OL.CODOBLIGPIF end)
          INNER JOIN GENERAL  G  ON G.CODGENERAL      = O.CODGENERAL
          INNER JOIN IESIRI   I  ON I.CODIES          = G.CODDOC AND I.TIPDOC = G.TIPDOC
        WHERE I.TIPDOC IN (19,21,22,26)
          AND O.SEMNIFICATIE NOT IN (800, 801)
          AND T.TIPDOC IN (29,30,31,33)
          AND T.OPERAT = 1
          AND I.ANULAT = 0 AND I.OPERAT = 1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || coalesce(sWhereAux,'') || '
          AND (t1.an * 12 + t1.luna) ' || coalesce(sWherePer,'') || '
        UNION ALL
        SELECT -- stingeri compensari
          i.codies cod, c.codcompens codaux,
          COALESCE(I.AGENT,0) AGENT, I.PARTENER, c.an * 12 + c.luna AL,
          0 SI, 0 VV,
          (S.VALOARE + (case when C.TipCompens = 2 then 0 else COALESCE(GS.TVA,0) end)) * Sign(o.valoare) * (Case  When G.CURS is NULL then 1 When G.CURS=0 then 1 else G.CURS end) VI,
          0 XV, 0 NV
        FROM COMPENS C
          INNER JOIN GENERAL  GS ON GS.CODDOC         = C.CODCOMPENS AND GS.TIPDOC = 28
          INNER JOIN OBLIGPIF OS ON OS.CODGENERAL     = GS.CODGENERAL
          INNER JOIN STINGERE S  ON S.CODSTINGATORPIF = OS.CODOBLIGPIF
          INNER JOIN OBLIGPIF OX ON OX.CODOBLIGPIF    = S.CODSTINSPIF
          INNER JOIN OBLIGPIF O  ON O.CODOBLIGPIF     = (Case  When OX.CODOBLIGASOCIAT is NULL then OX.CODOBLIGPIF When OX.CODOBLIGASOCIAT=0 then OX.CODOBLIGPIF else OX.CODOBLIGASOCIAT end)
          INNER JOIN GENERAL  G  ON G.CODGENERAL      = O.CODGENERAL AND G.TIPDOC IN (19,21,22,26)
          INNER JOIN IESIRI   I  ON I.CODIES          = G.CODDOC AND I.TIPDOC = G.TIPDOC
        WHERE COALESCE(C.TipCompens,0) IN (0,2)
          AND I.ANULAT = 0 AND I.OPERAT = 1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || coalesce(sWhereAux,'') || '
          AND (c.an * 12 + c.luna) ' || coalesce(sWherePer,'') || '
        UNION ALL
        SELECT -- stingeri retur
          i.codies cod, i2.codies codaux,
          COALESCE(I.AGENT,0) AGENT, I.PARTENER, i2.an * 12 + i2.luna AL,
          0 SI, 0 VV,
          S.VALOARE * Sign(o.valoare) * (Case When G.CURS is NULL then 1 When G.CURS=0 then 1 else G.CURS end) VI,
          0 XV, 0 NV
        FROM IESIRI I
          INNER JOIN GENERAL  G  ON I.CODIES       = G.CODDOC AND I.TIPDOC = G.TIPDOC
          INNER JOIN OBLIGPIF O  ON O.CODGENERAL   = G.CODGENERAL
          INNER JOIN STINGERE S  ON S.CODSTINSPIF  = O.CODOBLIGPIF
          INNER JOIN OBLIGPIF OS ON OS.CODOBLIGPIF = S.CODSTINGATORPIF
          INNER JOIN GENERAL  GS ON GS.CODGENERAL  = OS.CODGENERAL
          INNER JOIN IESIRI   I2 ON I2.CODIES      = GS.CODDOC AND I2.TIPDOC = GS.TIPDOC
        WHERE I.TIPDOC IN (19,21,22,26)
          AND GS.SEMNIFICATIE IN (/*211,*/ 400)
          AND I.ANULAT = 0 AND I.OPERAT = 1
          AND I2.ANULAT = 0 AND I2.OPERAT = 1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || coalesce(sWhereAux,'') || '
          AND (i2.an * 12 + i2.luna) ' || coalesce(sWherePer,'') || '
          AND Coalesce(i2.infocm,0) &lt;&gt; 1
      )
      SELECT
        (Case When T.AGENT=0 then '' '' else NPERS.NUME||'' ''||NPERS.PRENUME end) AGENT, AGI.NUME||'' ''||AGI.PRENUME AGENTI, NPART.DEN_PART, NCP.DEN_CLASEP, SUM(T.SI), SUM(T.SI + T.VV - T.VI)'
          || coalesce(PKG_LIST_BASE_VANZAGENT_CAMPURI('SELECT'),'') || gUserAlias || '
      FROM TMP T
        INNER JOIN NPERS         ON NPERS.CODPERS   = T.AGENT
        INNER JOIN NPART         ON NPART.CODPART   = T.PARTENER
        LEFT  JOIN NAGENDA  SSOC ON SSOC.CODPART    = NPART.CODPART AND SSOC.SEDIUSOCIAL BETWEEN 4 AND 7 AND COALESCE(SSOC.INACTIV, 0) = 0
        LEFT  JOIN NLOCALIT LSOC ON LSOC.CODLOCALIT = COALESCE(SSOC.CODLOCALIT, 0)
        LEFT  JOIN NJUDET   JSOC ON JSOC.CODJUDET   = COALESCE(LSOC.CODJUDET, 0)
        LEFT  JOIN NTARI    TSOC ON TSOC.CODTARA    = COALESCE(LSOC.CODTARA, 0)
        LEFT  JOIN NPERS    AGI  ON AGI.CODPERS     = COALESCE(SSOC.CODAGENT,0)
        LEFT  JOIN NCLASEP  NCP  ON NCP.CODCLASEP   = NPART.CODCLASA' || gSuplJoins || '
      GROUP BY T.AGENT, NPERS.NUME, NPERS.PRENUME, AGI.NUME, AGI.PRENUME, NPART.DEN_PART, NCP.DEN_CLASEP ' || gUserAlias;
  --sUpdate := '
  --    MERGE INTO ' || tmpName || ' A
  --      USING (
  --        SELECT ROWID,
  --          Sum(T_VV) OVER (PARTITION BY Agent, Client) xS_VV,
  --          Sum(T_VI) OVER (PARTITION BY Agent, Client) xS_VI,
  --         Sum(T_XV) OVER (PARTITION BY Agent, Client) xS_XV,
  --          Sum(T_NV) OVER (PARTITION BY Agent, Client) xS_NV
  --        FROM ' || tmpName || '
  --      ) B ON (A.ROWID = B.ROWID)
  --    WHEN MATCHED THEN UPDATE SET A.S_VV = B.xS_VV, A.S_VI = B.xS_VI, A.S_XV = B.xS_XV, A.S_NV = B.xS_NV';
    sUpdate :='
      UPDATE '|| tmpName ||' A
      SET (S_VV, S_VI, S_XV, S_NV) = (SELECT Sum(B.T_VV), Sum(B.T_VI), Sum(B.T_XV), Sum(B.T_NV) FROM '|| tmpName ||' B WHERE B.Agent = A.Agent AND B.Client = A.Client)';

    PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
    PERFORM LIST_EXECUTE_IMMEDIATE(supdate, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzagentart_processlist</obj_name>
  <obj_hashval>f131205c1a1b51bd9f6d823abda7ea7d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzagentart_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sSelect     varchar;
  sUpdate     varchar;
  sWherePer   varchar;
  sWhereAux   varchar;
  gSuplCols   varchar := 'NPERS NPERS, NPART NPART, NAGENDA SSOC, NLOCALIT LSOC, NJUDET JSOC, NTARI TSOC, NARTOBJ NOBJ, NART NART, NCLASEP NCP, NCLASEA NCA';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --28.08.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = NOBJ.CODOBIECT'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCLASEAS'  , 'NCAS', 'NCAS.CODCLASEAS = NART.CLASASTATIST',NULL);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_VANZAGENTART.gSuplCols', gSuplCols, FALSE);

  IF (current_setting('PKG_LIST_BASE_VANZAGENTART.vLunaIni', true)::numeric = current_setting('PKG_LIST_BASE_VANZAGENTART.vLunaFin', true)::numeric)
     AND
     (current_setting('PKG_LIST_BASE_VANZAGENTART.vAnIni', true)::numeric = current_setting('PKG_LIST_BASE_VANZAGENTART.vAnFin', true)::numeric)
  THEN
    sWherePer := '= ' || coalesce((current_setting('PKG_LIST_BASE_VANZAGENTART.vAnFin', true)::numeric * 12 + current_setting('PKG_LIST_BASE_VANZAGENTART.vLunaFin', true)::numeric) ,0);
  ELSE
    sWherePer := 'BETWEEN ' || coalesce((current_setting('PKG_LIST_BASE_VANZAGENTART.vAnIni', true)::numeric * 12 + current_setting('PKG_LIST_BASE_VANZAGENTART.vLunaIni', true)::numeric) ,0) || ' AND ' || coalesce((  current_setting('PKG_LIST_BASE_VANZAGENTART.vAnFin', true)::numeric * 12 + current_setting('PKG_LIST_BASE_VANZAGENTART.vLunaFin', true)::numeric) ,0);
  END IF;

  IF NOT current_setting('PKG_LIST_BASE_VANZAGENTART.vAllClient', true)::boolean THEN
    sWhereAux := coalesce(sWhereAux,'') || '
            AND I.PARTENER::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODPART'')';
  END IF;

  IF NOT current_setting('PKG_LIST_BASE_VANZAGENTART.vAllAgent', true)::boolean THEN
    sWhereAux := coalesce(sWhereAux,'') || '
            AND COALESCE(I.AGENT,0)::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODPERS'')';
  END IF;

  sInsert := 'INSERT INTO ' || tmpName || '(Agent, Client, DenClasaC, Art, DenClasaA, SoldI, SoldF ' || coalesce(PKG_LIST_BASE_VANZAGENTART_CAMPURI('INSERT'), '') || gUserFields || ')';
  sSelect := '
      WITH
      DOC AS (
        SELECT codies, al, sum(si) si, sum(VV) vv, sum(VI) vi, sum(XV) xv, sum(NV) nv
        FROM (
          SELECT
            i.codies, 0 AL,
            (OL.REST + CASE WHEN O.SEMNIFICATIE IN (210, 1303) THEN 0 ELSE OL.RESTTVA END) * (Case When G.CURS is NULL then 1 When G.CURS=0 then 1 else G.CURS end) SI,
            0 VV, 0 VI, 0 XV, 0 NV
          FROM OBLIGPIFLUNA OL
            INNER JOIN OBLIGPIF O  ON O.CODOBLIGPIF  = OL.CODOBLIGPIF
            INNER JOIN OBLIGPIF OS ON OS.CODOBLIGPIF = (Case When O.SEMNIFICATIE=1303 then O.CODOBLIGASOCIAT else O.CODOBLIGPIF end)
            INNER JOIN GENERAL  G  ON G.CODGENERAL   = OS.CODGENERAL
            INNER JOIN IESIRI   I  ON I.CODIES       = G.CODDOC AND I.TIPDOC = G.TIPDOC
          WHERE (OL.AN*12+OL.LUNA) = ' || coalesce((current_setting('PKG_LIST_BASE_VANZAGENTART.vAnIni', true)::numeric * 12 + current_setting('PKG_LIST_BASE_VANZAGENTART.vLunaIni', true)::numeric - 1) , 0) || '
            AND O.SEMNIFICATIE &lt;&gt; 210
            AND I.TIPDOC IN (19,21,22,26)
            AND I.ANULAT = 0 AND I.OPERAT = 1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || coalesce(sWhereAux,'') || '
          UNION ALL
          SELECT
            i.codies, (i.an *12 +i.luna) AL,
            0 SI, I.VALDOC * (Case When I.CURS is NULL then 1 When I.CURS=0 then 1 else I.CURS end) VV, CASE WHEN I.TIPFACTURA = 7 THEN I.VALDOC * (Case When I.CURS is NULL then 1 When I.CURS=0 then 1 else I.CURS end) ELSE 0 END VI,
            ( SELECT SUM(I1.CANT * I1.PU - (Case  When I.TIPDOC=21 then I1.TVA else 0 end))
              FROM IESIRI1 I1
              WHERE I1.CODIES = I.CODIES AND I1.TIPLINIE IN (''='',''V'',''S'')
            ) * (Case When I.CURS is NULL then 1 When I.CURS=0 then 1 else I.CURS end) XV,
            (I.VALDOC - I.TVADOC) * (Case  When I.CURS is NULL then 1 When I.CURS=0 then 1 else I.CURS end) NV
          FROM IESIRI I
          WHERE I.TIPDOC IN (16,19,21,22,26)
            AND I.ANULAT = 0 AND I.OPERAT = 1 AND COALESCE(I.INFOCM,0) = 0 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || coalesce(sWhereAux,'') || '
            AND ( I.An * 12 + I.LUNA ) ' || coalesce(sWherePer,'') || '
          UNION ALL
          SELECT -- stingeri trezorerie
            i.codies, t1.an * 12 + t1.luna AL,
            0 SI, 0 VV,
            (S.VALOARE + COALESCE(GS.TVA,0)) * Sign(o.valoare) * (Case When GS.CURS is NULL then 1 When GS.CURS=0 then 1 else G.CURS end) VI,
            0 XV, 0 NV
          FROM TREZOR T
            INNER JOIN TREZOR1  T1 ON T1.CODTREZOR      = T.CODTREZOR
            INNER JOIN GENERAL  GS ON GS.TIPDOC         = T.TIPDOC AND GS.CODDOC = T1.CODTREZOR1
            INNER JOIN OBLIGPIF OS ON OS.CODGENERAL     = GS.CODGENERAL
            INNER JOIN STINGERE S  ON S.CODSTINGATORPIF = OS.CODOBLIGPIF
            INNER JOIN OBLIGPIF OL ON OL.CODOBLIGPIF    = S.CODSTINSPIF
            INNER JOIN OBLIGPIF O  ON O.CODOBLIGPIF     = (Case When OL.SEMNIFICATIE=1303 then OL.CODOBLIGASOCIAT else OL.CODOBLIGPIF end)
            INNER JOIN GENERAL  G  ON G.CODGENERAL      = O.CODGENERAL
            INNER JOIN IESIRI   I  ON I.CODIES          = G.CODDOC AND I.TIPDOC = G.TIPDOC
          WHERE I.TIPDOC IN (19,21,22,26)
            AND O.SEMNIFICATIE NOT IN (800, 801)
            AND T.TIPDOC IN (29,30,31,33)
            AND T.OPERAT = 1
            AND I.ANULAT = 0 AND I.OPERAT = 1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || coalesce(sWhereAux,'') || '
            AND (t1.an * 12 + t1.luna) ' || coalesce(sWherePer,'') || '
          UNION ALL
          SELECT -- stingeri compensari
            i.codies, c.an * 12 + c.luna AL,
            0 SI, 0 VV,
            (S.VALOARE + (case when C.TipCompens = 2 then 0 else COALESCE(GS.TVA,0) end)) * Sign(o.valoare) * (Case When G.CURS is NULL then 1 When G.CURS=0 then 1 else G.CURS end) VI,
            0 XV, 0 NV
          FROM COMPENS C
            INNER JOIN GENERAL  GS ON GS.CODDOC         = C.CODCOMPENS AND GS.TIPDOC = 28
            INNER JOIN OBLIGPIF OS ON OS.CODGENERAL     = GS.CODGENERAL
            INNER JOIN STINGERE S  ON S.CODSTINGATORPIF = OS.CODOBLIGPIF
            INNER JOIN OBLIGPIF OX ON OX.CODOBLIGPIF    = S.CODSTINSPIF
            INNER JOIN OBLIGPIF O  ON O.CODOBLIGPIF     = (Case  When OX.CODOBLIGASOCIAT is NULL then OX.CODOBLIGPIF When OX.CODOBLIGASOCIAT=0 then OX.CODOBLIGPIF else OX.CODOBLIGASOCIAT end)
            INNER JOIN GENERAL  G  ON G.CODGENERAL      = O.CODGENERAL AND G.TIPDOC IN (19,21,22,26)
            INNER JOIN IESIRI   I  ON I.CODIES          = G.CODDOC AND I.TIPDOC = G.TIPDOC
          WHERE COALESCE(C.TipCompens,0) IN (0,2)
            AND I.ANULAT = 0 AND I.OPERAT = 1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || coalesce(sWhereAux,'') || '
            AND (c.an * 12 + c.luna) ' || coalesce(sWherePer,'') || '
          UNION ALL
          SELECT -- stingeri retur
            i.codies, i2.an * 12 + i2.luna AL,
            0 SI, 0 VV,
            S.VALOARE * Sign(o.valoare) * (Case When G.CURS is NULL then 1 When G.CURS=0 then 1 else G.CURS end) VI,
            0 XV, 0 NV
          FROM IESIRI I
            INNER JOIN GENERAL  G  ON I.CODIES       = G.CODDOC AND I.TIPDOC = G.TIPDOC
            INNER JOIN OBLIGPIF O  ON O.CODGENERAL   = G.CODGENERAL
            INNER JOIN STINGERE S  ON S.CODSTINSPIF  = O.CODOBLIGPIF
            INNER JOIN OBLIGPIF OS ON OS.CODOBLIGPIF = S.CODSTINGATORPIF
            INNER JOIN GENERAL  GS ON GS.CODGENERAL  = OS.CODGENERAL
            INNER JOIN IESIRI   I2 ON I2.CODIES      = GS.CODDOC AND I2.TIPDOC = GS.TIPDOC
          WHERE I.TIPDOC IN (16,19,21,22,26)
            AND GS.SEMNIFICATIE IN (/*211, */400)
            AND I.ANULAT = 0 AND I.OPERAT = 1
            AND I2.ANULAT = 0 AND I2.OPERAT = 1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || coalesce(sWhereAux,'') || '
            AND (i2.an * 12 + i2.luna) ' || coalesce(sWherePer,'') || '
            AND Coalesce(i2.infocm,0) &lt;&gt; 1
        ) a_pg
        GROUP BY CODIES, AL),
      TMP AS (
        SELECT
          CASE WHEN i.tipdoc = 16 THEN COALESCE(I1.CODAGENTEMULARE,0) ELSE COALESCE(I.AGENT,0) END AGENT, I.PARTENER, COALESCE(I1.CODOBIECT,0) CODOBIECT, DOC.AL,
          CASE
            WHEN I1.CODIES1 IS NULL THEN DOC.SI
            WHEN I.VALDOC = 0 OR i1.addim = -100 OR COALESCE(l1.cant, i1.cant) = 0 THEN 0
            ELSE DOC.SI / I.VALDOC * (SELECT PKG_LIST_BASE_IESIRI_CALCPIES.wme_result FROM PKG_LIST_BASE_IESIRI_CALCPIES(NULL, i.codies, i.tipdoc, i1.cant, i1.pu, i1.tva, i1.addim, i1.coefdiscmaj, i1.valdiscpret, 1)) * COALESCE(l1.cant*i1.cant/COALESCE(ae1.cant,i1.cant), i1.cant)
          END SI,
          CASE
            WHEN I1.CODIES1 IS NULL THEN DOC.VV
            WHEN I1.CANT = 0 THEN 0
            WHEN I.VALDOC = 0 OR i1.addim = -100 OR COALESCE(l1.cant, i1.cant) = 0 THEN 0
            ELSE DOC.VV / I.VALDOC * (SELECT PKG_LIST_BASE_IESIRI_CALCPIES.wme_result FROM PKG_LIST_BASE_IESIRI_CALCPIES(NULL, i.codies, i.tipdoc, i1.cant, i1.pu, i1.tva, i1.addim, i1.coefdiscmaj, i1.valdiscpret, 1)) * COALESCE(l1.cant*i1.cant/COALESCE(ae1.cant,i1.cant), i1.cant)
          END VV,
          CASE
            WHEN I1.CODIES1 IS NULL THEN DOC.VI
            WHEN I.VALDOC = 0 OR i1.addim = -100 OR COALESCE(l1.cant, i1.cant) = 0 THEN 0
            ELSE DOC.VI / I.VALDOC * (SELECT PKG_LIST_BASE_IESIRI_CALCPIES.wme_result FROM PKG_LIST_BASE_IESIRI_CALCPIES(NULL, i.codies, i.tipdoc, i1.cant, i1.pu, i1.tva, i1.addim, i1.coefdiscmaj, i1.valdiscpret, 1)) * COALESCE(l1.cant*i1.cant/COALESCE(ae1.cant,i1.cant), i1.cant)
          END VI,
          CASE
            WHEN I1.CODIES1 IS NULL THEN DOC.XV
            WHEN I1.CANT = 0 THEN 0
            WHEN I.VALDOC - I.TVADOC = 0 OR i1.addim = -100 OR COALESCE(l1.cant, i1.cant) = 0 THEN 0
            ELSE DOC.XV / (I.VALDOC - I.TVADOC) * (SELECT PKG_LIST_BASE_IESIRI_CALCPIES.wme_result FROM PKG_LIST_BASE_IESIRI_CALCPIES(NULL, i.codies, i.tipdoc, i1.cant, i1.pu, i1.tva, i1.addim, i1.coefdiscmaj, i1.valdiscpret, 0)) * COALESCE(l1.cant*i1.cant/COALESCE(ae1.cant,i1.cant), i1.cant)
          END XV,
          CASE
            WHEN I1.CODIES1 IS NULL THEN DOC.NV
            WHEN I.VALDOC - I.TVADOC = 0 OR i1.addim = -100 OR COALESCE(l1.cant, i1.cant) = 0 THEN 0
            ELSE DOC.NV / (I.VALDOC - I.TVADOC) * (SELECT PKG_LIST_BASE_IESIRI_CALCPIES.wme_result FROM PKG_LIST_BASE_IESIRI_CALCPIES(NULL, i.codies, i.tipdoc, i1.cant, i1.pu, i1.tva, i1.addim, i1.coefdiscmaj, i1.valdiscpret, 0)) * COALESCE(l1.cant*i1.cant/COALESCE(ae1.cant,i1.cant), i1.cant)
          END NV,
          CASE
            WHEN I1.CODIES1 IS NULL THEN 0
            WHEN I.VALDOC = 0 OR i1.addim = -100 OR COALESCE(l1.cant, i1.cant) = 0 THEN 0
            ELSE DOC.VV / I.VALDOC * ((SELECT PKG_LIST_BASE_IESIRI_CALCPIES.wme_result FROM PKG_LIST_BASE_IESIRI_CALCPIES(NULL, i.codies, i.tipdoc, i1.cant, i1.pu, i1.tva, i1.addim, i1.coefdiscmaj, i1.valdiscpret, 0)) - COALESCE(lv.pretachiz, ns.pret-ns.adaos,0)/ (Case When I.CURS is NULL then 1 When I.CURS=0 then 1 else I.CURS end)) * COALESCE(l1.cant*i1.cant/COALESCE(ae1.cant,i1.cant), i1.cant)
          END VA
        FROM doc
          INNER JOIN iesiri i    ON i.codies      = doc.codies
          LEFT JOIN iesiri1 i1   ON i1.codies     = i.codies
          LEFT JOIN ieslink ilae ON ilae.codies1  = i1.codies1
          LEFT JOIN iesiri1 ae1  ON ae1.codies1   = ilae.codlinieaviz
          LEFT JOIN iesiri  ae   ON ae.codies     = ae1.codies
          LEFT JOIN livr    l    ON l.codies      = COALESCE(ae1.codies,i.codies) AND l.tiplivr = COALESCE(ae.tipdoc,i.tipdoc)
          LEFT JOIN livr1   l1   ON l1.codlivr    = l.codlivr AND l1.codies1 = COALESCE(ae1.codies1,i1.codies1)
          LEFT JOIN nirstoc ns   ON ns.codnirstoc = l1.codnirstoc
          LEFT JOIN livrval lv   ON lv.codlivr1   = l1.codlivr1
        WHERE (i1.tiplinie IN (''S'',''V'',''='') OR i1.codies IS NULL)
      )
      SELECT
        (Case When T.AGENT=0 then NULL else NPERS.NUME||'' ''||NPERS.PRENUME end) AGENT, NPART.DEN_PART, NCP.DEN_CLASEP,
        COALESCE(NOBJ.DENUMIRE,NART.DEN_ARTICOL), NCA.DEN_CLASEA,
        SUM(T.SI), SUM(T.SI + T.VV - T.VI)' || coalesce(PKG_LIST_BASE_VANZAGENTART_CAMPURI('SELECT'),'') || gUserAlias || '
      FROM TMP T
        INNER JOIN NPERS        ON NPERS.CODPERS   = T.AGENT
        INNER JOIN NPART        ON NPART.CODPART   = T.PARTENER
        LEFT JOIN NAGENDA SSOC  ON SSOC.CODPART    = NPART.CODPART AND SSOC.SEDIUSOCIAL BETWEEN 4 AND 7 AND COALESCE(SSOC.INACTIV, 0) = 0
        LEFT JOIN NLOCALIT LSOC ON LSOC.CODLOCALIT = COALESCE(SSOC.CODLOCALIT, 0)
        LEFT JOIN NJUDET JSOC   ON JSOC.CODJUDET   = COALESCE(LSOC.CODJUDET, 0)
        LEFT JOIN NTARI TSOC    ON TSOC.CODTARA    = COALESCE(LSOC.CODTARA, 0)
        LEFT JOIN NARTOBJ NOBJ  ON NOBJ.CODOBIECT  = T.CODOBIECT
        LEFT JOIN NART          ON NART.CODARTICOL = COALESCE(NOBJ.CODARTICOL,0)
        LEFT JOIN NCLASEP NCP   ON NCP.CODCLASEP   = NPART.CODCLASA
        LEFT JOIN NCLASEA NCA   ON NCA.CODCLASEA   = NART.CLASA' || gSuplJoins || '
      GROUP BY T.AGENT, NPERS.NUME, NPERS.PRENUME, NPART.DEN_PART, NCP.DEN_CLASEP, NOBJ.DENUMIRE, NART.DEN_ARTICOL, NCA.DEN_CLASEA' || gUserAlias;
   sUpdate :='
      UPDATE '|| tmpName ||' A
      SET (S_VV, S_VI, S_XV, S_NV, S_VA) = (SELECT Sum(B.T_VV), Sum(B.T_VI), Sum(B.T_XV), Sum(B.T_NV), Sum(B.T_VA) FROM '|| tmpName ||' B WHERE B.Agent = A.Agent AND B.Client = A.Client)';
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(supdate, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzagentart_setjoinuri</obj_name>
  <obj_hashval>1c8d892434007ccd0d08159842b34a42</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzagentart_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 22.08.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_VANZAGENTART.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzari_setjoinuri</obj_name>
  <obj_hashval>7fcfc8ed6a5e9e87463bc720fcb38e39</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzari_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 16.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_VANZARI.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzaridiscount_setjoinuri</obj_name>
  <obj_hashval>b745e2d17912f8bcfed82fe7671f8819</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzaridiscount_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 10 septembrie 2020
  NULL;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzper_baga_dinamic_cols</obj_name>
  <obj_hashval>0a773e650cbff347f1afd8417b06899c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzper_baga_dinamic_cols()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  K           NUMERIC := 0;
  sAux         varchar := '';
  sOld         varchar := '';
  dAux         date;
  sCant       varchar := '';
   vTipUM      NUMERIC := current_setting('PKG_LIST_BASE_VANZPER.vTipUM'     , true)::NUMERIC;
   vTipPer      NUMERIC := current_setting('PKG_LIST_BASE_VANZPER.vTipPer'    , true)::NUMERIC;
   vDataIni    varchar := current_setting('PKG_LIST_BASE_VANZPER.vDataIni'   , true);
   vDataFin    varchar := current_setting('PKG_LIST_BASE_VANZPER.vDataFin'   , true);
   vCantitativ  boolean := current_setting('PKG_LIST_BASE_VANZPER.vCantitativ', true)::boolean;
   vCantCutii  boolean := current_setting('PKG_LIST_BASE_VANZPER.vCantCutii' , true)::boolean;
   vCantPaleti  boolean := current_setting('PKG_LIST_BASE_VANZPER.vCantPaleti', true)::boolean;
   vValoric    boolean := current_setting('PKG_LIST_BASE_VANZPER.vValoric'   , true)::boolean;
   vInclTVA    boolean := current_setting('PKG_LIST_BASE_VANZPER.vInclTVA'   , true)::boolean;
   vInclUnit    boolean := current_setting('PKG_LIST_BASE_VANZPER.vInclUnit'  , true)::boolean;
   vVariatie    boolean := current_setting('PKG_LIST_BASE_VANZPER.vVariatie'  , true)::boolean;
BEGIN
  --Florin 03.05.2023 - sinc. Oracle
  --Florin 23.03.2023 - sinc. Oracle
  --Florin 27.01.2022 - fixat 52757
  --Adina 30.06.2021 - tichet 50679 - modificat linia 70 - add case pt.anii bisecti
  --Florin 21.08.2020
  --Adina 21.10.2020 - aranjat
  DELETE FROM tmp_dinamic_cols;

  CASE vTipUM
     WHEN 3 THEN sCant := 'KG';
    WHEN 4 THEN sCant := 'CC';
    ELSE        sCant := 'Cant.';
  END CASE;

  CASE vTipPer
    WHEN 1 THEN
      dAux := to_date(vDataIni, 'dd.mm.yyyy');
      WHILE dAux &lt;= to_date(vDataFin, 'dd.mm.yyyy') LOOP
        k := k + 1;
        sAux := To_Char(dAux, 'dd.mm.yyyy');
        IF vCantitativ THEN
          INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('C' || To_Char(k, 'fm999'), sCant || '/' || sAux, k);
        END IF;
        IF vCantCutii THEN
          INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('CC' || To_Char(k, 'fm999'), 'Cutii/' || sAux, k);
        END IF;
        IF vCantPaleti THEN
          INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('CP' || To_Char(k, 'fm999'), 'Paleti/' || sAux, k);
        END IF;
        IF vValoric THEN
          INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('V' || To_Char(k, 'fm999'), 'Val./' || sAux, k);
        END IF;
        IF vInclTVA THEN
          INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('VT' || To_Char(k, 'fm999'), 'Val.(+TVA)/' || sAux, k);
        END IF;
        IF vInclUnit THEN
          INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('VU' || To_Char(k, 'fm999'), 'VU/' || sAux, k);
        END IF;
        IF k &gt; 1 AND vVariatie THEN
          INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('VV' || To_Char(k - 1, 'fm999'), 'Var./' || sOld || '-' || sAux, k);
        END IF;
        INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('D' || To_Char(k, 'fm999'), 'Disc.mon./' || sAux, k);
        sOld := sAux;
        dAux := dAux + 1;
      END LOOP;
    WHEN 2 THEN
      dAux := trunc(to_date(vDataIni, 'dd.mm.yyyy'), 'iw');
        WHILE dAux &lt;= to_date(vDataFin, 'dd.mm.yyyy') LOOP
          k := k + 1;
          sAux := coalesce(To_Char(dAux, 'IW.IYYY'),'');

          IF vCantitativ THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('C' || To_Char(k, 'fm999'), sCant || '/Sapt.' || sAux, k);
          END IF;
          IF vCantCutii THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('CC' || To_Char(k, 'fm999'), 'Cutii/Sapt.' || sAux, k);
          END IF;
          IF vCantPaleti THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('CP' || To_Char(k, 'fm999'), 'Paleti/Sapt' || sAux, k);
          END IF;
          IF vValoric THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('V' || To_Char(k, 'fm999'), 'Val./Sapt.' || sAux, k);
          END IF;
          IF vInclTVA THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('VT' || To_Char(k, 'fm999'), 'Val.(+TVA)/Sapt.' || sAux, k);
          END IF;
          IF vInclUnit THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('VU' || To_Char(k, 'fm999'), 'VU/Sapt.' || sAux, k);
          END IF;
          IF  k &gt; 1 AND vVariatie THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('VV' || To_Char(k - 1, 'fm999'), 'Var./Sapt.' || sOld || '-' || sAux, k);
          END IF;
          sOld := sAux;
          dAux := add_days(dAux, 7::integer);
        END LOOP;
    WHEN 3 THEN
      BEGIN
        dAux := to_date(current_setting('PKG_LIST_BASE_VANZPER.vDataIni', true), 'dd.mm.yyyy');

        WHILE  dAux &lt;= to_date(current_setting('PKG_LIST_BASE_VANZPER.vDataFin', true), 'dd.mm.yyyy') LOOP
          k := k + 1;
          sAux := To_Char(dAux, 'mm.yyyy');
          IF vCantitativ THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('C' || To_Char(k, 'fm999'), sCant || '/Luna ' || sAux, k);
          END IF;
          IF vCantCutii THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('CC' || To_Char(k, 'fm999'), 'Cutii/Luna ' || sAux, k);
          END IF;
          IF vCantPaleti THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('CP' || To_Char(k, 'fm999'), 'Paleti/Luna ' || sAux, k);
          END IF;
          IF vValoric THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('V' || To_Char(k, 'fm999'), 'Val./Luna ' || sAux, k);
          END IF;
          IF vInclTVA THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('VT' || To_Char(k, 'fm999'), 'Val.(+TVA)/Luna ' || sAux, k);
          END IF;
          IF vInclUnit THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('VU' || To_Char(k, 'fm999'), 'VU/Luna ' || sAux, k);
          END IF;
          IF  k &gt; 1 AND vVariatie THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('VV' || To_Char(k - 1, 'fm999'), 'Var./Luna ' || sOld || '-' || sAux, k);
          END IF;
          sOld := sAux;
          dAux := date_trunc('MONTH', ADD_MONTHS(dAux, 1));
        END LOOP;
      END;
    WHEN 4 THEN
      BEGIN
        dAux := DATE_TRUNC('QUARTER',to_date(vDataIni, 'dd.mm.yyyy'));
        WHILE  dAux &lt;= to_date(vDataFin, 'dd.mm.yyyy') LOOP
          k := k + 1;
          sAux := To_Char(dAux, 'Q.YYYY');
          IF vCantitativ THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('C' || To_Char(k, 'fm999'), sCant || '/Trim.' || sAux, k);
          END IF;
          IF vCantCutii THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('CC' || To_Char(k, 'fm999'), 'Cutii/Trim.' || sAux, k);
          END IF;
          IF vCantPaleti THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('CP' || To_Char(k, 'fm999'), 'Paleti/Trim.' || sAux, k);
          END IF;
          IF vValoric THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('V' || To_Char(k, 'fm999'), 'Val./Trim.' || sAux, k);
          END IF;
          IF vInclTVA THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('VT' || To_Char(k, 'fm999'), 'Val.(+TVA)/Trim.' || sAux, k);
          END IF;
          IF vInclUnit THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('VU' || To_Char(k, 'fm999'), 'VU/Trim.' || sAux, k);
          END IF;
          IF  k &gt; 1 AND vVariatie THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('VV' || To_Char(k - 1, 'fm999'), 'Var./Trim.' || sOld || '-' || sAux, k);
          END IF;
          sOld := sAux;
          dAux := ADD_MONTHS(dAux, 3);
        END LOOP;
      END;
    WHEN 5 THEN
      BEGIN
        FOR i IN current_setting('PKG_LIST_BASE_VANZPER.vInceput', true)::numeric..current_setting('PKG_LIST_BASE_VANZPER.vSfarsit', true)::numeric LOOP
          k := k + 1;
          sAux := To_Char(i,'fm9999');
          IF current_setting('PKG_LIST_BASE_VANZPER.vCantitativ', true)::boolean THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('C' ||To_Char(k  ,'fm999'), sCant||'/An '||To_Char(i,'fm9999'),k);
          END IF;
          IF current_setting('PKG_LIST_BASE_VANZPER.vCantCutii', true)::boolean THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('CC'||To_Char(k  ,'fm999'), 'Cutii/An '||sAux,k);
          END IF;
          IF current_setting('PKG_LIST_BASE_VANZPER.vCantPaleti', true)::boolean THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('CP'||To_Char(k  ,'fm999'), 'Paleti/An '||sAux,k);
          END IF;
          IF current_setting('PKG_LIST_BASE_VANZPER.vValoric', true)::boolean THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('V' ||To_Char(k  ,'fm999'), 'Val./An '||To_Char(i,'fm9999'),k);
          END IF;
          IF current_setting('PKG_LIST_BASE_VANZPER.vInclTVA', true)::boolean THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('VT'||To_Char(k  ,'fm999'), 'Val.(+TVA)/An ' ||sAux,k);
          END IF;
          IF current_setting('PKG_LIST_BASE_VANZPER.vInclUnit', true)::boolean THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('VU'||To_Char(k  ,'fm999'), 'VU/An ' ||sAux,k);
          END IF;
          IF k &gt; 1 AND current_setting('PKG_LIST_BASE_VANZPER.vVariatie', true)::boolean THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('VV'||To_Char(k-1,'fm999'), 'Var./An.' ||sOld||'-'||sAux,k);
          END IF;
          sOld := sAux;
        END LOOP;
      END;
  END CASE;
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vNrCol',k::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzper_fl_baga_dinamic_cols</obj_name>
  <obj_hashval>cbbf4a1c6cdf6a59920d2716b3280a3e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzper_fl_baga_dinamic_cols()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  I     NUMERIC;
  J     NUMERIC;
  K     NUMERIC := 0;
  sAux  varchar;
  sOld  varchar;
  dAux  date;
  sCant varchar;
BEGIN
  --Florin 21.08.2020
  DELETE FROM tmp_dinamic_cols;

  CASE current_setting('PKG_LIST_BASE_VANZPER.vTipUM', true)::NUMERIC
    WHEN 3 THEN sCant := 'KG';
    WHEN 4 THEN sCant := 'CC';
    ELSE sCant := 'Cant.';
  END CASE;

  CASE current_setting('PKG_LIST_BASE_VANZPER.vTipPer', true)::NUMERIC
  WHEN 1 THEN
    dAux := to_date(current_setting('PKG_LIST_BASE_VANZPER.vDataIni', true), 'dd.mm.yyyy');
    WHILE dAux &lt;= to_date(current_setting('PKG_LIST_BASE_VANZPER.vDataFin', true), 'dd.mm.yyyy') LOOP
      k    := k + 1;
      sAux := To_Char(dAux, 'dd.mm.yyyy');
      IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vCantitativ') THEN
        INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal)
        VALUES('C' || coalesce(To_Char(k, 'fm999'),''), coalesce(sCant,'') || '/' || coalesce(sAux,''), k);
      END IF;
      IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vCantCutii') THEN
        INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal)
        VALUES('CC' || coalesce(To_Char(k, 'fm999'),''), 'Cutii/' || coalesce(sAux,''), k);
      END IF;
      IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vCantPaleti')
      THEN
        INSERT INTO tmp_dinamic_cols
        (
        FieldName, Display, IndexLocal
        )
        VALUES
        (
        'CP' || coalesce(To_Char(k, 'fm999'),''), 'Paleti/' || coalesce(sAux,''), k
        );
      END IF;
      IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vValoric')
      THEN
        INSERT INTO tmp_dinamic_cols
        (
        FieldName, Display, IndexLocal
        )
        VALUES
        (
        'V' || coalesce(To_Char(k, 'fm999'),''), 'Val./' || coalesce(sAux,''), k
        );
      END IF;
      IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vInclTVA')
      THEN
        INSERT INTO tmp_dinamic_cols
        (
        FieldName, Display, IndexLocal
        )
        VALUES
        (
        'VT' || coalesce(To_Char(k, 'fm999'),''), 'Val.(+TVA)/' || coalesce(sAux,''), k
        );
      END IF;
      IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vInclUnit')
      THEN
        INSERT INTO tmp_dinamic_cols
        (
        FieldName, Display, IndexLocal
        )
        VALUES
        (
        'VU' || coalesce(To_Char(k, 'fm999'),''), 'VU/' || coalesce(sAux,''), k
        );
      END IF;
      IF k &gt; 1 AND fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vVariatie')
      THEN
        INSERT INTO tmp_dinamic_cols
        (
        FieldName, Display, IndexLocal
        )
        VALUES
        (
        'VV' || coalesce(To_Char(k - 1, 'fm999'),''), 'Var./' || coalesce(sOld,'') || '-' || coalesce(sAux,''), k
        );
    END IF;
    sOld := sAux;
    dAux := dAux + 1;
  END LOOP;
  WHEN 2
  THEN
  BEGIN
   j := To_Char(to_date(to_char(date_trunc('year', to_date(current_setting('PKG_LIST_BASE_VANZPER.vDataIni', true), 'dd.mm.yyyy')), 'iyyy-iw'), 'iyyy-iw'), 'D')::numeric - 1;
    i := 0;
    dAux := add_days(to_date(to_char(date_trunc('year', to_date(current_setting('PKG_LIST_BASE_VANZPER.vDataIni', true), 'dd.mm.yyyy')), 'iyyy-iw'), 'iyyy-iw'), (- j)::integer);
    WHILE add_days(dAux, 7::integer) &lt;= to_date(current_setting('PKG_LIST_BASE_VANZPER.vDataIni', true), 'dd.mm.yyyy') LOOP
      i := i + 1;
      dAux := add_days(dAux, 7::integer);
    END LOOP;
    WHILE dAux &lt;= to_date(current_setting('PKG_LIST_BASE_VANZPER.vDataFin', true), 'dd.mm.yyyy') LOOP
    k := k + 1;
    i := i + 1;
    IF i &gt; 52 AND To_Char(dAux, 'ddd') &lt;= '7'
    THEN
    i := 1;
    END IF;
    sAux := To_Char(i, 'fm999');
    IF dAux &lt; to_date(current_setting('PKG_LIST_BASE_VANZPER.vDataIni', true), 'dd.mm.yyyy')
    THEN
      sAux := coalesce(sAux,'') || '.' || coalesce(To_Char(to_date(current_setting('PKG_LIST_BASE_VANZPER.vDataIni', true), 'dd.mm.yyyy'), 'iyyy'),'');
    ELSE
      sAux := coalesce(sAux,'') || '.' || coalesce(To_Char(dAux, 'iyyy'),'');
    END IF;
    IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vCantitativ')
    THEN
      INSERT INTO tmp_dinamic_cols
      (
      FieldName, Display, IndexLocal
      )
      VALUES
      (
      'C' || coalesce(To_Char(k, 'fm999'),''), coalesce(sCant,'') || '/Sapt.' || coalesce(sAux,''), k
      );
      END IF;
      IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vCantCutii')
      THEN
      INSERT INTO tmp_dinamic_cols
      (
      FieldName, Display, IndexLocal
      )
      VALUES
      (
      'CC' || coalesce(To_Char(k, 'fm999'),''), 'Cutii/Sapt.' || coalesce(sAux,''), k
      );
      END IF;
    IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vCantPaleti')
    THEN
      INSERT INTO tmp_dinamic_cols
      (
      FieldName, Display, IndexLocal
      )
      VALUES
      (
      'CP' || coalesce(To_Char(k, 'fm999'),''), 'Paleti/Sapt' || coalesce(sAux,''), k
      );
      END IF;
      IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vValoric')
      THEN
      INSERT INTO tmp_dinamic_cols
      (
      FieldName, Display, IndexLocal
      )
      VALUES
      (
      'V' || coalesce(To_Char(k, 'fm999'),''), 'Val./Sapt.' || coalesce(sAux,''), k
      );
    END IF;
    IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vInclTVA')
    THEN
      INSERT INTO tmp_dinamic_cols
      (
      FieldName, Display, IndexLocal
      )
      VALUES
      (
      'VT' || coalesce(To_Char(k, 'fm999'),''), 'Val.(+TVA)/Sapt.' || coalesce(sAux,''), k
      );
      END IF;
      IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vInclUnit')
      THEN
      INSERT INTO tmp_dinamic_cols
      (
      FieldName, Display, IndexLocal
      )
      VALUES
      (
      'VU' || coalesce(To_Char(k, 'fm999'),''), 'VU/Sapt.' || coalesce(sAux,''), k
      );
    END IF;
    IF  k &gt; 1 AND fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vVariatie')
    THEN
      INSERT INTO tmp_dinamic_cols
      (
      FieldName, Display, IndexLocal
      )
      VALUES
      (
      'VV' || coalesce(To_Char(k - 1, 'fm999'),''), 'Var./Sapt.' || coalesce(sOld,'') || '-' || coalesce(sAux,''), k
      );
    END IF;
    sOld := sAux;
    dAux := dAux + 7;
  END LOOP;
  END;
  WHEN 3
  THEN
  BEGIN
    dAux := to_date(current_setting('PKG_LIST_BASE_VANZPER.vDataIni', true), 'dd.mm.yyyy');
    WHILE  dAux &lt;= to_date(current_setting('PKG_LIST_BASE_VANZPER.vDataFin', true), 'dd.mm.yyyy') LOOP
    k := k + 1;
    sAux := To_Char(dAux, 'mm.yyyy');
    IF current_setting('PKG_LIST_BASE_VANZPER.vCantitativ', true)
    THEN
    INSERT INTO tmp_dinamic_cols
    (
    FieldName, Display, IndexLocal
    )
    VALUES
    (
    'C' || coalesce(To_Char(k, 'fm999'),''), coalesce(sCant,'') || '/Luna ' || coalesce(sAux,''), k
    );
    END IF;
    IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vCantCutii')
    THEN
    INSERT INTO tmp_dinamic_cols
    (
    FieldName, Display, IndexLocal
    )
    VALUES
    (
    'CC' || coalesce(To_Char(k, 'fm999'),''), 'Cutii/Luna ' || coalesce(sAux,''), k
    );
    END IF;
    IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vCantPaleti')
    THEN
    INSERT INTO tmp_dinamic_cols
    (
    FieldName, Display, IndexLocal
    )
    VALUES
    (
    'CP' || coalesce(To_Char(k, 'fm999'),''), 'Paleti/Luna ' || coalesce(sAux,''), k
    );
    END IF;
    IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vValoric')
    THEN
    INSERT INTO tmp_dinamic_cols
    (
    FieldName, Display, IndexLocal
    )
    VALUES
    (
    'V' || coalesce(To_Char(k, 'fm999'),''), 'Val./Luna ' || coalesce(sAux,''), k
    );
    END IF;
    IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vInclTVA')
    THEN
    INSERT INTO tmp_dinamic_cols
    (
    FieldName, Display, IndexLocal
    )
    VALUES
    (
    'VT' || coalesce(To_Char(k, 'fm999'),''), 'Val.(+TVA)/Luna ' || coalesce(sAux,''), k
    );
    END IF;
    IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vInclUnit')
    THEN
    INSERT INTO tmp_dinamic_cols
    (
    FieldName, Display, IndexLocal
    )
    VALUES
    (
    'VU' || coalesce(To_Char(k, 'fm999'),''), 'VU/Luna ' || coalesce(sAux,''), k
    );
    END IF;
    IF  k &gt; 1 AND fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vVariatie')
    THEN
    INSERT INTO tmp_dinamic_cols
    (
    FieldName, Display, IndexLocal
    )
    VALUES
    (
    'VV' || coalesce(To_Char(k - 1, 'fm999'),''), 'Var./Luna ' || coalesce(sOld,'') || '-' || coalesce(sAux,''), k
    );
    END IF;
    sOld := sAux;
    dAux := date_trunc('MONTH', ADD_MONTHS(dAux, 1));
    END LOOP;
    END;
    WHEN 4
    THEN
    BEGIN
      dAux := DATE_TRUNC('QUARTER',to_date(current_setting('PKG_LIST_BASE_VANZPER.vDataIni', true), 'dd.mm.yyyy'));
      WHILE  dAux &lt;= to_date(current_setting('PKG_LIST_BASE_VANZPER.vDataFin', true), 'dd.mm.yyyy') LOOP
      k := k + 1;
      sAux := To_Char(dAux, 'QYYYY');
      IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vCantitativ')
      THEN
      INSERT INTO tmp_dinamic_cols
      (
      FieldName, Display, IndexLocal
      )
      VALUES
      (
      'C' || coalesce(To_Char(k, 'fm999'),''), coalesce(sCant,'') || '/Trim.' || coalesce(sAux,''), k
      );
      END IF;
      IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vCantCutii')
      THEN
      INSERT INTO tmp_dinamic_cols
      (
      FieldName, Display, IndexLocal
      )
      VALUES
      (
      'CC' || coalesce(To_Char(k, 'fm999'),''), 'Cutii/Trim.' || coalesce(sAux,''), k
      );
      END IF;
      IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vCantPaleti')
      THEN
      INSERT INTO tmp_dinamic_cols
      (
      FieldName, Display, IndexLocal
      )
      VALUES
      (
      'CP' || coalesce(To_Char(k, 'fm999'),''), 'Paleti/Trim.' || coalesce(sAux,''), k
      );
      END IF;
      IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vValoric')
      THEN
      INSERT INTO tmp_dinamic_cols
      (
      FieldName, Display, IndexLocal
      )
      VALUES
      (
      'V' || coalesce(To_Char(k, 'fm999'),''), 'Val./Trim.' || coalesce(sAux,''), k
      );
      END IF;
      IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vInclTVA')
      THEN
      INSERT INTO tmp_dinamic_cols
      (
      FieldName, Display, IndexLocal
      )
      VALUES
      (
      'VT' || coalesce(To_Char(k, 'fm999'),''), 'Val.(+TVA)/Trim.' || coalesce(sAux,''), k
      );
      END IF;
      IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vInclUnit')
      THEN
      INSERT INTO tmp_dinamic_cols
      (
      FieldName, Display, IndexLocal
      )
      VALUES
      (
      'VU' || coalesce(To_Char(k, 'fm999'),''), 'VU/Trim.' || coalesce(sAux,''), k
      );
      END IF;
      IF  k &gt; 1 AND fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vVariatie')
      THEN
      INSERT INTO tmp_dinamic_cols
      (
      FieldName, Display, IndexLocal
      )
      VALUES
      (
      'VV' || coalesce(To_Char(k - 1, 'fm999'),''), 'Var./Trim.' || coalesce(sOld,'') || '-' || coalesce(sAux,''), k
      );
      END IF;
    sOld := sAux;
    dAux := ADD_MONTHS(dAux, 3);
  END LOOP;
  END;
  WHEN 5
  THEN
  BEGIN
    FOR i IN current_setting('PKG_LIST_BASE_VANZPER.vInceput', true)::numeric..current_setting('PKG_LIST_BASE_VANZPER.vSfarsit', true)::numeric LOOP
          k := k + 1;
          sAux := To_Char(i,'fm9999');
          IF current_setting('PKG_LIST_BASE_VANZPER.vCantitativ', true)::boolean THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('C' ||To_Char(k  ,'fm999'), sCant||'/An '||To_Char(i,'fm9999'),k);
          END IF;
          IF current_setting('PKG_LIST_BASE_VANZPER.vCantCutii', true)::boolean THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('CC'||To_Char(k  ,'fm999'), 'Cutii/An '||sAux,k);
          END IF;
          IF current_setting('PKG_LIST_BASE_VANZPER.vCantPaleti', true)::boolean THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('CP'||To_Char(k  ,'fm999'), 'Paleti/An '||sAux,k);
          END IF;
          IF current_setting('PKG_LIST_BASE_VANZPER.vValoric', true)::boolean THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('V' ||To_Char(k  ,'fm999'), 'Val./An '||To_Char(i,'fm9999'),k);
          END IF;
          IF current_setting('PKG_LIST_BASE_VANZPER.vInclTVA', true)::boolean THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('VT'||To_Char(k  ,'fm999'), 'Val.(+TVA)/An ' ||sAux,k);
          END IF;
          IF current_setting('PKG_LIST_BASE_VANZPER.vInclUnit', true)::boolean THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('VU'||To_Char(k  ,'fm999'), 'VU/An ' ||sAux,k);
          END IF;
          IF k &gt; 1 AND current_setting('PKG_LIST_BASE_VANZPER.vVariatie', true)::boolean THEN
            INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('VV'||To_Char(k-1,'fm999'), 'Var./An.' ||sOld||'-'||sAux,k);
          END IF;
          sOld := sAux;
        END LOOP;
  END;
  END CASE;
  PERFORM set_config('PKG_LIST_BASE_VANZPER.vNrCol',k::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzper_fl_processlist</obj_name>
  <obj_hashval>5dd8c7550d232f104134ba85010055bc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzper_fl_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar;
  sSelect varchar;
  sUpdate varchar;
  sWhere varchar;
  sJoinUM varchar;
  sJoinU1 varchar;
  sCurs varchar;
  sCampUM varchar := 'NUM.DEN_UM';
  vVal varchar;
  sInsAUX varchar;
  sSelAUX varchar;
  sJoinUMA varchar;
  sJoinCL varchar;
  aSitV numeric;
  aBancaV numeric;
  aMonedaV numeric;
  K NUMERIC;
  sCU1 varchar := '';
  vMaxCl NUMERIC;
  sAnP numeric;
  sLunaP numeric;
  sAnM numeric;
  sLunaM numeric;
  vDataRef date;
  sTipLin varchar := '''=''';
  sArtAtrib1 varchar := ', NULL ARTATRIB1';
  sFiltruObj varchar := '';
  gSuplCols varchar := 'NARTOBJ NAO, NART NA, NUM NUM, NGEST NG, NPART NP, NPART PROD, IOART IOA, NCLASEA NCA, NCLASEP NCP, NPERS AG, ' || 'NAGENDA SSOC, NLOCALIT LSOC, NJUDET JSOC, NAGENDA SLIV, NLOCALIT LLIV, NJUDET JLIV, TRASEULIVR TLIV, NTIPSEDII TIPSLIV,PRETM PRETIMP';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  wmeRes     boolean;
BEGIN
  --Adina 19.02.2021 - GetInfoSitValuta
  --Florin 21.08.2020
  IF current_setting('PKG_LIST_BASE_VANZPER.vCodAtribut', true)::numeric &gt; 0
  THEN
    sArtAtrib1 := ',
      (SELECT Min(aa1.valoare)
        FROM nartatr aa
          LEFT JOIN natrobj ao ON ao.codartatr = aa.codartatr
          LEFT JOIN natrib1 aa1 ON aa1.codvalatr = ao.codvalatr
        WHERE aa.codarticol = nao.codarticol AND ao.codobiect = nao.codobiect AND aa.codatribut = ' || coalesce(current_setting('PKG_LIST_BASE_VANZPER.vCodAtribut', true) ,'') || '
      ) ARTATRIB1';
  sFiltruObj := ' and exists (select aa.codatribut from nartatr aa where aa.codarticol = nao.codarticol AND aa.codatribut = ' || coalesce(current_setting('PKG_LIST_BASE_VANZPER.vCodAtribut', true) ,'') || ') ';
  END IF;

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = NAO.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = NAO.CODOBIECT',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_VANZPER.gSuplCols', gSuplCols, FALSE);

  PERFORM pkg_list_base_vanzper_BAGA_JOB_DINAMIC_COLS(tmpName);
  IF current_setting('PKG_LIST_BASE_VANZPER.vTipPer', true)::numeric = 5
  THEN
    IF current_setting('PKG_LIST_BASE_VANZPER.vLunaIni', true)::numeric = current_setting('PKG_LIST_BASE_VANZPER.vLunaFin', true)::numeric
    THEN
      sWhere := 'I.LUNA = ' || coalesce(current_setting('PKG_LIST_BASE_VANZPER.vLunaIni', true)::numeric,0) || ' AND I.An';
    ELSE
      sWhere := 'I.LUNA BETWEEN ' || coalesce(current_setting('PKG_LIST_BASE_VANZPER.vLunaIni', true)::numeric,0) || ' AND ' || coalesce(current_setting('PKG_LIST_BASE_VANZPER.vLunaFin', true)::numeric,0) || ' AND I.An';
    END IF;
    ELSIF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vTipData')
    THEN
    sWhere := 'I.DataDoc';
    ELSE
    sWhere := 'I.An*12+I.LUNA';
  END IF;
  IF current_setting('PKG_LIST_BASE_VANZPER.vInceput', true) = current_setting('PKG_LIST_BASE_VANZPER.vSfarsit', true) AND fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vTipData')
    THEN
      sWhere := coalesce(sWhere,'') || ' = To_Date(''' || coalesce(current_setting('PKG_LIST_BASE_VANZPER.vInceput', true),'') || ''',''dd.mm.yyyy'')';
    ELSIF
      current_setting('PKG_LIST_BASE_VANZPER.vInceput', true) = current_setting('PKG_LIST_BASE_VANZPER.vSfarsit', true)
    THEN
      sWhere := coalesce(sWhere,'') || ' = ' || coalesce(current_setting('PKG_LIST_BASE_VANZPER.vInceput', true),'');
    ELSIF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vTipData')
    THEN
      sWhere := coalesce(sWhere,'') || ' BETWEEN ' || ' To_Date(''' || coalesce(current_setting('PKG_LIST_BASE_VANZPER.vInceput', true),'') || ''',''dd.mm.yyyy'')' || ' AND ' ||
      'To_Date(''' || coalesce(current_setting('PKG_LIST_BASE_VANZPER.vInceput', true),'') || ''',''dd.mm.yyyy'')' ;
    ELSE
      sWhere := COALESCE(sWhere, '')||' BETWEEN '|| coalesce(current_setting('PKG_LIST_BASE_VANZPER.vInceput', true), '') ||' AND '|| coalesce(current_setting('PKG_LIST_BASE_VANZPER.vsfarsit', true), '');
  END IF;
  IF current_setting('PKG_LIST_BASE_VANZPER.vTipUM', true)::numeric = 3
    THEN
    sWhere := coalesce(sWhere,'') || '
              AND (COALESCE(O.MASA,0) &lt;&gt; 0 OR U.TIPUM = 1)';
  END IF;
  IF current_setting('PKG_LIST_BASE_VANZPER.vTipUM', true)::numeric = 4
  THEN
    sWhere := coalesce(sWhere,'') || '
              AND (COALESCE(O.VOLUM,0) &lt;&gt; 0 OR U.TIPUM = 2)';
  END IF;

  SELECT pkg_list_base_utils_GetInfoSitValuta.wme_result, psitvaluta, pbancavaluta, pmonedavaluta
  INTO wmeRes, aSitV, aBancaV, aMonedaV
  FROM pkg_list_base_utils_GetInfoSitValuta(NULL, aSitV, aBancaV, aMonedaV);

  IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vValuta') AND wmeRes  --(SELECT pkg_list_base_utils_GetInfoSitValuta.WME_RESULT FROM pkg_list_base_utils_GetInfoSitValuta(NULL,aSitV, aBancaV, aMonedaV))
  THEN
    sCurs := '/ PKG_LIST_BASE_UTILS_GETCURSREFERINTA(' || coalesce(aMonedaV,0) || ',' || coalesce(aBancaV,0) || ', to_char(i.datadoc,''dd.mm.yyyy'') )';
  END IF;

  IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vCantitativ')
  THEN
    vVal := coalesce(vVal,'') || ',
              CASE WHEN I.TIPDOC = 26 AND AE1.CANT &lt;&gt; 0 THEN I1.CANT/AE1.CANT ELSE 1 END * COALESCE(L1.CANT,I1.CANT) CAux';
  END IF;
  IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vValoric')
  THEN
    vVal := coalesce(vVal,'') || ',
              CASE WHEN I.TIPDOC = 26 AND AE1.CANT &lt;&gt; 0 THEN I1.CANT/AE1.CANT ELSE 1 END * COALESCE(L1.CANT,I1.CANT) * i1.pretorig * COALESCE(i1.coefdiscmaj,1) * CASE WHEN i.tipdoc IN (16,21) AND (i1.cant * i1.pu) &lt;&gt; 0 THEN (1 - COALESCE(i1.tva,0) / (i1.cant * i1.pu)) ELSE 1 END * i.curs' || coalesce(sCurs,'') || ' VAux';
    END IF;
    IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vInclTVA')
    THEN
      vVal := coalesce(vVal,'') || ',
              CASE WHEN I.TIPDOC = 26 AND AE1.CANT &lt;&gt; 0 THEN I1.CANT/AE1.CANT ELSE 1 END * COALESCE(L1.CANT,I1.CANT) * i1.pretorig * COALESCE(i1.coefdiscmaj,1) * CASE WHEN i.tipdoc IN (16,21) OR (i1.cant * i1.pu) = 0 THEN 1 ELSE (1 + COALESCE(i1.tva,0) / (i1.cant * i1.pu)) END * i.curs' || coalesce(sCurs,'') || ' VTAux';
  END IF;
  IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vInclUnit')
  THEN
    vVal := coalesce(vVal,'') || ',
              CASE WHEN I.TIPDOC = 26 AND AE1.CANT &lt;&gt; 0 THEN I1.CANT/AE1.CANT ELSE 1 END * COALESCE(L1.CANT,I1.CANT) * i1.pu * CASE WHEN i.tipdoc IN (16,21) AND (i1.cant * i1.pu) &lt;&gt; 0 THEN (1 - COALESCE(i1.tva,0) / (i1.cant * i1.pu)) ELSE 1 END * i.curs' || coalesce(sCurs,'') || ' VUAux';
    END IF;
    sJoinU1 := '
        LEFT JOIN NUM1 U1 ON U1.CODUM = NA.UM AND SECUNDARA = 0';
    IF current_setting('PKG_LIST_BASE_VANZPER.vTipUM', true)::numeric = 1
    THEN
      sJoinUM := '
            INNER JOIN NARTOBJ O ON O.CODOBIECT = I1.CODOBIECT
            INNER JOIN NART ART ON ART.CODARTICOL = O.CODARTICOL AND ART.UM = ' || coalesce(current_setting('PKG_LIST_BASE_VANZPER.vUM', true)::numeric,0);
    ELSIF current_setting('PKG_LIST_BASE_VANZPER.vTipUM', true)::numeric = 2
    THEN
      sJoinUM := '
            INNER JOIN NARTOBJ O ON O.CODOBIECT = I1.CODOBIECT
            INNER JOIN NARTAMB AA ON AA.CODOBIECT = O.CODOBIECT AND AA.UMSEC = ' || coalesce(current_setting('PKG_LIST_BASE_VANZPER.vUM', true)::numeric,0) || '
            INNER JOIN NUM1 U1 ON U1.CODUM1 = AA.UMSEC';
      sCU1 := ', ' || coalesce(current_setting('PKG_LIST_BASE_VANZPER.vUM', true)::numeric,0) || ' CU1';
      sJoinU1 := '
        LEFT JOIN NUM1 U1 ON U1.CODUM1 = IG.CU1';
      sCampUM := 'U1.DEN_UM1';
      sInsAux := coalesce(sInsAux,'') || ', ParCant';
      sSelAux := coalesce(sSelAux,'') || ', U1.PARITATE';
    ELSIF current_setting('PKG_LIST_BASE_VANZPER.vTipUM', true)::numeric IN (3,4) THEN
    sJoinUM := '
        INNER JOIN NARTOBJ O ON O.CODOBIECT = I1.CODOBIECT
        INNER JOIN NART ART ON ART.CODARTICOL = O.CODARTICOL
        INNER JOIN NUM U ON U.CODUM = ART.UM';
    sCampUM  := CASE WHEN current_setting('PKG_LIST_BASE_VANZPER.vTipUM', true)::numeric = 3 THEN '''KG''' ELSE '''CC''' END;
    sInsAux  := sInsAux||', ParCant';
    sSelAux  := sSelAux||', NUM.COEF';
  END IF;
    IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vInclserv')
    THEN
      sTipLin := coalesce(sTipLin,'') || ',''S''';
    END IF;
    vDataRef := TO_DATE(current_setting('PKG_LIST_BASE_VANZPER.vDataFin', true), 'dd.mm.yyyy');
    sAnP := To_Char(vDataRef, 'yyyy');
    sLunaP := To_Char(vDataRef, 'mm');
    SELECT anmaxim, lunamaxima
    INTO sAnM, sLunaM
    FROM FIRMALUNI;
    IF sAnP * 12 + sLunaP &gt; sAnM * 12 + sLunaM
    THEN
      sAnP := sAnM;
      sLunaP := sLunaM;
    ELSE
      sAnM := sAnP;
      sLunaM := sLunaP;
    END IF;
  PERFORM PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA(sAnP, sLunaP, sAnP, sLunaP);
  sSelect := '
    WITH STOC AS (
      SELECT CODOBIECT, GEST, CODIOART, SUM(REST) STOCINI, SUM(VALACHIZ) VALACHIZ
      FROM (
        SELECT NS.CODOBIECT, N.GEST, NS.CODIOART, NL.REST, COALESCE(NS.PRET,0) * NL.REST VALACHIZ
        FROM NIRLUNA NL
          INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = NL.CODNIRSTOC
          INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
        WHERE NL.AN = ' || coalesce(sAnP,0) || ' AND NL.LUNA = ' || coalesce(sLunaP,0) || '
        UNION ALL -- NIRURI LUNA
        SELECT NS.CODOBIECT, N.GEST, NS.CODIOART, NS.CANTNIR AS REST, COALESCE(NS.PRET,0) * NS.CANTNIR VALACHIZ
        FROM NIRSTOC NS
          INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
          LEFT JOIN INTRARI I ON I.CODINTR = N.CODINTR
          LEFT JOIN TRANSF T ON T.CODTRANSF = N.CODTRANSF
        WHERE N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 12, 13) AND  N.ANULAT = 0 AND N.OPERAT = 1
          AND N.DATANIR &lt; To_Date(''' || coalesce(To_Char(vDataRef, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')
          AND COALESCE(I.AN,T.AN,0) = ' || coalesce(sAnM,0) || '
          AND COALESCE(I.LUNA,T.LUNA,0) = ' || coalesce(sLunaM,0) || '
        UNION ALL
        SELECT NS.CODOBIECT, N.GEST, NS.CODIOART, CASE WHEN L.TIPLIVR = 15 THEN L1.CANT ELSE -1 * L1.CANT END REST, COALESCE(NS.PRET,0) * CASE WHEN L.TIPLIVR = 15 THEN L1.CANT ELSE -1 * L1.CANT END VALACHIZ
        FROM LIVR L
          INNER JOIN LIVR1 L1 ON L1.CODLIVR = L.CODLIVR
          INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = L1.CODNIRSTOC
          INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
          LEFT JOIN INTRARI I ON I.CODINTR = L.CODINTR
          LEFT JOIN IESIRI IES ON IES.CODIES = L.CODIES
          LEFT JOIN TRANSF T ON T.CODTRANSF = L.CODTRANSF
        WHERE L.TIPLIVR IN (1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15 ,16, 19, 20, 21, 23, 24) AND L.OPERAT = 1 AND L.ANULAT = 0
          AND L.DATALIVR &lt; To_Date(''' || coalesce(To_Char(vDataRef,'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')
          AND COALESCE(I.AN,IES.AN,T.AN,0) = ' || coalesce(sAnM,0) || '
          AND COALESCE(I.LUNA,IES.LUNA,T.LUNA,0) = ' || coalesce(sLunaM,0) || '
      ) a_pg
      GROUP BY CODOBIECT, GEST, CODIOART)';
  IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vCantCutii') OR fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vCantPaleti')
  THEN
    sSelect := coalesce(sSelect,'') || ',
      UMA AS (
        SELECT
          AMB.CODOBIECT,
          Max((CASE WHEN Upper(U1.Codextern) = ''CUTIE'' THEN paritate END)) PUMAC,
          Max((CASE WHEN Upper(U1.Codextern) = ''PALET'' THEN paritate END)) PUMAP
        FROM NARTAMB AMB
          INNER JOIN NUM1 U1 ON U1.CODUM1 = AMB.UMSEC
        GROUP BY CODOBIECT)';
    sInsAux := coalesce(sInsAux,'') || ', ParCutie, ParPalet';
    sSelAux := coalesce(sSelAux,'') || ', UMA.PUMAC, UMA.PUMAP';
    sJoinUMA := '
      LEFT JOIN UMA ON UMA.CODOBIECT = NAO.CODOBIECT';
  END IF;
  vMaxCl := (SELECT PKG_LIST_BASE_UTILS_NIVELE_NCLASEA.WME_RESULT FROM PKG_LIST_BASE_UTILS_NIVELE_NCLASEA(NULL,NULL));
  IF vMaxCL &gt; 0
  THEN
    sJoinCL := coalesce(sJoinCL,'') || '
        LEFT JOIN (
          SELECT
            CODCLASEA ';
    FOR i in 1..vMaxCL loop
      sInsAUX := sInsAUX||', CL'||i::varchar  ||', CS'||i::varchar;
      sSelAUX := sSelAUX||', CL.D'||i::varchar||', CL.S'||i::varchar;
      sJoinCL := sJoinCL ||',
        Max(CASE WHEN nivel = '||i::varchar||' THEN den_clasea ELSE '''' end) D'||i::varchar||',
        Max(CASE WHEN nivel = '||i::varchar||' THEN simbol ELSE '''' end) S'||i::varchar;
    END LOOP;
    sJoinCL := coalesce(sJoinCL,'') || '
          FROM TMP_PROFIT_NCLASEA
        GROUP BY CODCLASEA
      ) CL ON CL.CodClasea = NA.Clasa ';
  END IF;
  sInsert := 'INSERT INTO ' || tmpName || '(Art, UM, Client, Gest, IOArt, DenClasaA, CodInt, CodExt, Prod, DenClasaC, SediuCli, SediuLiv, Agent, AgentI, StocFin, ValAchizStocFin, Masa, Volum,ArtAtrib1'
  || coalesce(sInsAUX,'') || coalesce(PKG_LIST_BASE_VANZPER_CAMPURI('INSERT',NULL),'')
  || gUserFields || ')';
  sSelect := coalesce(sSelect,'') || ',
    IG AS (
      SELECT CODOBIECT, PARTENER, CODLOCATIE, GEST, CODIOART, AGENT '
      || coalesce(PKG_LIST_BASE_VANZPER_CAMPURI('SELECT',NULL),'') || coalesce(sCU1,'') || '
      FROM (
        SELECT
          I1.CODOBIECT, I.PARTENER, I.CODLOCATIE, COALESCE(N.GEST,LV.GEST) GEST, COALESCE(NS.CODIOART,LV.CODIOART) CODIOART, COALESCE(I.AGENT,0) AGENT,
          I.DATADOC, I.LUNA, I.AN' || coalesce(vVal,'') || '
        FROM IESIRI I
          INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES' || coalesce(sJoinUM,'') || '
          LEFT JOIN IESLINK IL ON IL.CODIES1 = I1.CODIES1
          LEFT JOIN IESIRI1 AE1 ON AE1.CODIES1 = IL.CODLINIEAVIZ
          LEFT JOIN LIVR L ON L.CODIES = COALESCE(AE1.CODIES, I.CODIES) AND I1.TIPLINIE = ''=''
          LEFT JOIN LIVR1 L1 ON L1.CODLIVR = L.CODLIVR AND L1.CODIES1 = COALESCE(AE1.CODIES1,I1.CODIES1)
          LEFT JOIN NIRSTOC NS ON NS.CODNIRSTOC = L1.CODNIRSTOC
          LEFT JOIN NIR N ON N.CODNIR = NS.CODNIR
          LEFT JOIN LIVRVAL LV ON LV.CODLIVR1 = L1.CODLIVR1
        WHERE ' || coalesce(sWhere,'') || ' AND COALESCE(I.InfoCM,0) = 0
          AND I.TIPDOC::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''TIPDOC'')
          AND I1.TIPLINIE IN (' || coalesce(sTipLin,'') || ')
          AND I.ANULAT = 0 AND I.OPERAT = 1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || ') b_pg
      GROUP BY CODOBIECT, PARTENER, CODLOCATIE, GEST, CODIOART, AGENT )
    SELECT
      NAO.DENUMIRE, ' || coalesce(sCampUM,'') || ', NP.DEN_PART, NG.DEN_GEST, IOA.DEN_IOART, NCA.DEN_CLASEA, NAO.CODINTERN, NAO.CODEXTERN,
      PROD.DEN_PART, NCP.DEN_CLASEP,
      LSOC.DEN_LOCALIT||'' ''||(SELECT GETADRESA.wme_result FROM GETADRESA(NULL, SSOC.SECTOR, SSOC.STRADA, SSOC.NR1, SSOC.NR2, SSOC.BLOC, SSOC.SCARA, SSOC.ETAJ, SSOC.APART, SSOC.CODPOSTAL)),
      LLIV.DEN_LOCALIT||'' ''||(SELECT GETADRESA.wme_result FROM GETADRESA(NULL, SLIV.SECTOR, SLIV.STRADA, SLIV.NR1, SLIV.NR2, SLIV.BLOC, SLIV.SCARA, SLIV.ETAJ, SLIV.APART, SLIV.CODPOSTAL)),
      (Case  When AG.CODPERS=0 then AG.NUME else AG.NUME||'' ''||AG.PRENUME end), (Case  When AGI.CODPERS=0 then AGI.NUME else AGI.NUME||'' ''||AGI.PRENUME end),
      COALESCE(STOC.STOCINI,0), COALESCE(STOC.VALACHIZ,0), COALESCE(NAO.MASA,0), COALESCE(NAO.VOLUM,0)' || coalesce(sArtAtrib1,'') || coalesce(sSelAUX,'')
      || coalesce(PKG_LIST_BASE_VANZPER_CAMPURI('INSERT', 'IG'),'') || gUserAlias || '
    FROM IG
      ' || coalesce(CASE
      WHEN fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vFaraVanz') THEN 'FULL'
      ELSE 'LEFT'
      END ,'') || ' JOIN STOC ON STOC.CODOBIECT = IG.CODOBIECT AND STOC.GEST = IG.GEST AND STOC.CODIOART = IG.CODIOART
      LEFT JOIN NARTOBJ NAO ON NAO.CODOBIECT = COALESCE(IG.CODOBIECT, STOC.CODOBIECT)
      LEFT JOIN NART NA ON NA.CODARTICOL = NAO.CODARTICOL
      LEFT JOIN NUM ON NUM.CODUM = NA.UM ' || coalesce(sJoinU1,'') || coalesce(sJoinUMA,'') || coalesce(sJoinCL,'') || '
      LEFT JOIN NGEST NG ON NG.CODGEST = COALESCE(IG.GEST,STOC.GEST)
      LEFT JOIN NPART NP ON NP.CODPART = IG.PARTENER
      LEFT JOIN NPART PROD ON PROD.CODPART = NAO.CODPRODUCATOR
      LEFT JOIN IOART IOA ON IOA.CODIOART = COALESCE(IG.CODIOART,STOC.CODIOART)
      LEFT JOIN NCLASEA NCA ON NCA.CODCLASEA = NA.CLASA
      LEFT JOIN NCLASEP NCP ON NCP.CODCLASEP = NP.CODCLASA
      LEFT JOIN NPERS AG ON AG.CODPERS = IG.AGENT
      LEFT JOIN NAGENDA SSOC ON SSOC.CODPART = IG.PARTENER AND SSOC.SEDIUSOCIAL BETWEEN 4 AND 7 AND COALESCE(SSOC.INACTIV, 0) = 0
      LEFT JOIN NPERS AGI ON AGI.CODPERS = COALESCE(SSOC.CODAGENT,0)
      LEFT JOIN NLOCALIT LSOC ON LSOC.CODLOCALIT = SSOC.CODLOCALIT
      LEFT JOIN NJUDET JSOC ON JSOC.CODJUDET = LSOC.CODJUDET
      LEFT JOIN NAGENDA SLIV ON SLIV.CODAGENDA = IG.CODLOCATIE
      LEFT JOIN NLOCALIT LLIV ON LLIV.CODLOCALIT = SLIV.CODLOCALIT
      LEFT JOIN NJUDET JLIV ON JLIV.CODJUDET = LLIV.CODJUDET
      LEFT JOIN TRASEULIVR TLIV ON TLIV.CODTRASEULIVR = SLIV.CODTRASEU
      LEFT JOIN NTIPSEDII TIPSLIV ON TIPSLIV.CODTIPSEDIU = SLIV.CODTIPSEDIU
      LEFT JOIN PRETM PRETIMP ON PRETIMP.CODOBIECT = NAO.CODOBIECT AND PRETIMP.SUBUNITATEA = NG.CODSUBUNIT AND PRETIMP.IMPLICIT = 1' || gSuplJoins;
  INSERT INTO x (view_name, test) VALUES ('vanzper', coalesce(sInsert,'') || coalesce(sSelect,''));
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
IF current_setting('PKG_LIST_BASE_VANZPER.vNrCol', true)::numeric &gt; 1 AND fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vVariatie')
  THEN
    sUpdate := 'UPDATE ' || tmpName || '
      SET ';
     FOR k IN 1..current_setting('PKG_LIST_BASE_VANZPER.vNrCol', TRUE)::NUMERIC - 1 LOOP
      IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vCantitativ') THEN
        sUpdate := sUpdate || '
        VV'||To_Char(k,'fm999')||' = (CASE WHEN C'||To_Char(k,'fm999')||' = 0 THEN 0 ELSE (C'||To_Char(k+1,'fm999')||'-C'||To_Char(k,'fm999')||')/C'||To_Char(k,'fm999')||'*100 END),';
      END IF;
      IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vValoric') THEN
        sUpdate := sUpdate || '
        VV'||To_Char(k,'fm999')||' = (CASE WHEN V'||To_Char(k,'fm999')||' = 0 THEN 0 ELSE (V'||To_Char(k+1,'fm999')||'-V'||To_Char(k,'fm999')||')/V'||To_Char(k,'fm999')||'*100 END),';
      END IF;
    END LOOP;
    sUpdate := SubStr(sUpdate, 1, Length(sUpdate) - 1);
  PERFORM LIST_EXECUTE_IMMEDIATE(sUpdate, 0, 0);
  END IF;
  IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vCantCutii')
  THEN
    sUpdate := 'UPDATE ' || tmpName || '
      SET CC0 = C0/ParCutie';
    FOR k IN 1..current_setting('PKG_LIST_BASE_VANZPER.vNrCol', TRUE)::NUMERIC LOOP
      sUpdate := sUpdate ||', CC'||To_Char(k,'fm999')||' = C'||To_Char(k,'fm999')||'/ParCutie';
    END LOOP;
    sUpdate := coalesce(sUpdate,'') || '
      WHERE COALESCE(ParCutie,0) &lt;&gt; 0';
  PERFORM LIST_EXECUTE_IMMEDIATE(sUpdate, 0, 0);
  END IF;
  IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vCantPaleti')
  THEN
    sUpdate := 'UPDATE ' || tmpName || '
        SET CP0 = C0/ParPalet';
    FOR k IN 1..current_setting('PKG_LIST_BASE_VANZPER.vNrCol', TRUE)::NUMERIC LOOP
      sUpdate := sUpdate ||', CP'||To_Char(k,'fm999')||' = C'||To_Char(k,'fm999')||'/ParPalet';
    END LOOP;
    sUpdate := coalesce(sUpdate,'') || '
      WHERE COALESCE(ParPalet,0) &lt;&gt; 0';
  PERFORM LIST_EXECUTE_IMMEDIATE(sUpdate, 0, 0);
  END IF;
  IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vCantitativ') AND  current_setting('PKG_LIST_BASE_VANZPER.vTipUM', true)::numeric = 2
  THEN
    sUpdate := 'UPDATE ' || tmpName || '
        SET C0 = C0/ParCant';
    FOR k IN 1..current_setting('PKG_LIST_BASE_VANZPER.vNrCol', TRUE)::NUMERIC LOOP
      sUpdate := sUpdate ||', C'||To_Char(k,'fm999')||' = C'||To_Char(k,'fm999')||'/ParCant';
    END LOOP;
    sUpdate := coalesce(sUpdate,'') || '
      WHERE COALESCE(ParCant,0) &lt;&gt; 0';
  PERFORM LIST_EXECUTE_IMMEDIATE(sUpdate, 0, 0);
  END IF;
  IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vCantitativ') AND  current_setting('PKG_LIST_BASE_VANZPER.vTipUM', true)::numeric = 3
  THEN
    sUpdate := 'UPDATE ' || tmpName || '
        SET C0 = (Case  When MASA=0 then C0/ParCant else C0*MASA end)';
    FOR k IN 1..current_setting('PKG_LIST_BASE_VANZPER.vNrCol', TRUE)::NUMERIC LOOP
     sUpdate := sUpdate ||', C'||To_Char(k,'fm999')||' = (CASE WHEN MASA = 0 THEN C'||To_Char(k,'fm999')||'/ParCant ELSE C'||To_Char(k,'fm999')||'*MASA END)';
    END LOOP;
    sUpdate := coalesce(sUpdate,'') || '
      WHERE COALESCE(ParCant,0) &lt;&gt; 0 OR MASA &lt;&gt;0';
  PERFORM LIST_EXECUTE_IMMEDIATE(sUpdate, 0, 0);
  END IF;
  IF fnc_current_setting_boolean('PKG_LIST_BASE_VANZPER.vCantitativ') AND  current_setting('PKG_LIST_BASE_VANZPER.vTipUM', true)::numeric = 4
  THEN
    sUpdate := 'UPDATE ' || tmpName || '
        SET C0 = (Case  When VOLUM=0 then C0/ParCant else C0*VOLUM end)';
    FOR k IN 1..current_setting('PKG_LIST_BASE_VANZPER.vNrCol', TRUE)::NUMERIC LOOP
      sUpdate := sUpdate ||', C'||To_Char(k,'fm999')||' = (CASE WHEN VOLUM = 0 THEN C'||To_Char(k,'fm999')||'/ParCant ELSE C'||To_Char(k,'fm999')||'*VOLUM END)';
    END LOOP;
    sUpdate := coalesce(sUpdate,'') || '
      WHERE COALESCE(ParCant,0) &lt;&gt; 0 OR VOLUM &lt;&gt;0';
  PERFORM LIST_EXECUTE_IMMEDIATE(sUpdate, 0, 0);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_veniturirac_setjoinuri</obj_name>
  <obj_hashval>64bc2c31b4e784fc8be057552d141c5e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_veniturirac_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 03.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_VENITURIRAC.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_verif_imp_intr_processlist</obj_name>
  <obj_hashval>e4c4994efd4d7c45ff2126a9e0374407</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_verif_imp_intr_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert VARCHAR(2000);
  sSelect VARCHAR(10000);
  anLucru NUMERIC(4);
  alStart NUMERIC;
  alStop  NUMERIC;
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  gSuplCols varchar := 'intrari i, npart np, spvarhiva a';
  condHolding VARCHAR(1000);
  joinHolding VARCHAR(1000);
  subunitHolding VARCHAR(1000);
  vSubunit NUMERIC (20);
BEGIN
  --Florin 03.12.2024 - fixat 64172
  --Florin 07.10.2024 - sinc. Oracle
  --Florin 09.09.2024 - sinc. Oracle
  --Florin 30.08.2024 - fixat regexp
  --Florin 29.08.2024 - sinc. Oracle
  --Florin 27.08.2024 - sinc. Oracle
  --Florin 16.08.2024
  CALL pkg_list_struct_StartSuplCols();
  CALL pkg_list_struct_GetSuplCols(aLISTID,
                                alistver,
                                gUserFields,
                                gUserAlias,
                                gNullAlias,
                                gSuplJoins,
                                gSuplCols);
  PERFORM set_config ('PKG_LIST_BASE_VERIF_IMP_INTR.gSuplCols',gSuplCols,false);

  anLucru := getANLUCRU();
  alStart := anLucru * 12 + coalesce(current_setting('PKG_LIST_SELECTLUNA.vLunaStart', true)::numeric, 0);
  alStop  := anLucru * 12 + coalesce(current_setting('PKG_LIST_SELECTLUNA.vLunaFin', true)::numeric, 0);


  condHolding := '';
  joinHolding := '';
  subunitHolding := 'i.subunitatea';
  if (fnc_getvalconstantalucru('Holding') = '1') then
    vSubunit := GETSUBUNITATE();
      subunitHolding := ' coalesce(i.subunitatea, ns.codsubunit) ';
      joinHolding    := ' left join nsubunit ns on REGEXP_REPLACE (ns.cif,  ''[[:alpha:]]'','''',''g'') = a.cif ';
      if (vSubunit &lt;&gt; 0) then
        if (vSubunit &lt;&gt; 1) then
          condHolding := ' and '||subunitHolding||' = ' || vSubunit;
        ELSIF Coalesce(fnc_getvalconstantalucru('CumulatFirmaToateSub'),2) = '2' THEN
           condHolding := 'and '||subunitHolding||' IN (SELECT codsubunit FROM tmp_subunitdedicate)';
        end if;
      end if;
  end if;

  sInsert := 'INSERT INTO '|| tmpName ||'(
                       NAV_CodDoc, NAV_TipDoc, NrDoc, DATADOC, VALDOC, TVADOC, VALDOCEFACT, ANWME, LUNAWME,
                       ANSPV, LUNASPV, ID_DESC_WME, ID_DESC_SPV, DEN_PART, DATAINCARCARE, ANDOC,
                       LUNADOC, DATADOCSPV, CIF, STARE_CUI, TIPTRANZ, TIPTVA, LOCALITATE, TARA, DEN_SUBUNIT '||gUserFields||' )';
    sSelect := '
            select i.codintr, i.tipdoc, i.nrdoc, i.datadoc, i.valdoc,i.tvadoc,i.valdocefact,
                   i.an as anwme, i.luna as lunawme, a.an as anspv, a.luna as lunaspv,
                   i.iddescarcare as idwme, a.iddescarcare as idspv, np.den_part, a.dataincarcare ,
                   coalesce(i.an, a.an),
                   coalesce(i.luna, a.luna),
                   a.DATADOCSPV,
                   coalesce(a.cif_partener, npcfintr.codfiscal),
                   case when NPA.CONTRIBUABIL = 0 then ''CUI neplatitor TVA''
                        when NPA.CONTRIBUABIL = 1 then ''CUI platitor TVA''
                        when NPA.CONTRIBUABIL = -1 then ''CUI incorect''
                        when NPA.CONTRIBUABIL = -2 then ''CUI radiat/inactiv''
                        else null
                        end,
                      case i.tiptranzactie
                        when  1 then ''tranzactie interna''
                        when  2 then ''achizitie intracomunitara''
                        when  3 then ''import servicii''
                        when  4 then ''factura de transport taxabila pe DVI''
                        when  5 then ''factura de decontare''
                        when  6 then ''monetar''
                        when  7 then ''Borderou de achizitii''
                        when  8 then ''Fila carnet producator''
                        when  9 then ''Contract achizitii''
                        when 10 then ''Alte documente''
                        when 11 then ''Arenda''
                        else null
                   end,
                   case i.tiptva
                        when 1 then ''taxare normala''
                        when 2 then ''taxare inversa''
                        when 3 then ''tranzactie triunghiulara''
                        when 4 then ''taxare normala Prorata''
                        when 6 then ''regim special de scutire art 311 CF''
                        when 7 then ''regim special de scutire art 312 CF''
                        when 8 then ''achizitii UE de bunuri cu instalare/montaj''
                        when 9 then ''regim special pt. agricultori (art.315)''
                        else null
                   end, loc.den_localit, t.den_tara, nsu.den_subunit '||gUserAlias||
            ' from intrari i
              full join spvarhiva a on a.iddescarcare = i.iddescarcare::varchar
              left join (  SELECT
                                  distinct FIRST_VALUE(ncfi.codpart)
                                           OVER(PARTITION BY ncfi.CODFISCAL
                                                          order by  np.blocat nulls first, np.inactiv nulls first, ncfi.principal desc  nulls last
                                                          ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
                                           ) as codpart,
                                           ncfi.CODFISCAL
                            FROM NPARTCODFISC ncfi
                            join npart np on np.codpart = ncfi.codpart ) ncf on upper(trim(ncf.codfiscal)) = upper(trim(a.cif_partener))
              left join npart np on np.codpart = coalesce(i.partener, ncf.codpart)
              left join NPARTCODFISC npcfintr on npcfintr.cod_codfiscal = i.codfiscal
              left join nagenda nag on nag.codagenda = i.codlocatie
              left join nlocalit loc on loc.codlocalit = nag.codlocalit
               left join ntari t on t.codtara = loc.codtara '
              ||joinHolding||
              ' left join nsubunit nsu on nsu.codsubunit = ' || subunitHolding ||
              ' LEFT JOIN (select distinct npi.cui, first_value(npi.contribuabil) over (partition by npi.cui order by npi.contribuabil ) as contribuabil from  NPART_ANAF npi) NPA ON NPA.CUI::varchar = REGEXP_REPLACE (coalesce(a.cif_partener, npcfintr.codfiscal), ''[[:alpha:]]'','''',''g'')'
              ||gSuplJoins||
              ' where (a.tipdoc = 1 or a.tipdoc is null)
               and (i.tipdoc in (1, 9) or i.tipdoc is null)'
               || condHolding ||
               ' and ((i.an *12 + i.luna BETWEEN '||alStart||' AND '||alStop||')
               or (a.an *12 + a.luna BETWEEN '||alStart||' AND '||alStop||')) ';
    PERFORM LIST_EXECUTE_IMMEDIATE(COALESCE(sInsert, '') || COALESCE(sSelect, ''), aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_config_clientselect</obj_name>
  <obj_hashval>5bb283e6b559020c670cbd154537fb6d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_config_clientselect(INOUT wme_result numeric, INOUT tmptable character varying, INOUT visible_cols character varying, INOUT sum_cols character varying, INOUT group_cols character varying, INOUT where_cols character varying, INOUT order_cols character varying, INOUT sold_cols character varying, INOUT resetsold_cols character varying, INOUT calc_cols character varying, INOUT sum_calc character varying, INOUT sold_calc character varying, INOUT fara_total character varying, INOUT viewname character varying, INOUT susername character varying, INOUT bcentralizat boolean, INOUT finterval character varying, INOUT stabla character varying, INOUT groupsort character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  xTable      varchar;
  wTable      varchar;
  strSelect   varchar;
  visibleCols varchar;
  pTipSQL     varchar;
begin
  -- Stef   24.03.2022 - CREATE TEMPORARY (scosGLOBAL fiindca e obsolete si apare/incurca in loguri de BD)
  -- Stef   21.03.2022
  -- Bogdan 14.02.2022 53069 : PG - Lista balanta stocurilor: grupare fara afisare linie de titlu si subtotal
  -- Adina  13.05.2021 - add linia 22 si scos linia 23
  -- Stef   27.07.2020
  xTable    := tmptable;
  wTable    := 'W' || tmptable;
  strSelect := 'SELECT null ';

  IF sTabla = 'GROUPBEFORE' THEN
     --53069
     SELECT cpt.tmptable INTO xTable FROM pkg_list_config_proceseazatotal( xTable, sum_cols, group_cols, sUserName) cpt;
    -- end 53069
  END IF;
  IF (   sTabla &lt;&gt; '?')  and (   sTabla &lt;&gt; 'GROUPBEFORE') THEN
    --insert into X(view_name) values('1'); --commit;
    EXECUTE 'drop table if exists ' || stabla;
    -- PERFORM pkg_list_config_TryToDropTable( sTabla);
    EXECUTE ' CREATE TABLE    ' || sTabla || ' AS SELECT * FROM ' || TMPTABLE;
    EXECUTE ' GRANT SELECT ON ' || sTabla || ' TO ' || sUserName;
  END IF;

  visibleCols := visible_cols;
  IF  ( COALESCE( char_length( TRIM(both ' ' from  group_cols)), 0) &gt;  0)
  AND ( COALESCE( char_length( TRIM(both ' ' from  sum_cols  )), 0) &gt;= 0)
  AND ( COALESCE( char_length( TRIM(both ' ' from  sold_cols )), 0) =  0)
  THEN
    pTipSql := 'CU GRUPARE SI SUBTOTALURI';
    --insert into X(view_name, test) values('2', pTipSql::text);
    strSelect := pkg_list_config_GrupSumeSelect(xtable, visible_cols, sum_cols, group_cols, where_cols, order_cols, calc_cols, sum_calc, fara_total, bCentralizat, fInterval, groupsort);
  ELSIF( COALESCE( char_length( TRIM(both ' ' from  group_cols)), 0) = 0)
  AND  ( COALESCE( char_length( TRIM(both ' ' from  sum_cols  )), 0) &gt; 0)
  AND  ( COALESCE( char_length( TRIM(both ' ' from  sold_cols )), 0) = 0)
  THEN
    pTipSql := 'CU TOTAL GENERAL SI FARA GRUPARE';
    --insert into X(view_name, test) values('3', pTipSql::text);
    strSelect := pkg_list_config_SumeSelect( xTable, visible_cols, sum_cols, where_cols, order_cols, calc_cols, sum_calc, fara_total, bCentralizat, fInterval);
  ELSIF( COALESCE( char_length( TRIM(both ' ' from  group_cols)), 0) = 0)
  AND  ( COALESCE( char_length( TRIM(both ' ' from  sum_cols  )), 0)&gt;= 0)
  AND  ( COALESCE( char_length( TRIM(both ' ' from  sold_cols )), 0) &gt; 0)
  THEN
    pTipSql   := 'CU COLOANE TIP SOLD SI TOTAL GENERAL';
    --insert into X(view_name, test) values('4', pTipSql::text);
--    insert into X(view_name,test) values('400',
--   'pkg_list_config_SumeSoldSelect ('''||
--      coalesce(xTable,'')||''','''||coalesce(visible_cols,'')||''','''||coalesce(sum_cols,'')||''','''||
--      coalesce(where_cols,'')||''','''||coalesce(order_cols,'')||''','''||
--      coalesce(sold_cols,'')||''','''||coalesce(resetsold_cols,'')||''','''||coalesce(calc_cols,'')||''','''||
--      coalesce(sum_calc,'')||''','''||coalesce(sold_calc,'')||''','||bCentralizat::varchar||','''||coalesce(fInterval,'')||''')');
--   return;
    strSelect := pkg_list_config_SumeSoldSelect (xTable ,visible_cols ,sum_cols ,where_cols,order_cols ,sold_cols,resetsold_cols,calc_cols , sum_calc, sold_calc, bCentralizat, fInterval);
  ELSIF( COALESCE( char_length( TRIM(both ' ' from  group_cols)), 0) &gt; 0)
  AND  ( COALESCE( char_length( TRIM(both ' ' from  sum_cols  )), 0)&gt;= 0)
  AND  ( COALESCE( char_length( TRIM(both ' ' from  sold_cols )), 0) &gt; 0)
  THEN
    pTipSql   := 'CU COLOANE TIP SOLD SI CU SUBTOTALURI DE GRUP';
    --insert into X(view_name, test) values('5', pTipSql::text);
--    insert into X(view_name,test) values('500',
--      'pkg_list_config_GrupSumeSoldSelect (('''||
--      coalesce(xTable,'')||''','''||coalesce(visible_cols,'')||''','''||coalesce( sum_cols,'')||''','''||coalesce( group_cols,'')||''','''||coalesce( where_cols,'')||''','''||
--      coalesce(order_cols,'')||''','''||coalesce(sold_cols,'')||''','''||coalesce(resetsold_cols,'')||''','''||coalesce(calc_cols,'')||''','''||coalesce(sum_calc,'')||''','''||
--      coalesce(sold_calc,'')||''','||bCentralizat::varchar||','''||coalesce(fInterval,'')||''','''||coalesce(groupsort,'')||''')');
--    return;
    strSelect := pkg_list_config_GrupSumeSoldSelect (xTable,visible_cols, sum_cols, group_cols, where_cols, order_cols, sold_cols, resetsold_cols, calc_cols , sum_calc, sold_calc, bCentralizat,fInterval,groupsort);
  ELSIF( COALESCE( char_length( TRIM(both ' ' from  group_cols)), 0) = 0)
  AND  ( COALESCE( char_length( TRIM(both ' ' from  sum_cols  )), 0) = 0)
  AND  ( COALESCE( char_length( TRIM(both ' ' from  sold_cols )), 0) = 0)
  THEN
    pTipSql   := 'SELECT SIMPLU (VEZI NOMENCLATOARE)';
    --insert into X(view_name, test) values('6', pTipSql::text);
    strSelect := pkg_list_config_GetSelectSimplu(xTable,visible_cols,where_cols,order_cols,calc_cols,sum_calc,bCentralizat,fInterval);
  ELSE
    --insert into X(view_name, Test) values('0', visible_cols);
    pTipSql := '--DACA KIAR NU INTRU PE NICI O RAMURA DE MAI SUS....';
    select pkg_list_config_FormatNullSelect.WME_RESULT into strSelect from pkg_list_config_FormatNullSelect( null, xTable, visible_cols);
  END IF;

  IF (   sTabla = '?')  or (   sTabla = 'GROUPBEFORE') THEN
    PERFORM pkg_list_config_TryToDropTMP( WTable);
    strSelect := ' CREATE TEMPORARY TABLE ' || WTable || ' ON COMMIT PRESERVE ROWS AS ' || coalesce(strSelect, '');
    --insert into X(view_name, Test) values('7', strSelect); --commit;
    --EXECUTE strSelect;
    --strSelect := ' update  ' || WTable || ' SET GLOBALID = 1000000000 where NRCRT = 1000000000';
    EXECUTE strSelect;
    EXECUTE ' GRANT SELECT ON ' || WTable || ' TO ' || sUserName;
  END IF;
  WME_Result :=  0;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_config_get_id_footer</obj_name>
  <obj_hashval>de14d602e64926d144e2781ea1956337</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_config_get_id_footer()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  return 999999999;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_config_grupsumeselect</obj_name>
  <obj_hashval>8553e48341f2ea0b569471b5b29b1c7e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_config_grupsumeselect(tmptable character varying, visible_cols character varying, sum_cols character varying, group_cols character varying, where_clause character varying, order_cols character varying, calc_cols character varying, sum_calc character varying, fara_total character varying, bcentralizat boolean, finterval character varying, groupsort character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_COLS RECORD;
  strSelect        varchar := 'SELECT null';
  strSelectAll     varchar := 'SELECT ';
  strSelectHeader  varchar := 'SELECT ';
  strSelectFooter  varchar := 'SELECT ';
  strSelectDetalii varchar := 'SELECT ';
  strSelectSum     varchar := 'SELECT ';
  strWhereClause   varchar := ' WHERE NOT (';
  nrCols           integer;
  i                integer;
  sNVL_header      varchar:='';
  sNVL_footer      varchar:='';
  visibleCols      varchar:='';
  sWhere           varchar:='';
  sCase            varchar:='';
  sColoaneCalc     varchar:='';
  sCalcCols        varchar:='';
  sSumCalcCols     varchar:='';
  sSumHeaderFooter varchar:='';
  nrCalcCols       numeric;
  allCols          varchar:='';
  isCol            BOOLEAN;
  desc_            BOOLEAN;
  Sss              varchar:='';
  sType            varchar;
begin
  --Florin 14.12.2021 - fixat 52284/40170
  -- stef 22.07.2020
  visibleCols := Visible_Cols;
  FOR V_COLS IN (SELECT COLUMN_NAME::varchar FROM information_schema.columns WHERE TABLE_NAME = lower( tmptable)) LOOP
    strSelectAll := strSelectAll || v_cols.column_name || ',';
    strSelectDetalii := strSelectDetalii || v_cols.column_name || ',';
    allCols := allcols || v_cols.column_name || ',';
    SELECT
    PKG_LIST_CONFIG_CautaColoana.WME_RESULT, PKG_LIST_CONFIG_CautaColoana.Desc_
    into isCol,desc_
    FROM PKG_LIST_CONFIG_CautaColoana(NULL, UPPER( v_cols.column_name), UPPER( group_cols), desc_);
    IF isCol THEN
      select
        PKG_LIST_CONFIG_GetNVLClause.sNVL_header,
        PKG_LIST_CONFIG_GetNVLClause.sNVL_footer,
        PKG_LIST_CONFIG_GetNVLClause.sWhere,
        PKG_LIST_CONFIG_GetNVLClause.sType
        into sNVL_header, sNVL_footer, sWhere, sType
      from PKG_LIST_CONFIG_GetNVLClause( tmptable, v_cols.column_name, sNVL_header, sNVL_footer, sWhere, sType, desc_);
      IF desc_ THEN
        strSelectHeader := strSelectHeader || sNVL_Footer || ' ' || v_cols.column_name || ',';
        strSelectFooter := strSelectFooter || sNVL_Header || ' ' || v_cols.column_name || ',';
      ELSE
        strSelectHeader := strSelectHeader || sNVL_header || ' ' || v_cols.column_name || ',';
        strSelectFooter := strSelectFooter || sNVL_footer || ' ' || v_cols.column_name || ',';
      END IF;
      strSelectSum := strSelectSum || v_cols.column_name || ',';
      strWhereClause := strWhereClause || ' ' || v_cols.column_name || sWhere;
    ELSIF
      (SELECT PKG_LIST_CONFIG_CautaColoana.WME_RESULT FROM PKG_LIST_CONFIG_CautaColoana(NULL, UPPER( v_cols.column_name), UPPER( sum_cols), desc_))
    THEN
      strSelectHeader := strSelectHeader || UPPER( v_cols.column_name) || ',';
      strSelectFooter := strSelectFooter || UPPER( v_cols.column_name) || ',';
      IF  length( trim(both ' ' from  fara_total)) &gt; 0
      THEN  strSelectSum := strSelectSum || 'SUM(CASE WHEN ' || fara_total || ' THEN ' || v_cols.column_name || ' ELSE 0 END) ' || v_cols.column_name || ',';
      ELSE  strSelectSum := strSelectSum || 'SUM(' || v_cols.column_name || ') ' || v_cols.column_name || ',';
      END IF;
    ELSE
      select (pkg_list_config_GET_COL_TYPE.wme_result) into sType from pkg_list_config_GET_COL_TYPE(null, v_cols.column_name,tmptable);
      strSelectHeader := strSelectHeader || 'NULL::'||sType||',';
      strSelectFooter := strSelectFooter || 'NULL::'||sType||',';
      strSelectSum := strSelectSum || 'NULL::'||sType||',';
    END IF;
  END LOOP;
 --insert into X(view_name, Test) values('1 strSelectDetalii1', strSelectDetalii);
 --insert into X(view_name, Test) values('1 strSelectAll', strSelectAll);
  allcols := substr( allCols, 1, length( allCols) - 1);
  strSelectAll := substr( strSelectAll, 1, length( strSelectAll) - 1) || ' FROM ' || UPPER( tmptable);
  IF  length( trim(both ' ' from  where_clause)) &gt; 0  THEN  strSelectAll := strSelectAll || ' WHERE ' || where_clause;END IF;
  strSelectAll := strSelectAll || ' ORDER BY ' || order_cols;

  SELECT
  PKG_LIST_CONFIG_getColoanefromExpresii.WME_RESULT,
  PKG_LIST_CONFIG_getColoanefromExpresii.calc_cols,
  PKG_LIST_CONFIG_getColoanefromExpresii.nrcols
  into sColoaneCalc,calc_cols, nrCalcCols
  FROM PKG_LIST_CONFIG_getColoanefromExpresii(NULL, calc_cols, nrCalcCols);

  sCalcCols := calc_cols;
  sSumCalcCols := sum_calc;
  IF  Length( calc_cols) &gt; 0 THEN
    select
      PKG_LIST_CONFIG_PrelucreazaColCalc.pcoloanecalc,
      PKG_LIST_CONFIG_PrelucreazaColCalc.psumcalc,
      PKG_LIST_CONFIG_PrelucreazaColCalc.psumheaderfooter
    into sCalcCols, sSumCalcCols, sSumHeaderFooter
    from PKG_LIST_CONFIG_PrelucreazaColCalc( sCalcCols, sSumCalcCols, sSumHeaderFooter, fara_total);

    strSelectDetalii := strSelectDetalii || sCalcCols;
    strSelectHeader := strSelectHeader || sSumHeaderFooter;
    strSelectFooter := strSelectFooter || sSumHeaderFooter;
    strSelectSum := strSelectSum || sSumCalcCols;
  END IF;
 --insert into X(view_name, Test) values('1 strSelectDetalii2', strSelectDetalii);
  strSelectDetalii := strSelectDetalii || '(ROW_number() over(order by ' || order_cols || '))::numeric  AS NRCRT,';
 --insert into X(view_name, Test) values('1 strSelectDetalii3', strSelectDetalii);
  strSelectHeader := strSelectHeader || ' NRCRT ';
  strSelectFooter := strSelectFooter || ' NRCRT ';
  IF  length( calc_cols) &gt; 0 THEN  allCols := allCols || ',' || sColoaneCalc;END IF;
  allCols := allCols || ',NRCRT';


  SELECT
  pkg_list_Config_GetRowNumClause.WME_Result,
  pkg_list_Config_GetRowNumClause.NrCols
  into Sss, NrCols
  from pkg_list_Config_GetRowNumClause( null, group_cols, nrCols);
  strSelectDetalii := strSelectDetalii || Sss;
 --insert into X(view_name, Test) values('1 strSelectDetalii4', strSelectDetalii);

  --insert into X(view_name, Test) values('1nrCols', To_char(nrCols, '9999'));
  --insert into X(view_name, Test) values('1Sss', Sss);
  for i IN 1..nrCols LOOP
    strSelectDetalii := strSelectDetalii||',NULL::numeric NRG_'  ||i;
    strSelectHeader  := strSelectHeader ||',NULL::numeric NRCRT_'||i;
    strSelectFooter  := strSelectFooter ||',NULL::numeric NRCRT_'||i;
    allCols          := allCols         ||','||'NRG_'||i||','||'NRCRT_'||i;
  END LOOP;
  --insert into X(view_name, Test) values('1 strSelectDetalii5', strSelectDetalii);
  --insert into X(view_name, Test) values('1 strSelectHeader', strSelectHeader);
  --insert into X(view_name, Test) values('1 strSelectFooter', strSelectFooter);

  SELECT pkg_list_Config_GetDenseRankClause.WME_RESULT into Sss FROM pkg_list_Config_GetDenseRankClause(NULL, group_cols, nrcols);
  strSelectHeader := strSelectHeader || ',' || Sss;
 --insert into X(view_name, Test) values('2 SSS1', SSS);
  strSelectHeader := strSelectHeader || ' FROM (' || strSelectSum || '-(200 + GROUPING(' || replace( group_cols, ' DESC', '') || '))::numeric NRCRT FROM ' || tmptable;

  SELECT pkg_list_Config_GetDenseRankClause.WME_RESULT into Sss FROM pkg_list_Config_GetDenseRankClause(NULL, group_cols, nrcols);
  strSelectFooter := strSelectFooter || ',' || Sss;
 --insert into X(view_name, Test) values('2 SSS2', SSS);
  strSelectFooter := strSelectFooter || ' FROM (' || strSelectSum || '(999999999 + GROUPING(' || replace( group_cols, ' DESC', '') || '))::numeric NRCRT FROM ' || tmptable;

--insert into X(view_name, Test) values('2 nrCols', To_char(nrCols, '9999'));

 --insert into X(view_name, Test) values('00',strSelectSum || '(999999999 + GROUPING(' || replace( group_cols, ' DESC', '') || '))::numeric NRCRT FROM ' || tmptable);
  IF  length( trim(both ' ' from  where_clause)) &gt; 0 THEN
    strSelectHeader := strSelectHeader || ' WHERE ' || where_clause;
    strSelectFooter := strSelectFooter || ' WHERE ' || where_clause;
  END IF;
 --insert into X(view_name, Test) values('3 strSelectHeader', strSelectHeader);
 --insert into X(view_name, Test) values('3 strSelectFooter', strSelectFooter);
 --insert into X(view_name, Test) values('3xgroup_cols', group_cols);
  strSelectHeader := strSelectHeader || ' GROUP BY ROLLUP(' || replace( group_cols, ' DESC', '') || ')) PG_Head';
  strSelectFooter := strSelectFooter || ' GROUP BY ROLLUP(' || replace( group_cols, ' DESC', '') || ')) PG_Foot';
  strSelectDetalii := strSelectDetalii || ' FROM(' || strSelectAll || ') PG_Det ';
  strWhereClause := substr( strWhereClause, 1, length( strWhereClause) - length( 'AND'));
  strWhereClause := strWhereClause || ')';
  allCols := allCols || ',pkg_list_Config_GET_GROUP_ID(NRCRT)::numeric AS NRSKIP ';

 --insert into X(view_name, Test) values('4 strSelectHeader', strSelectHeader);
 --insert into X(view_name, Test) values('4 strSelectFooter', strSelectFooter);
 --insert into X(view_name, Test) values('4 strSelectDetalii', strSelectDetalii);
 --insert into X(view_name, Test) values('4 allCols', allCols);

 visibleCols := visibleCols || ',NRSKIP';
  strSelect := 'SELECT ' || allCols || '  FROM ( ';
  strSelect := strSelect || strSelectDetalii || ' UNION ALL ';
  strSelect := strSelect || strSelectHeader  || ' UNION ALL ';
  strSelect := strSelect || strSelectFooter  || ' ) PG_All ' || strWhereClause || ' ORDER BY ' || groupsort;
  strSelect := 'SELECT SQL.*, ROW_number() over() AS GLOBALID FROM (' || STRSELECT || ') sql ';
  IF bCentralizat THEN
    strSelect := 'SELECT * FROM  (' || strSelect || ') PG_Cen WHERE  (NRCRT &gt;= 999999999 OR NRCRT &lt;= -200)  ';
    IF  length( trim(both ' ' from  fInterval)) &gt; 0 THEN  strSelect := strSelect || fInterval; END IF;
  END IF;
  --insert into X(view_name, Test) values('strSelect', strSelect);
  RETURN strSelect;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_config_grupsumesoldselect</obj_name>
  <obj_hashval>b113eb4c1c2a3c3cfdd47779222beeb1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_config_grupsumesoldselect(tmptable character varying, visible_cols character varying, sum_cols character varying, group_cols character varying, where_clause character varying, order_cols character varying, sold_cols character varying, resetsold_cols character varying, calc_cols character varying, sum_calc character varying, sold_calc character varying, bcentralizat boolean, finterval character varying, groupsort character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE V_COLS RECORD;
  strSelect        varchar := 'SELECT null';
  strSelectAll     varchar := 'SELECT ';
  strSelectHeader  varchar := 'SELECT ';
  strSelectFooter  varchar := 'SELECT ';
  strSelectDetalii varchar := 'SELECT ';
  strSelectSum     varchar := 'SELECT ';
  strWhereClause   varchar := ' WHERE NOT (';
  nrCols           integer;
  i                integer;
  sNVL_header      varchar;
  sNVL_footer      varchar;
  sWhere           varchar;
  strSoldClause    varchar;
  sColoaneCalc     varchar;
  nrCalcCols       integer;
  allCols          varchar := '';
  isCol            BOOLEAN;
  desc_            BOOLEAN;
  sSumCols         varchar;
  sCalcCols        varchar;
  sSumCalcCols     varchar;
  sSumHeaderFooter varchar;
  fara_total       varchar;
  sOrdSold         varchar;
  auxSelect        varchar := '';
  sType            varchar := '';
begin
  --Florin 11.11.2021 - sinc. Oracle (47805)
  --Stef 27.07.20120
  sSumCols    := Coalesce(sum_cols,'');
  sSumCols    := REPLACE(sum_cols, ' ' ,'' );
  sSumCols    := REPLACE(sSumCols, ',,',',');
  sSumCols    := ',' || Lower(sSumCols) || ',';

  FOR V_COLS IN (
    SELECT COLUMN_NAME::varchar COLUMN_NAME
    FROM information_schema.columns
    WHERE TABLE_NAME = lower(tmptable)
  ) LOOP
    strSelectAll     := strSelectAll     || v_cols.column_name || ',';
    strSelectDetalii := strSelectDetalii || v_cols.column_name || ',';
    allCols          := allCols          || v_cols.column_name || ',';

    SELECT
      PKG_LIST_CONFIG_CautaColoana.WME_RESULT,
      PKG_LIST_CONFIG_CautaColoana.Desc_
    INTO isCol,desc_
    FROM PKG_LIST_CONFIG_CautaColoana(NULL,v_cols.column_name,Lower(group_cols),desc_);

    IF isCol THEN
      SELECT
        PKG_LIST_CONFIG_GetNVLClause.sNVL_header,
        PKG_LIST_CONFIG_GetNVLClause.sNVL_footer,
        PKG_LIST_CONFIG_GetNVLClause.sWhere,
        PKG_LIST_CONFIG_GetNVLClause.sType,
        PKG_LIST_CONFIG_GetNVLClause.desc_
      INTO sNVL_header, sNVL_footer, sWhere, sType, desc_
      FROM PKG_LIST_CONFIG_GetNVLClause( tmptable, v_cols.column_name, sNVL_header, sNVL_footer, sWhere, sType, desc_);

      IF desc_ THEN
        strSelectHeader := strSelectHeader || sNVL_Footer || ' ' ||v_cols.column_name || ',';
        strSelectFooter := strSelectFooter || sNVL_Header || ' ' ||v_cols.column_name || ',';
      ELSE
        strSelectHeader := strSelectHeader || sNVL_header || ' ' ||v_cols.column_name || ',';
        strSelectFooter := strSelectFooter || sNVL_footer || ' ' ||v_cols.column_name || ',';
      END IF;
      strSelectSum   := strSelectSum   ||        v_cols.column_name || ',';
      strWhereClause := strWhereClause || ' ' || v_cols.column_name ||sWhere;
    ELSIF (strpos(sSumCols, ',' || v_cols.column_name || ',') &gt; 0) THEN
      strSelectHeader := strSelectHeader ||           v_cols.column_name || ',';
      strSelectFooter := strSelectFooter ||           v_cols.column_name || ',';
      strSelectSum    := strSelectSum    || 'SUM(' || v_cols.column_name || ') ' ||v_cols.column_name || ',';
    ELSE
      strSelectHeader := strSelectHeader || 'NULL,';
      strSelectFooter := strSelectFooter || 'NULL,';
      strSelectSum    := strSelectSum    || 'NULL,';
    END IF;
  END LOOP;
  allCols      := SUBSTR(allCols,      1, LENGTH(allCols)      - 1);
  strSelectAll := SUBSTR(strSelectAll, 1, LENGTH(strSelectAll) - 1) ||' FROM ' || tmptable;
  IF COALESCE(LENGTH(TRIM(where_clause)),0) &gt; 0 THEN
    strSelectAll := strSelectAll || ' WHERE ' || where_clause;
  END IF;
  IF COALESCE(LENGTH(TRIM(order_cols)),0) &gt; 0 THEN
    strSelectAll := strSelectAll || ' ORDER BY ' || order_cols;
  END IF;

  SELECT
    PKG_LIST_CONFIG_getColoanefromExpresii.WME_RESULT,
    PKG_LIST_CONFIG_getColoanefromExpresii.calc_cols
  INTO sColoaneCalc, calc_cols
  FROM PKG_LIST_CONFIG_getColoanefromExpresii(NULL,calc_cols,nrCalcCols);

  sCalcCols    := calc_cols;
  sSumCalcCols := sum_calc;
  fara_total   := '';
  IF Length(calc_cols) &gt; 0 THEN
    SELECT
      PKG_LIST_CONFIG_PrelucreazaColCalc.pcoloanecalc,
      PKG_LIST_CONFIG_PrelucreazaColCalc.psumcalc,
      PKG_LIST_CONFIG_PrelucreazaColCalc.psumheaderfooter
    INTO sCalcCols,sSumCalcCols,sSumHeaderFooter
    FROM PKG_LIST_CONFIG_PrelucreazaColCalc(sCalcCols,sSumCalcCols,sSumHeaderFooter,fara_total);
    strSelectDetalii := strSelectDetalii || sCalcCols;
    strSelectHeader  := strSelectHeader  || sSumHeaderFooter;
    strSelectFooter  := strSelectFooter  || sSumHeaderFooter;
    strSelectSum     := strSelectSum     || sSumCalcCols;
  END IF;
  IF COALESCE(LENGTH(TRIM(order_cols)),0) &gt; 0 THEN
    strSelectDetalii := strSelectDetalii || 'ROW_number() over(order by ' ||order_cols || ') AS NRCRT,';
  end if;
  strSelectHeader  := strSelectHeader  || 'NRCRT ';
  strSelectFooter  := strSelectFooter  || 'NRCRT ';
  IF length(calc_cols) &gt; 0 then
    allCols := allCols || ',' || sColoaneCalc;
  END IF;
  allCols := allCols || ',NRCRT';

  SELECT
    pkg_list_Config_GetRowNumClause.WME_RESULT,
    pkg_list_Config_GetRowNumClause.nrcols
  INTO auxSelect, nrCols
  FROM pkg_list_Config_GetRowNumClause(null, group_cols, nrCols);
  strSelectDetalii := strSelectDetalii ||auxSelect;

  for i IN 1..nrCols LOOP
    strSelectDetalii := strSelectDetalii||',NULL::numeric NRG_'||i;
    strSelectHeader  := strSelectHeader ||',NULL::numeric NRCRT_'||i;
    strSelectFooter  := strSelectFooter ||',NULL::numeric NRCRT_'||i;
    allCols          := allCols         ||','||'NRG_'||i||','||'NRCRT_'||i;
  END LOOP;

  SELECT
    pkg_list_Config_GetDenseRankClause.WME_RESULT,
    pkg_list_Config_GetDenseRankClause.NrCols
  INTO auxSelect,nrcols
  FROM pkg_list_Config_GetDenseRankClause(NULL,group_cols,nrcols);
  strSelectHeader  := strSelectHeader || ',' ||auxSelect;

  strSelectHeader := strSelectHeader || ' FROM (' || strSelectSum || '-(200 + GROUPING(' || replace( group_cols, ' DESC', '') || '))::numeric NRCRT FROM ' || tmptable;
  IF COALESCE(LENGTH(TRIM(where_clause)),0) &gt; 0 THEN
    strSelectHeader := strSelectHeader || ' WHERE ' || where_clause;
  END IF;
  strSelectHeader := strSelectHeader || ' GROUP BY ROLLUP(' || replace(group_cols, ' DESC', '') || ')) PG_Head';

  SELECT
    pkg_list_Config_GetDenseRankClause.WME_RESULT,
    pkg_list_Config_GetDenseRankClause.NrCols
  INTO auxSelect,nrcols
  FROM pkg_list_Config_GetDenseRankClause(NULL,group_cols,nrcols);
  strSelectFooter := strSelectFooter || ',' ||auxSelect;
  strSelectFooter := strSelectFooter || ' FROM (' || strSelectSum || '(999999999 + GROUPING(' || replace( group_cols, ' DESC', '') || '))::numeric NRCRT FROM ' || tmptable;

  IF COALESCE(LENGTH(TRIM(where_clause)),0) &gt; 0 THEN
    strSelectFooter := strSelectFooter || ' WHERE ' || where_clause;
  END IF;
  strSelectFooter  := strSelectFooter || ' GROUP BY ROLLUP(' ||replace(group_cols, ' DESC', '') || ')) PG_Foot';
  strSelectDetalii := strSelectDetalii || ' FROM(' || strSelectAll || ') PG_Det';
  strWhereClause   := substr(strWhereClause,1,length(strWhereClause) - length('AND'));
  strWhereClause   := strWhereClause || ')';
  sOrdSold         := group_cols || ',NRCRT';

  select pkg_list_Config_GetSoldSumClause.WME_RESULT into strSoldClause from pkg_list_Config_GetSoldSumClause(null, sold_cols,resetsold_cols,sOrdSold,nrCols,True);
  strSoldClause    := substr(strSoldClause, 1, length(strSoldClause) - 1);
  strSelect        := 'SELECT ' || allCols || ',' || strSoldClause || '   FROM (    ';
  strSelect        := strSelect || strSelectDetalii || ' UNION ALL ';
  strSelect        := strSelect || strSelectHeader  || ' UNION ALL ';
  strSelect        := strSelect || strSelectFooter  || ') PG_All' || strWhereClause || ' ORDER BY ' || groupsort;
  strSelect        := 'SELECT SQL.*, ROW_number() over() AS GLOBALID FROM (' ||STRSELECT || ') sql ';
  IF bCentralizat THEN
    strSelect := 'SELECT * FROM  (' || strSelect || ') sql WHERE (NRCRT &gt;= 999999999 OR NRCRT &lt;= -200) ';
    IF COALESCE(LENGTH(TRIM(fInterval)),0) &gt; 0 THEN
      strSelect := strSelect || fInterval;
    END IF;
  END IF;

  --insert into X(view_name,test) values('000001', strSelect::text);
  RETURN strSelect;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_config_sumeselect</obj_name>
  <obj_hashval>c610196f86119116e93dfc7f80904563</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_config_sumeselect(tmptable character varying, visible_cols character varying, sum_cols character varying, where_clause character varying, order_cols character varying, calc_cols character varying, sum_calc character varying, fara_total character varying, bcentralizat boolean, finterval character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_COLS           RECORD;
  strSelect        varchar := 'SELECT null ';
  strSelectAll     varchar := 'SELECT ';
  strSelectHeader  varchar := 'SELECT ';
  strSelectFooter  varchar := 'SELECT ';
  strSelectDetalii varchar := 'SELECT ';
  strSelectSum     varchar := 'SELECT ';
  strWhereClause   varchar := 'WHERE NOT (';
  sNVL_header      varchar := '';
  sNVL_footer      varchar := '';
  visibleCols      varchar := '';
  sWhere           varchar := '';
  sColoaneCalc     varchar := '';
  nrCalcCols       numeric;
  allCols          varchar := '';
  sCalcCols        varchar := '';
  sSumCalcCols     varchar := '';
  sSumHeaderFooter varchar := '';
  desc_            boolean;
  sType            varchar;
  sAuxCondHF       varchar := ' WHERE ';
begin
  --Florin 14.12.2021 - fixat 52284/40170
  --Adina 21.06.2021 - sinc.Oracle (add sAuxCondHF -tichet 50590)
  -- STEF 04.08.2020 Adaugat AS pentru cuvinte rezervate
  visibleCols := visible_cols;
  FOR V_COLS IN (SELECT COLUMN_NAME::varchar FROM information_schema.columns WHERE TABLE_NAME = lower( tmptable)) LOOP
    strSelectAll     := strSelectAll || v_cols.column_name || ',';
    strSelectDetalii := strSelectDetalii || v_cols.column_name || ',';
    allCols          := allCols || v_cols.column_name || ',';
    IF (SELECT PKG_LIST_CONFIG_CautaColoana.WME_RESULT FROM PKG_LIST_CONFIG_CautaColoana(NULL, Upper( v_cols.column_name), upper( sum_cols), desc_))
    THEN
      strSelectHeader := strSelectHeader || v_cols.column_name || ',';
      strSelectFooter := strSelectFooter || v_cols.column_name || ',';
      strSelectSum := strSelectSum || 'SUM(' || v_cols.column_name || ') AS ' || v_cols.column_name || ',';
    ELSE
      select
      PKG_LIST_CONFIG_GetNVLClause.sNVL_header,
      PKG_LIST_CONFIG_GetNVLClause.sNVL_footer,
      PKG_LIST_CONFIG_GetNVLClause.sWhere,
      PKG_LIST_CONFIG_GetNVLClause.sType
      into sNVL_header, sNVL_footer, sWhere, sType
      from PKG_LIST_CONFIG_GetNVLClause( tmptable, v_cols.column_name, sNVL_header, sNVL_footer, sWhere, sType, desc_);
      strSelectHeader := strSelectHeader || sNVL_header || ' ' || v_cols.column_name || ',';
      strSelectFooter := strSelectFooter || sNVL_footer || ' ' || v_cols.column_name || ',';
      strSelectSum    := strSelectSum || 'NULL::'||sType||' AS '|| v_cols.column_name || ',';
      strWhereClause  := strWhereClause || ' ' || v_cols.column_name || sWhere;
    END IF;
  END LOOP;
  allCols      := substring( allCols from 1 for Char_length( allCols) - 1);
  strSelectAll := substring( strSelectAll from 1 for char_length( strSelectAll) - 1) || ' FROM ' || UPPER( tmptable);
  IF  char_length( TRIM(both ' ' from  where_clause)) &gt; 0 THEN strSelectAll := strSelectAll || ' WHERE ' || where_clause;  END IF;
  IF  char_length( TRIM(both ' ' from  order_cols)) &gt; 0   THEN strSelectAll := strSelectAll || ' ORDER BY ' || order_cols; END IF;
  SELECT
    coalesce(PKG_LIST_CONFIG_getColoanefromExpresii.WME_RESULT, ''),
    PKG_LIST_CONFIG_getColoanefromExpresii.nrCols
  into sColoaneCalc,nrCalcCols
  FROM PKG_LIST_CONFIG_getColoanefromExpresii(NULL, calc_cols, nrCalcCols);

  sCalcCols := calc_cols;
  sSumCalcCols := sum_calc;
  IF  char_length( calc_cols) &gt; 0 THEN
    select
      coalesce(PKG_LIST_CONFIG_PrelucreazaColCalc.sCalcCols,''),
      coalesce(PKG_LIST_CONFIG_PrelucreazaColCalc.sSumCalcCols,''),
      coalesce(PKG_LIST_CONFIG_PrelucreazaColCalc.sSumHeaderFooter,'')
    into sCalcCols, sSumCalcCols, sSumHeaderFooter
    from PKG_LIST_CONFIG_PrelucreazaColCalc( sCalcCols, sSumCalcCols, sSumHeaderFooter, fara_total);
    strSelectDetalii := strSelectDetalii || sCalcCols;
    strSelectHeader := strSelectHeader || sSumHeaderFooter;
    strSelectFooter := strSelectFooter || sSumHeaderFooter;
    strSelectSum := strSelectSum || sSumCalcCols;
  END IF;
  strSelectDetalii := strSelectDetalii || '(row_number() over ())::numeric AS NRCRT';
  strSelectHeader  := strSelectHeader || 'NRCRT ';
  strSelectFooter  := strSelectFooter || pkg_list_config_get_sid_footer()||'::numeric AS NRCRT ';
  IF  char_length( calc_cols) &gt; 0 THEN allCols := allCols || ',' || sColoaneCalc; END IF;
  allCols         := allCols || ',NRCRT';
  strSelectHeader := strSelectHeader || ' FROM (' || strSelectSum || ' NULL::numeric AS NRCRT FROM ' || tmptable;
  strSelectFooter := strSelectFooter || ' FROM (' || strSelectSum || ' NULL::numeric AS NRCRT FROM ' || tmptable;
  IF  char_length( TRIM(both ' ' from  where_clause)) &gt; 0 THEN
    strSelectHeader := strSelectHeader || sAuxCondHF || where_clause;
    strSelectFooter := strSelectFooter || sAuxCondHF || where_clause;
    sAuxCondHF := ' AND ';
  END IF;
  IF  char_length( TRIM(both ' ' from  fara_total)) &gt; 0 THEN
    strSelectHeader := strSelectHeader || sAuxCondHF || fara_total;
    strSelectFooter := strSelectFooter || sAuxCondHF || fara_total;
    sAuxCondHF := ' AND ';
  END IF;
  strSelectHeader  := strSelectHeader || ') PG_Head';
  strSelectFooter  := StrSelectFooter || ') PG_Foot';
  strSelectDetalii := strSelectDetalii || ' FROM(' || strSelectAll || ') PG_Det';
  strWhereClause   := substr( strWhereClause, 1, char_length( strWhereClause) - char_length( 'AND'));
  strWhereClause   := strWhereClause || ')';
  strSelect        := 'SELECT ' || allCols || ',';
  strSelect        := substr( strSelect, 1, char_length( strSelect) - 1);
  strSelect        := strSelect || '  FROM ( ';
  strSelect        := strSelect || strSelectDetalii || ' UNION ALL ';
  strSelect        := strSelect || strSelectHeader || ' UNION ALL ';
--  insert into X(view_name, Test) values('strSelect', strSelect);
  IF  char_length( TRIM(both ' ' from  order_cols)) &gt; 0 THEN
    strSelect := strSelect || strSelectFooter || ' ) PG_Order ' || strWhereClause || ' ORDER BY  NRCRT, ' || order_cols || '';
  ELSE
    strSelect := strSelect || strSelectFooter || ' ) PG_NoOrder ' || strWhereClause || ' ORDER BY NRCRT';
  END IF;
--  insert into X(view_name, Test) values('1strSelect', strSelect);
  strSelect := 'SELECT SQL.*, (row_number() over ()) AS GLOBALID FROM (' || STRSELECT || ') sql ';
  IF bCentralizat THEN
    strSelect := 'SELECT * FROM  (' || strSelect || ') PG_Cen WHERE  (NRCRT &gt;= '||pkg_list_config_get_sid_footer()||' OR NRCRT &lt;= -'||pkg_list_config_get_sid_header()||')  ';
    IF  char_length( TRIM(both ' ' from  fInterval)) &gt; 0 THEN  strSelect := strSelect || fInterval;END IF;
  END IF;
--  insert into X(view_name, Test) values('2strSelect', strSelect);
  RETURN strSelect;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_seldata_chkextra1</obj_name>
  <obj_hashval>988099f0a5dfe4f50b6da64c6192f999</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_seldata_chkextra1()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.09.2020
  return current_setting ('PKG_LIST_SELDATA.vChkExtra1', true) :: numeric = 1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_seldata_codextra1</obj_name>
  <obj_hashval>ded96e824792dedda02f5f29bf72cd10</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_seldata_codextra1()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.09.2020
  return current_setting ('PKG_LIST_SELDATA.vCodExtra1', true) :: numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectgest2_setparamsxxx</obj_name>
  <obj_hashval>42f8b6094de96263c1ff0d63f262b77d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectgest2_setparamsxxx(pallgest boolean, pziuaini numeric, pziuafin numeric, pallioart boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
vZiMax NUMERIC := Extract( DAY FROM Last_Day( To_Date( coalesce(to_char( getlunalucru(), 'fm00'),'') || '.' || coalesce(to_char( getanlucru(), 'fm0000'),''), 'mm.yyyy')));
begin
  --Adina iulie 2020
perform set_config('PKG_LIST_SELECTGEST2.vAllGest', pAllGest::varchar,false);
perform set_config('PKG_LIST_SELECTGEST2.vAllIOArt', pAllIOArt::varchar,false);
perform set_config('PKG_LIST_SELECTGEST2.vZiIni',Least( pZiuaIni, vZiMax)::varchar,false);
perform set_config('PKG_LIST_SELECTGEST2.vZiFin',Least( pZiuaFin, vZiMax)::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectieprofit_setparams</obj_name>
  <obj_hashval>1a4554532c4145877712e61912508e7e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectieprofit_setparams(pdataini character varying DEFAULT NULL::character varying, pdatafin character varying DEFAULT NULL::character varying, pallgest numeric DEFAULT 1, pdupadata numeric DEFAULT 1, plunaanini numeric DEFAULT 0, plunaanfin numeric DEFAULT 0, pintern numeric DEFAULT 1, pextern numeric DEFAULT 1, ptransf numeric DEFAULT 1, psubunit numeric DEFAULT 1, pfactaviz numeric DEFAULT 1, pextra1 numeric DEFAULT 0, pextra2 numeric DEFAULT 0, pmon numeric DEFAULT 1, pextra3 numeric DEFAULT 0, pcodjob1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 10.05.2023 - sinc. Oracle (09.05.2023)
  --Florin 31.08.2020
  PERFORM set_config('PKG_LIST_SELECTIEPROFIT.vAllGest'  , (COALESCE(pAllGest, 0)= 1)  ::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTIEPROFIT.vDupaData' , (COALESCE(pDupaData, 0) = 1)::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTIEPROFIT.vDataIni'  , pdataini, FALSE);
  PERFORM set_config('PKG_LIST_SELECTIEPROFIT.vDataFin'  , pdatafin, FALSE);
  PERFORM set_config('PKG_LIST_SELECTIEPROFIT.vLunaAnIni', COALESCE(pLunaAnIni, 0)::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTIEPROFIT.vLunaAnFin', COALESCE(pLunaAnFin, 0)::varchar, FALSE);
  IF pCodJob1 &gt; 0
  THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(pCodJob1, pDataIni, pDataFin, pLunaAnIni, pLunaAnFin);
  END IF;
  PERFORM set_config('PKG_LIST_SELECTIEPROFIT.vIntern'  , (COALESCE(pIntern, 0) = 1)  ::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTIEPROFIT.vExtern'  , (COALESCE(pExtern, 0) = 1)  ::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTIEPROFIT.vTransf'  , (COALESCE(pTransf, 0) = 1)  ::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTIEPROFIT.vSubunit' , (COALESCE(pSubunit, 0) = 1) ::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTIEPROFIT.vFactAviz', (COALESCE(pFactAviz, 0) = 1)::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTIEPROFIT.vExtra1'  , (COALESCE(pExtra1, 0) = 1)  ::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTIEPROFIT.vExtra2'  , (COALESCE(pExtra2, 0) = 1)  ::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTIEPROFIT.vExtra3'  , (COALESCE(pExtra3, 0) = 1)  ::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTIEPROFIT.vMon'     , (COALESCE(pMon, 0) = 1)     ::varchar, FALSE);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscadentar_tranzcursfirma</obj_name>
  <obj_hashval>20e879cbfeb57057ed9ee460fc40419a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscadentar_tranzcursfirma()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --Stef 08.08.2022
  return current_setting ('PKG_LIST_SELECTSCADENTAR.g_TCursFirma', true)::boolean;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_inclartstoc0</obj_name>
  <obj_hashval>06d3544f6d6bd456be48af2f66077f0a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_inclartstoc0(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_LIST_SELFISAMAG.p_Stoc0',true));
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_setp_flggest</obj_name>
  <obj_hashval>0f386a8c5398847019501165a6d0f86b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_setp_flggest(ap_flggest boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_SELFISAMAG.p_flgGest',ap_flgGest,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selperagent_lunaanini</obj_name>
  <obj_hashval>f87dd96301a435bfe77eeb2eab57e6ef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selperagent_lunaanini()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.09.2020
  return current_setting ('PKG_LIST_SELPERAGENT.vLunaAnIni', true)::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selurmdocpart_codpart</obj_name>
  <obj_hashval>da9d6313a055cda969861ad35949b663</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selurmdocpart_codpart()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 03.09.2020
  return  current_setting('PKG_LIST_SELURMDOCPART.vCodPart', true)::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selurmdocpart_datadoc</obj_name>
  <obj_hashval>8cf2cf21e75a43e7babbe87d2db06ced</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selurmdocpart_datadoc()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 03.09.2020
  return  to_date(current_setting('PKG_LIST_SELURMDOCPART.vDataDoc', true),'dd.mm.yyyy');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selurmdocpart_nrdoc</obj_name>
  <obj_hashval>638be1f4d744cb3d961e8bccc5c1bcf7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selurmdocpart_nrdoc()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 03.09.2020
  return  current_setting('PKG_LIST_SELURMDOCPART.vNrDoc', true)::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_adauga_param</obj_name>
  <obj_hashval>eb8d139435e9196728619eacc518478d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_adauga_param(pdenumire character varying, pvaloare character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_IdxParamLista NUMERIC;
BEGIN
  --Adina 22 septembrie 2020 - modificat pt.cazul cand parametrul 'PKG_LIST_STRUCT.v_IdxParamLista' nu este setat inca;
  v_IdxParamLista := trunc(CASE WHEN length(current_setting('PKG_LIST_STRUCT.v_IdxParamLista', true))=0 THEN 0 ELSE current_setting('PKG_LIST_STRUCT.v_IdxParamLista', true)::NUMERIC END );
  v_IdxParamLista := v_IdxParamLista + 1;
  perform set_config('PKG_LIST_STRUCT.v_IdxParamLista',to_char(v_IdxParamLista,'999999999999999999'),false);
  INSERT INTO TMP_LIST_PARAMS(IDX, DENUMIRE, VALOARE)
  VALUES(v_IdxParamLista, pDenumire, pValoare);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_altertmp</obj_name>
  <obj_hashval>55500b7f408ce2f80ed7ce4a2f2299c5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_altertmp(tmpname character varying, listcols character varying, suplcols character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sDDL varchar := '';
begin
  --Stef   24.03.2022 - CREATE TEMPORARY (scosGLOBAL fiindca e obsolete si apare/incurca in loguri de BD)
  IF  (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(NULL, tmpName)) = 1 THEN
    sDDL := 'ALTER TABLE ' || tmpName || ' Rename to ' || tmpName || 'XX';
    EXECUTE sDDL;
    sDDL := 'CREATE TEMPORARY TABLE ' || tmpName || ' ON COMMIT PRESERVE ROWS AS (SELECT * FROM ' || tmpName || 'XX WHERE 1=0)';
    EXECUTE sDDL;
    sDDL := 'ALTER TABLE ' || tmpName || ' ' || ListCols;
    EXECUTE sDDL;
    sDDL := 'INSERT INTO ' || tmpName || ' SELECT x.*,' || SuplCols || ' FROM ' || tmpName || 'XX x';
    EXECUTE sDDL;
    PERFORM pkg_list_Struct_DropTbl( tmpName || 'XX');
  END IF;
  Return;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_setv_idxsupltab</obj_name>
  <obj_hashval>255641c43cf18168e67517fc0d1c810d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_setv_idxsupltab(av_idxsupltab numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_STRUCT.v_IdxSuplTab',to_char(av_IdxSuplTab,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_utilfisacont_get_infodescr</obj_name>
  <obj_hashval>602e85ee1b425505c13993c0c9752219</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_utilfisacont_get_infodescr(ptipcont numeric, pcoddescr numeric, pan numeric, pluna numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vResult varchar;
begin
  --BogdanL 27.07.2020
  IF  pTipCont = current_setting('PKG_LIST_UTILFISACONT.TCJCONST', true)::numeric THEN
    vResult := (SELECT PKG_CATEGCONST_GETVALCONSTBYCODE.WME_RESULT FROM PKG_CATEGCONST_GETVALCONSTBYCODE(NULL,pCodDescr, pAn, pLuna));
  ELSIF
     pTipCont = current_setting('PKG_LIST_UTILFISACONT.TCJTVA', true)::numeric
  THEN
    vResult := 'NTVA1';
  END IF;

  return vResult;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_locmunca_sp_deleterecord</obj_name>
  <obj_hashval>acaf25366267763667cfd2b5c9d159f5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_locmunca_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 18.06.2025 - sinc. Oracle
  PERFORM PKG_LOCMUNCA_SP_LOCKRECORD( RecId);
  PERFORM PKG_CFGTABLES_EXT_DELETERECORD (recId, 524);
  DELETE FROM LOCMUNCA1 WHERE CodLoc = RecId;
  DELETE FROM LOCMUNCA2 WHERE CodLoc = RecId;
  DELETE FROM LOCMUNCA  WHERE CodLoc = RecId;
  PERFORM NotifyModif( 2, RecId, 'LOCMUNCA');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mail_utils_getcurrentusermail</obj_name>
  <obj_hashval>4eca231ffcc72476b5db34d5fe0bcbe3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mail_utils_getcurrentusermail(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult      varchar;
  iServer      numeric;
  aID1         varchar;
  aID2         varchar;
  aID3         varchar;
  iPort        numeric;
  aServMail    varchar;
  aDomeniuMail varchar;
  iAuthType    numeric;
  gClientSecret       varchar(200);
  gAuthEndPoint       varchar(200);
  gAccesTokenEndPoint varchar(200);
  gRefreshToken       varchar(2000);
  gLogOutEndPoint     varchar(200);
  gScopes             varchar(300);
  gOAuth2             NUMERIC;
BEGIN
  --Florin 18.03.2025 - sinc. Oracle
  PERFORM winmadmin.pkg_UserFirme.get_user_credential_ext( TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), 0, (SELECT pkg_globals_GETCODFIRMA.WME_RESULT FROM pkg_globals_GETCODFIRMA(NULL,NULL)), aID1, aID2, iPort, aServMail, aDomeniuMail, iAuthType,
    gClientID,
    gClientSecret,
    gAuthEndPoint,
    gAccesTokenEndPoint,
    gLogOutEndPoint,
    gScopes);
  WME_Result :=  aID1;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mail_utils_resendmail</obj_name>
  <obj_hashval>910c3c4562d1368c23b95944159b58ce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mail_utils_resendmail(acod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
iCodMail numeric;
begin
SELECT NEXTVAL('SEQ_MAILURI_CODMAIL')
INTO iCodMail;
INSERT INTO mailuri
(
CODMAIL, SENDER, RECIPIENTS, SUBJECT, MESSAGE, MSG, USERID, DATA, status, host, port, domain, Codfirma, CodServer
)
SELECT iCodMail, SENDER, RECIPIENTS, SUBJECT, MESSAGE, MSG, (SELECT pkg_globals_GETUSERID.WME_RESULT FROM pkg_globals_GETUSERID(NULL,NULL)), CURRENT_TIMESTAMP, 0, host, port, domain, (SELECT pkg_globals_GETCODFIRMA.WME_RESULT FROM pkg_globals_GETCODFIRMA(NULL,NULL)), CodServer
FROM mailuri
WHERE
   CodMail = aCod;
INSERT INTO mailuri1
(
CODMAIL1, CODMAIL, FileName, ATTACHFILE
)
SELECT NEXTVAL('SEQ_MAILURI1_CODMAIL1'), iCodMail, FileName, ATTACHFILE
FROM mailuri1
WHERE
   CodMail = aCod;
--&lt;sstcommit&gt;
PERFORM PKG_MAIL_UTILS_DoTheJob( iCodMail,NULL);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mascaserart_sp_insertrecord</obj_name>
  <obj_hashval>b0736c60ed27e72f6544cb53d1e3b911</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mascaserart_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_MASCASERART (CodMasca) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_medex_getcompensare</obj_name>
  <obj_hashval>11339de9fe081d25985a47cf5623b6fd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_medex_getcompensare(INOUT wme_result character varying, INOUT cim character varying, INOUT datastart date)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  t varchar;
begin
  BEGIN
    SELECT string_agg(m2.tipcompens,',') INTO t
    FROM (SELECT  DISTINCT tipcompens, validdela FROM medex2 WHERE codcim = CIM) m2
    WHERE m2.validdela = datastart;
  EXCEPTION WHEN others THEN
    t := '';
  END;

  WME_Result :=  t;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_medex_getcompensares</obj_name>
  <obj_hashval>94f621ecdb5683173bc0a23dc41d8bc5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_medex_getcompensares(INOUT wme_result character varying, INOUT cim character varying, INOUT datastart character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  t varchar;
begin
  BEGIN
    SELECT string_agg(m2.tipcompens,',') INTO t
    FROM (SELECT  DISTINCT tipcompens, validdela FROM medex2 WHERE codcim = CIM) m2
    WHERE m2.validdela = to_date(datastart, 'DD.MM.YYYY');
  EXCEPTION WHEN others THEN
    t := '';
  END;

  WME_Result :=  t;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_medex_sp_insertrecord</obj_name>
  <obj_hashval>7125476996c3fdc1866513baab333ead</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_medex_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_MEDEX (CodMedex) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mese_sp_deleterecord</obj_name>
  <obj_hashval>6cd03926d29b06f7195588918079181e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mese_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_MESE_SP_LOCKRECORD( RecId);
  DELETE FROM MESE WHERE CODMASA = RecId;
  PERFORM NotifyModif( 2, RECID, 'MESE');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mese_sp_insertrecord</obj_name>
  <obj_hashval>30b36076808a7688d13ae7c58687b4bc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mese_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_MESE (CODMASA) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mese_sp_lockrecord</obj_name>
  <obj_hashval>fac65a9b0c538ad04c820e201ed2ff8d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mese_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CODMASA INTO Tmp FROM MESE WHERE CODMASA = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mifix_setct_monitor</obj_name>
  <obj_hashval>65f162a818b4846664da4088059c1d5e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mifix_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_MIFIX.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mifix_sp_insertrecord</obj_name>
  <obj_hashval>5fc76cba3222dee8ce5aacdb5d6cf48a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mifix_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 28.11.2024 - sinc. Oracle
  INSERT INTO TMP_MASTERMIFIX (CODNIRSTOC) VALUES(0);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(36);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mifix_sp_lockrecord</obj_name>
  <obj_hashval>42ee0ea5d95b4dcca0521b25b7784e66</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mifix_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  BEGIN
    SELECT CODNIRSTOC INTO Tmp FROM MASTERMIFIX WHERE CODNIRSTOC = RecId FOR UPDATE NOWAIT;
  EXCEPTION WHEN OTHERS THEN
    TMP := 0;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mifix_unlocknrinv</obj_name>
  <obj_hashval>234042784cf2c5b676f179917ef5a996</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mifix_unlocknrinv()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM NRINVLOCK WHERE USERID = TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_check_rezervari_modipret_in</obj_name>
  <obj_hashval>afa1108a0a608cfaf30142f193c96b9e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_check_rezervari_modipret_in()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN
  (
  SELECT L1.CODNIRSTOC AS CODNIRSTOC_DEST, L1.CODNIRSER AS CODNIRSER_DEST, L1.CANT, NS.CODNIRSTOC AS CODNIRSTOC_SURSA, COALESCE( NSE.CODNIRSER, 0) AS CODNIRSER_SURSA
  FROM TMP_LIVR1_INITIAL L1, TMP_NIRSTOCINI NS
       LEFT JOIN TMP_NIRSERINI NSE ON  NSE.CODNIRSTOC = NS.CODNIRSTOC
  WHERE NS.CODLIVR1 = L1.CODLIVR1
  )
  LOOP
    PERFORM PKG_MISCARI_INTERNE_CHECK_REZERVARI( V_REC.CODNIRSTOC_SURSA, V_REC.CODNIRSER_SURSA, V_REC.CODNIRSTOC_DEST, V_REC.CODNIRSER_DEST, V_REC.CANT);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_nr_livrari_din_nirtransf</obj_name>
  <obj_hashval>1c65e116cc77cfc20d6d123185f261b6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_nr_livrari_din_nirtransf(INOUT wme_result numeric, INOUT acodtransf numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  BEGIN
    SELECT COALESCE( COUNT( *), 0)
    INTO NR
    FROM LIVR1
    WHERE
      CODNIRSTOC IN (SELECT CODNIRSTOC FROM NIRSTOC WHERE CODNIR IN (SELECT CODNIR FROM NIR WHERE CODTRANSF = ACODTRANSF AND TIPNIR IN (12, 13)) );
  EXCEPTION WHEN OTHERS THEN
    NR := 0;
  END;

  WME_Result :=  NR;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_setcarnetdoc_i</obj_name>
  <obj_hashval>2c9733d7619d3a9e9a04b378d1221fec</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_setcarnetdoc_i(acarnetdoc_i numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_MISCARI_INTERNE.CARNETDOC_I',to_char(aCARNETDOC_I,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_sp_gotorecord</obj_name>
  <obj_hashval>07b27f2cc433a4de2837c8cd3107a640</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC      RECORD;
  ATIPDOC    numeric := 0;
  TIPPREFIX  varchar := '0';
  acount     numeric;
BEGIN
  --Florin 18.06.2025 - sinc. Oracle
  --Florin 18.04.2024 - sinc. Oracle
  --Florin 27.10.2023 - sinc. Oracle
  --Florin 06.10.2023 - fixat 59598
  --Florin 12.04.2023 - sinc. Oracle (11.04.2023)
  --Florin 20.09.2022 - sinc. Oracle (19.09.2021)
  --Florin 12.09.2022 - sinc. Oracle
  --Florin 30.06.2022 - fixat 54778
  --Florin 29.06.2022 - sinc. Oracle (28.06.2022), fnc_getprocenttvaart
  --Florin 22.01.2022 - sinc. Oracle (29.12.2021)
  --Adina 04.05.2021 - sinc.Oracle din 30.04.2021
  --Adina 25.02.2021 - sinc.Oracle
  --Florin 16.11.2021 - fixat 52001
  perform pkg_miscari_interne_setct_monitor('MON_13');
  PERFORM PKG_STOC_GENERARE_FACTURI_MAKE_CONFIG_LUNA();

  -- MASTER TRANSF
  INSERT INTO TMP_TRANSF(CODTRANSF, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, CARNETDOC, SUBUNITATEA, NRDOC, DATADOC, CARNETAE, NRAE, VALDOC, TVADOC, OBS, AN, LUNA,
                         VALSUPLIM, CONTSUPLIM, TIPREPSUPLIM, DELEGAT, CODPART, STORNO, TIPMODIFPRET, MIJLTRANSP, NRTRANSP, CODGESTCMD, LISTAT, REEVALUARE, SERIADOC,
                         UserID, CodAnaliza, SubunitDest, AJUSTVALSTOC, STADIUWMS, CODAUTO,
                         TipET,  UIT, ET_IDINCARCARE, ET_IDDESCARCARE, ET_TIPMEDIU, ET_STATUS, is_ETransp, Corectie)
  (
  SELECT CODTRANSF, TR.TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, CARNETDOC, SUBUNITATEA, NRDOC, DATADOC, CARNETAE, NRAE, VALDOC, TVADOC, OBS, TR.AN, TR.LUNA, VALSUPLIM,
         CONTSUPLIM, TIPREPSUPLIM, DELEGAT, CODPART, STORNO, TIPMODIFPRET, MIJLTRANSP, NRTRANSP, CODGESTCMD, LISTAT, REEVALUARE, SERIADOC, UserID, CodAnaliza,
         SubunitDest, AJUSTVALSTOC, STADIUWMS, CODAUTO,
         TipET, ET.UIT, ET.IDINCARCARE, ET.IDDESCARCARE, ET.TIPMEDIU, Coalesce(ET.STARE,'?'), is_ETransp, Corectie
  FROM TRANSF TR LEFT OUTER JOIN StatusDecl ET ON ET.CodDoc = tr.CODTRANSF and ET.TipDoc = 100 + tr.TipDoc
  WHERE CODTRANSF = RECID
  );

  INSERT INTO TMP_TRANSF1(CODTRANSF1, CODTRANSF, INDEXLOCAL, TIPLINIE, CODOBIECTORIG, PARITATEORIG, CODCONT, UMSEC, CODOBIECT, PU, CANT, TVA, DENUM, VALOARE,
                          PARITATE, PROCTVA, CODTVA, CODACCIZE, CODTAXA1, CODTAXA2, PUMAXIMAL, DENOBIECT, CODMIFIX, PUVAl, CodReteta, CODCENTRU, CODCOMANDA1,
                          CodAnalizaNod, CODEXTERN, CODINTERN, UM1, RELATIEUM1, D1, D2, D3, CantUM1, CantUM2, CmdInt, PRELUAT, COEFUM_CANTAR, COSTTRANSPORT,
                          CODAUTO, CODEMULARE1,OBS, TIPDOCIMP, CODLINIEDOCIMP)
  SELECT *
  FROM (SELECT T1.CODTRANSF1, T1.CODTRANSF, T1.INDEXLOCAL, TIPLINIE, CODOBIECTORIG, PARITATEORIG, T1.CODCONT, T1.UMSEC, T1.CODOBIECT, T1.PU * U1.PARITATE,
               T1.CANT / U1.PARITATE, T1.TVA, U1.DEN_UM1, T1.CANT * T1.PU, U1.PARITATE,
               fnc_getprocenttvaart(A.CODARTICOL, TO_NUMBER(current_setting('PKG_GLOBALS.ANLUCRU', true),'999999999999999999'), TO_NUMBER(current_setting('PKG_GLOBALS.LUNALUCRU', true),'999999999999999999')),
               NART1LUNA.CODTVA, NART1LUNA.CODACCIZE, NART1LUNA.CODTAXA1, NART1LUNA.CODTAXA2, T1.PUMAXIMAL * U1.PARITATE, O.DENUMIRE, T1.CODMIFIX, T1.PUVAl,
               t1.CodReteta, T1.CODCENTRU, T1.CODCOMANDA1, T1.Codanalizanod, O.CODEXTERN, O.CODINTERN, A.UM1, A.RELATIEUM1, T1.D1, T1.D2, T1.D3, T1.CantUM1,
               T1.CantUM2, C.NrDoc, T1.PRELUAT,
               CASE WHEN  COALESCE( u.tipum, 0) = 1 THEN u.coef ELSE 0 END ,
               T1.COSTTRANSPORT, T1.CODAUTO, T1.CODEMULARE1,T1.OBS, T1.TIPDOCIMP, T1.CODLINIEDOCIMP
        FROM TRANSF1 T1
            LEFT JOIN COMANDA1   C1       ON  C1.CODCOMANDA1 = T1.CODCOMANDA1
            LEFT JOIN COMANDA    C        ON  C.CODCOMANDA   = C1.CODCOMANDA
            LEFT JOIN NARTOBJ   O        ON  O.CODOBIECT    = T1.CODOBIECT
            LEFT JOIN NART       A        ON  A.CODARTICOL   = O.CODARTICOL
            LEFT JOIN NUM        U        ON  A.UM = U.CODUM
            LEFT JOIN NART1    NART1LUNA   ON  NART1LUNA.CODARTICOL = O.CODARTICOL and getanlunalucru() BETWEEN NART1LUNA.alstart AND NART1LUNA.alstop
                  LEFT JOIN NUM1     U1       ON  U1.CODUM1 = T1.UMSEC
        WHERE T1.CODTRANSF = RECID
       ) A_PG
  ORDER BY INDEXLOCAL ;

  DELETE FROM TMP_TRANSF1_INITIAL;
  INSERT INTO TMP_TRANSF1_INITIAL(CODTRANSF1, CODCOMANDA1) SELECT CODTRANSF1, CODCOMANDA1 FROM TMP_TRANSF1;

  -- Detail TRANSFLINK
  INSERT INTO TMP_TRANSFLINK(CODTRANSF1, CODLINIECOMANDA, CANT)
  (SELECT CODTRANSF1, CODLINIECOMANDA, CANT FROM TRANSFLINK L WHERE L.CODTRANSF1 IN (SELECT CODTRANSF1 FROM TMP_TRANSF1));

  -- Detail IMBMIFIXLINK
  INSERT INTO TMP_IMBMIFIXLINK(CODIMBMIFIXLINK, CODTRANSF1, CODINTR1, CODIES1, CODNC1, CODMIFIX, CANT)
  (SELECT CODIMBMIFIXLINK, CODTRANSF1, CODINTR1, CODIES1, CODNC1, CODMIFIX, CANT
   FROM IMBMIFIXLINK L
   WHERE EXISTS (SELECT CODTRANSF1 FROM TMP_TRANSF1 WHERE CODTRANSF1 = L.CODTRANSF1)
  );

  INSERT INTO TMP_IMBMIFIXLINK_INITIAL
  SELECT * FROM TMP_IMBMIFIXLINK;

  UPDATE TMP_TRANSF1 I1
  SET
  NRDOCLINK = CASE  WHEN I1.TIPLINIE IN ('S', '=') THEN (SELECT coalesce(CC.PREFIXDOC,'') || coalesce(( CC.NRDOC)::varchar,'')
                                                         FROM TRANSFLINK IL
                                                              LEFT JOIN COMANDA1 CC1 ON  CC1.CodComanda1 = IL.CODLINIECOMANDA
                                                              LEFT JOIN COMANDA  CC  ON  CC.CodComanda   = CC1.CODCOMANDA
                                                         WHERE IL.CODTRANSF1 = I1.CODTRANSF1
                                                        )
              END
  WHERE I1.TIPLINIE IN ('S', '=');

  INSERT INTO TMP_TRANSFLINK_INITIAL SELECT * FROM TMP_TRANSFLINK;

  UPDATE TMP_TRANSFLINK L
  SET
  DATACOMANDA = (SELECT C.DATADOC
                 FROM COMANDA1 C1, COMANDA C
                 WHERE C1.CODCOMANDA1 = L.CODLINIECOMANDA AND  C.CODCOMANDA = C1.CODCOMANDA
                );


  -- DETAIL LIVR
  INSERT INTO TMP_LIVR(CODLIVR, CODIES, CODINTR, CODTRANSF, CARNETLIVR, NRLIVR, DATALIVR, OBS, TIPLIVR, ANULAT, BLOCAT, OPERAT)
  (SELECT CODLIVR, CODIES, CODINTR, CODTRANSF, CARNETLIVR, NRLIVR, DATALIVR, OBS, TIPLIVR, ANULAT, BLOCAT, OPERAT
   FROM LIVR WHERE CODTRANSF = RECID
  );

  -- DETAIL LIVR1
  INSERT INTO TMP_LIVR1(CODLIVR1, CODLIVR, CODIES1, CODNIRSTOC, CANT, CANTUM1, CANTUM2, CODNIRSER, PMP, PMPDOC, PMPVALUTA, PMPVALUTADOC, UMSEC, DENUM,
                        PARITATE, GEST, CODIOART, CODOBIECT, DENOBIECT, CODLIVRTOT, TIPLINIE, PRETINREG, ADAOS, TVANEEX, PRETACHIZ, TIPSERIE, CODSERIE,
                        SERIE, TG, PUMAXIMAL, FURN, DATAACHIZ, TIPDOCACHIZ, CODGESTPROD, SUBUNITATEA, CANTREZERVAT, D1, D2, D3, CODCERTIF, CODLOCATIE,
                        PUAVAL, PROVIZION, CONTINTERMED, CODPROIECT, SERIELOT, CODLIVR1PARINTE, CODPRODCOMP,
                        EUDR_RN,
                        EUDR_VN)
  (SELECT L1.CODLIVR1, L1.CODLIVR, L1.CODIES1, L1.CODNIRSTOC, L1.CANT / U1.PARITATE, L1.CANTUM1, L1.CANTUM2, L1.CODNIRSER, L1.PMP, L1.PMPDOC, L1.PMPVALUTA,
          L1.PMPVALUTADOC, L1.UMSEC, U1.DEN_UM1, U1.PARITATE,
          CASE WHEN LV.CODLIVR1 IS NULL  THEN N.GEST       ELSE LV.GEST      END ,
          CASE WHEN LV.CODLIVR1 IS NULL  THEN NS.CODIOART  ELSE LV.CODIOART  END ,
          CASE WHEN LV.CODLIVR1 IS NULL  THEN NS.CODOBIECT ELSE LV.CODOBIECT END ,
          CASE WHEN LV.CODLIVR1 IS NULL  THEN (SELECT PKG_SELECTARTICOLE_GETDENOBIECTEXT.WME_RESULT FROM PKG_SELECTARTICOLE_GETDENOBIECTEXT(NULL, NS.CODOBIECT))
               ELSE (SELECT PKG_SELECTARTICOLE_GETDENOBIECTEXT.WME_RESULT FROM PKG_SELECTARTICOLE_GETDENOBIECTEXT(NULL, LV.CODOBIECT))
          END ,
          0, '=',
          CASE WHEN LV.CODLIVR1 IS NULL  THEN NS.PRET * U1.PARITATE  ELSE LV.PRETINREG * U1.PARITATE END ,
          CASE WHEN LV.CODLIVR1 IS NULL  THEN NS.ADAOS * U1.PARITATE ELSE (LV.PRETINREG - LV.PRETACHIZ)  * U1.PARITATE END ,
          CASE WHEN LV.CODLIVR1 IS NULL  THEN NS.TVA ELSE LV.TVANEEX END ,
          CASE WHEN LV.CODLIVR1 IS NULL  THEN (  NS.PRET - NS.ADAOS)  * U1.PARITATE ELSE LV.PRETACHIZ * U1.PARITATE END ,
          CASE WHEN LV.CODLIVR1 IS NULL  THEN NS.TIPSERIE ELSE 0 END ,
          (SELECT CODSERIE FROM NIRSER WHERE CODNIRSER = L1.CODNIRSER),
          (SELECT SERIE    FROM NSERII WHERE CODSERIE = (SELECT CODSERIE FROM NIRSER WHERE CODNIRSER = L1.CODNIRSER)),
          NS.TG, NS.PUMAXIMAL, NS.FURN, NS.DATAACHIZ, NS.TIPDOCACHIZ, NS.CODGESTPROD, NS.SUBUNITATEA, L1.CANTREZERVAT / U1.PARITATE,
          NS.D1, NS.D2, NS.D3, L1.CODCERTIF, NS.CODLOCATIE, NS.PUVAL, NS.PROVIZION, L1.CONTINTERMED, L1.CODPROIECT, NS.SERIELOT, L1.CODLIVR1PARINTE, L1.CODPRODCOMP,
          NS.EUDR_RN,
          NS.EUDR_VN
   FROM LIVR1 L1
        LEFT JOIN NIRSTOC NS ON  NS.CODNIRSTOC = L1.CODNIRSTOC
        LEFT JOIN LIVRVAL LV ON  LV.CODLIVR1   = L1.CODLIVR1
        LEFT JOIN NIR     N  ON  N.CODNIR      = NS.CODNIR
        LEFT JOIN LIVR    L  ON  L.CODLIVR     = L1.CODLIVR, NUM1 U1
   WHERE L.CODTRANSF = RECID AND  U1.CODUM1 = L1.UMSEC
  );

  -- DETAIL LIVRTOT
  DELETE FROM TMP_LIVRTOT;
  INSERT INTO TMP_LIVRTOT(CODLIVRTOT, CODLIVR, CODIESINT1, UMSEC, GEST, CODIOART, CONTINTERMED, CODPROIECT, CODOBIECT, DENUM, PARITATE, DENGESTIOART,
                          DIFPRET, ACCIZELATRANSFER, ARETVANEEX, MG, CONT, SUFIXTVANEEX, STOCREZOLVAT, CANT, PRETINREG, PRETACHIZ, PMP, PMPDOC, PMPVALUTA, PMPVALUTADOC, CODPRODCOMP)
  SELECT row_number() over() as codlivrtot, B_PG.*
  FROM (SELECT L1.CODLIVR, L1.CODIES1, L1.UMSEC, L1.GEST, L1.CODIOART, COALESCE( L1.CONTINTERMED, 0), COALESCE( L1.CODPROIECT, 0), L1.CODOBIECT, L1.DENUM,
               L1.PARITATE, coalesce(G.DEN_GEST,'') || coalesce(CHR( 13),'') || coalesce(IO.DEN_IOART,''), IOALUNA.DIFPRET, IOALUNA.ACCIZELATRANSFER,
               IOALUNA.ARETVANEEX, IOALUNA.MG, IOALUNA.CONT, IOALUNA.TVANEEX, 1,
               SUM( L1.CANT),
               SUM( L1.PRETINREG    * L1.CANT) / SUM( L1.CANT),
               SUM( L1.PRETACHIZ    * L1.CANT) / SUM( L1.CANT),
               SUM( L1.PMP          * L1.CANT) / SUM( L1.CANT),
               SUM( L1.PMPDOC       * L1.CANT) / SUM( L1.CANT),
               SUM( L1.PMPVALUTA    * L1.CANT) / SUM( L1.CANT),
               SUM( L1.PMPVALUTADOC * L1.CANT) / SUM( L1.CANT),
               L1.CODPRODCOMP
        FROM TMP_LIVR1 L1
              LEFT JOIN IOART1   IOALUNA ON IOALUNA.CODIOART = L1.CODIOART and getanlunalucru() BETWEEN IOALUNA.alstart AND IOALUNA.alstop
          LEFT JOIN LIVR    L      ON  L.CODLIVR   = L1.CODLIVR
        LEFT JOIN NGEST   G      ON  G.CODGEST   = L1.GEST
        LEFT JOIN IOART   IO     ON  IO.CODIOART = L1.CODIOART
        WHERE L.CODTRANSF = RECID AND  L1.CANT &lt;&gt; 0
        GROUP BY L1.CODLIVR, L1.CODIES1, L1.CODOBIECT, L1.UMSEC, L1.GEST, L1.CODIOART, COALESCE( L1.CONTINTERMED, 0), COALESCE( L1.CODPROIECT, 0),
                 L1.DENUM, L1.PARITATE, coalesce(G.DEN_GEST,'') || coalesce(CHR( 13),'') || coalesce(IO.DEN_IOART,''),
                 IOALUNA.DIFPRET, IOALUNA.ACCIZELATRANSFER, IOALUNA.ARETVANEEX, IOALUNA.MG, IOALUNA.CONT, IOALUNA.TVANEEX, L1.CODPRODCOMP
       ) B_PG
  ORDER BY CODLIVR , CODIES1 ;


  UPDATE TMP_LIVRTOT T
  SET
  --CODLIVRTOT = ROWNUM,
  (DENOBIECT, CODEXTERN, CODINTERN) = (SELECT DENUMIRE, CODEXTERN, CODINTERN FROM NARTOBJ O WHERE O.CODOBIECT = T.CODOBIECT),
  (UM1, UM2, RELATIEUM1, TIPSERIE)  = (SELECT UM1, UM2, RELATIEUM1, TIPSERIE FROM NART WHERE CODARTICOL = (SELECT PKG_SELECTARTICOLE_GETARTOFOBJECT.WME_RESULT FROM PKG_SELECTARTICOLE_GETARTOFOBJECT(NULL, T.CODOBIECT))),
  INDEXMASTER   = (SELECT INDEXLOCAL    FROM TMP_TRANSF1 WHERE CODTRANSF1 = T.CODIESINT1),
  GESTIMPLICITA = (SELECT GESTIMPLICITA FROM NART        WHERE CODARTICOL = (SELECT PKG_SELECTARTICOLE_GETARTOFOBJECT.WME_RESULT FROM PKG_SELECTARTICOLE_GETARTOFOBJECT(NULL, T.CODOBIECT))),
  PROCTVA       = fnc_getprocenttvaart((SELECT PKG_SELECTARTICOLE_GETARTOFOBJECT.WME_RESULT FROM PKG_SELECTARTICOLE_GETARTOFOBJECT(NULL, T.CODOBIECT)), TO_NUMBER(current_setting('PKG_GLOBALS.ANLUCRU', true),'999999999999999999'), TO_NUMBER(current_setting('PKG_GLOBALS.LUNALUCRU', true),'999999999999999999'));


  -- DETAIL TMP_LIVRVAL;
  INSERT INTO TMP_LIVRVAL SELECT * FROM LIVRVAL WHERE CODLIVR1 IN (SELECT CODLIVR1 FROM TMP_LIVR1);

  -- PARITATEA PRETURILOR DIN LIVRVAL ESTE CEA DIN TMP_LIVR1
  UPDATE TMP_LIVRVAL LV
  SET
  PRETINREG = PRETINREG * COALESCE( (SELECT L1.PARITATE FROM TMP_LIVR1 L1 WHERE L1.CODLIVR1 = LV.CODLIVR1), 1),
  PRETACHIZ = PRETACHIZ * COALESCE( (SELECT L1.PARITATE FROM TMP_LIVR1 L1 WHERE L1.CODLIVR1 = LV.CODLIVR1), 1);

  -- FAC LEGATURA INTRE LIVR1 SI LIVRTOT
  UPDATE TMP_LIVR1 L1
  SET
  (CODLIVRTOT, GESTIMPLICITA, DIFPRET, ARETVANEEX) = (SELECT CODLIVRTOT, GESTIMPLICITA, DIFPRET, ARETVANEEX
                                                      FROM TMP_LIVRTOT
                                                      WHERE  CODLIVR                = L1.CODLIVR
                                                        AND  CODIESINT1             = L1.CODIES1
                                                        AND  UMSEC                  = L1.UMSEC
                                                        AND  PARITATE               = L1.PARITATE
                                                        AND  COALESCE( GEST, 0)     = COALESCE( L1.GEST, 0)
                                                        AND  COALESCE( CODIOART, 0) = COALESCE( L1.CODIOART, 0)
                                                     );

  -- DETAIL NIR
  INSERT INTO TMP_NIR(CODNIR, CODINTR, CODTRANSF, CARNETNIR, NRNIR, DATANIR, GEST, OBS, TIPNIR, ANULAT, BLOCAT, OPERAT, USERID, VALOARE, CODIOARTIMPLICIT)
  SELECT N.CODNIR, N.CODINTR, N.CODTRANSF, N.CARNETNIR, N.NRNIR, N.DATANIR, N.GEST, N.OBS, N.TIPNIR, N.ANULAT, N.BLOCAT, N.OPERAT, N.USERID,
         (SELECT SUM( NS.CANTNIR * NS.PRET) FROM NIRSTOC NS WHERE NS.CODNIR = N.CODNIR),
         G.CODCONT
  FROM NIR N LEFT JOIN NGEST G ON  G.CODGEST = N.GEST
  WHERE N.CODTRANSF = RECID
  ORDER BY NRNIR ;

  -- DETAIL NIRSTOC
  INSERT INTO TMP_NIRSTOC(CODNIRSTOC, CODNIR, CODINTR1, CODTRANSF1, CODNIRSTOCPARINTE, FURN, CANTNIR, UMSEC, CODOBIECT, CODIOART, PRET,
                          ROTLEI, ROTVALUTA, CODLOCATIE, PUMAXIMAL, ADAOS, TVA, TIPSERIE, CODLIVR1, REST, PROCENTADAOS, Supliment, TG,
                          DATAACHIZ, DENUM, PARITATE, VALOARE, CANTFURN, MG, DIFPRET, ACCIZELATRANSFER, ARETVANEEX, PUSTANDARD, PRETACHIZ,
                          PROCTVA, DISCLIKISTOC, DENOBIECT, CANTUM1, CANTUM2, UM1, UM2, RelatieUM1, D1, D2, D3, CODGESTPROD, TIPDOCACHIZ,
                          PUVAL, PROVIZION, SERIELOT, CODEXTERN, CODINTERN, EUDR_RN, EUDR_VN)
  SELECT *
  FROM (SELECT NS.CODNIRSTOC, NS.CODNIR, NS.CODINTR1, NS.CODTRANSF1, NS.CODNIRSTOCPARINTE, NS.FURN, NS.CANTNIR / U1.PARITATE, NS.UMSEC, NS.CODOBIECT,
               NS.CODIOART, NS.PRET * U1.PARITATE, NS.ROTLEI, NS.ROTVALUTA, NS.CODLOCATIE, NS.PUMAXIMAL, NS.ADAOS * U1.PARITATE, NS.TVA, NS.TIPSERIE,
               NS.CODLIVR1, NS.REST, NS.PROCENTADAOS, NS.Supliment, NS.TG, NS.DATAACHIZ, U1.DEN_UM1, U1.PARITATE, NS.CANTNIR * NS.PRET,
               NS.CANTFURN / U1.PARITATE, IOALUNA.MG, IOALUNA.DIFPRET, IOALUNA.ACCIZELATRANSFER, IOALUNA.ARETVANEEX, IOALUNA.PUSTANDARD,
               (NS.PRET - NS.ADAOS - CASE WHEN  COALESCE( NS.CANTNIR, 0) = 0 THEN 0 ELSE COALESCE( NS.SUPLIMENT, 0) / (  NS.CANTNIR / U1.PARITATE) END) * u1.Paritate,
               fnc_getprocenttvaart(A.CODARTICOL, TO_NUMBER(current_setting('PKG_GLOBALS.ANLUCRU', true),'999999999999999999'), TO_NUMBER(current_setting('PKG_GLOBALS.LUNALUCRU', true),'999999999999999999')),
               DISCLIKISTOC, O.DENUMIRE, NS.CANTUM1, NS.CANTUM2, A.UM1, A.UM2, A.RelatieUM1, NS.D1, NS.D2, NS.D3, NS.CODGESTPROD, NS.TIPDOCACHIZ,
               NS.PUVAL, NS.PROVIZION, NS.SERIELOT, O.CODEXTERN, O.CODINTERN,
               NS.EUDR_RN,
               NS.EUDR_VN
        FROM NIRSTOC NS
             LEFT JOIN ioart1   IOALUNA ON  IOALUNA.CODIOART = NS.CODIOART and getanlunalucru() BETWEEN IOALUNA.alstart AND IOALUNA.alstop
             LEFT JOIN NARTOBJ   O     ON  O.CODOBIECT  = NS.CODOBIECT
             LEFT JOIN NART      A     ON  A.CODARTICOL = O.CODARTICOL, NUM1 U1
        WHERE NS.CODNIR IN (SELECT CODNIR FROM TMP_NIR) AND  U1.CODUM1 = NS.UMSEC
       ) C_PG
  ORDER BY CODNIR , CODINTR1 ;

  INSERT INTO TMP_NIRSTOC1
  SELECT NS1.* FROM NIRSTOC1 NS1 WHERE EXISTS (SELECT TMP.CODNIRSTOC FROM TMP_NIRSTOC TMP WHERE TMP.CODNIRSTOC = NS1.CODNIRSTOC);

  -- PENTRU DISTRIBUIRE VALORI SUPLIMENTARE PREIAU MASA SI VOLUM
  UPDATE TMP_NIRSTOC NS
  SET
  (MASA, VOLUM)   = (SELECT COALESCE( MASA, 0), COALESCE( VOLUM, 0) FROM NARTOBJ O WHERE O.CODOBIECT = NS.CODOBIECT),
  PRETINITIAL     = PRET,
  ADAOSINITIAL    = ADAOS,
  CONT            = (SELECT CONT FROM TMP_IOART_LUNA IO WHERE IO.CODIOART = NS.CODIOART),
  MGPARINTE       = (SELECT COALESCE( MG, 0) FROM NIRSTOC NSP WHERE NSP.CODNIRSTOC = NS.CODNIRSTOCPARINTE),
  CODIOARTINITIAL = CODIOART,
  TIPPRETMAX      = (SELECT COALESCE( TIPPRETMAX, 0) FROM TMP_NARTOBJ_LUNA O1 WHERE O1.CODOBIECT = NS.CODOBIECT),
  DENFURN         = (CASE WHEN  NS.TIPDOCACHIZ = 7 THEN (SELECT DEN_GEST FROM NGEST WHERE CODGEST = NS.CODGESTPROD)
                          ELSE (SELECT DEN_PART FROM NPART WHERE CODPART = NS.FURN)
                     END );


  -- DETAIL NIRSER
  INSERT INTO TMP_NIRSER (CODNIRSER, CODNIRSTOC, CODSERIE, CANTNIR, SERIE, CANTUM1, CANTUM2, OBS, CODCERTIF, DATAPROD, TG, STARE, DATAPROD1, TG1, CODPRODUCATOR)
  (SELECT CODNIRSER, CODNIRSTOC, CODSERIE, CANTNIR, (SELECT SERIE FROM NSERII WHERE CODSERIE = NS.CODSERIE), CANTUM1, CANTUM2, OBS, CODCERTIF, DATAPROD, TG, STARE, DATAPROD1, TG1, CODPRODUCATOR FROM NIRSER NS
  WHERE CODNIRSTOC IN (SELECT CODNIRSTOC FROM TMP_NIRSTOC)
  );
  UPDATE TMP_NIRSER SET TG = NULL WHERE TG = to_date('30.12.1899','dd.mm.yyyy');
  UPDATE TMP_NIRSER SET DATAPROD = NULL WHERE DATAPROD = to_date('30.12.1899','dd.mm.yyyy');

  IF  RECID &gt; 0 THEN
    SELECT TIPDOC INTO ATIPDOC FROM TMP_TRANSF;
  END IF;

  PERFORM PKG_CFGTABLES_CHECK_STRUCT_EXTENSIE_X_TIPDOC(ATIPDOC);

  DELETE FROM TMP_JURNAL;
  DELETE FROM TMP_JURNAL1;

  INSERT INTO TMP_JURNAL  (SELECT * FROM JURNAL  WHERE TIPDOC = ATIPDOC AND  CODDOC = RECID);
  INSERT INTO TMP_JURNAL1 (SELECT * FROM JURNAL1 WHERE TIPDOC = ATIPDOC AND  CODDOC = RECID);

  DELETE FROM TMP_RULAJ;

  UPDATE TMP_LIVR1 L1
  SET
  PROCTVA                = (SELECT PROCTVA              FROM TMP_LIVRTOT WHERE CODLIVRTOT    = L1.CODLIVRTOT),
  PROCENTADAOS           = (SELECT PROCENTADAOS         FROM NIRSTOC NS  WHERE NS.CODNIRSTOC = L1.CODNIRSTOC),
  (DATAPROD, STARE, OBS) = (SELECT DATAPROD, STARE, OBS FROM NIRSER NSE  WHERE NSE.CODNIRSER = L1.CODNIRSER);

  UPDATE TMP_NIRSTOC NS
  SET
  INDEXMASTER = (SELECT INDEXLOCAL FROM TMP_TRANSF1 WHERE CODTRANSF1 = NS.CODTRANSF1);

  UPDATE TMP_NIRSER NSE
  SET
  PARITATE = COALESCE( (SELECT PARITATE FROM TMP_NIRSTOC WHERE CODNIRSTOC = NSE.CODNIRSTOC), 1),
  CANTNIR  = CANTNIR / COALESCE( (SELECT PARITATE FROM TMP_NIRSTOC WHERE CODNIRSTOC = NSE.CODNIRSTOC), 1);

  DELETE FROM TMP_NIRSTOCINI;
  DELETE FROM TMP_NIRSERINI;

  INSERT INTO TMP_NIRSTOCINI(CODNIRSTOC, CODLIVR1) SELECT CODNIRSTOC, CODLIVR1 FROM TMP_NIRSTOC;

  INSERT INTO TMP_NIRSERINI SELECT * FROM TMP_NIRSER;

  UPDATE TMP_TRANSF1 I1
  SET
  INFOMF = SUBSTR( (SELECT MF.NRINVENTAR::varchar || '/' || coalesce(O.DENUMIRE,'')
                    FROM MIFIX MF, MIFIX1 MF1, NIRSTOC NS, NARTOBJ O
                    WHERE  MF.CODMIFIX = I1.CODMIFIX
                      AND  MF.CODMIFIX = MF1.CODMIFIX
                      AND  MF1.ANSTART * 12 + MF1.LUNASTART = TO_NUMBER(current_setting('PKG_GLOBALS.ANLUCRU', true),'999999999999999999') * 12 + TO_NUMBER(current_setting('PKG_GLOBALS.LUNALUCRU', true),'999999999999999999')
                      AND  NS.CODNIRSTOC = MF1.CODNIRSTOC
                      AND  O.CODOBIECT   = NS.CODOBIECT
                   ), 1, 50)
  WHERE COALESCE( CODMIFIX, 0) &lt;&gt; 0;


  -- legatura cu comenzi de la gestiuni
  FOR V_REC IN (SELECT T.CODLIVRTOT, IL.CODLINIECOMANDA
                FROM TMP_LIVRTOT T, TMP_TRANSFLINK IL
                WHERE T.CODIESINT1 = IL.CODTRANSF1
               )
  LOOP
    UPDATE TMP_LIVRTOT SET CODLINIECOMANDA = V_REC.CODLINIECOMANDA WHERE CODLIVRTOT = V_REC.CODLIVRTOT;
  END LOOP;

  -- legatura cu comenzi clienti de pe care am generat transferuri
  FOR V_REC IN (SELECT T.CODLIVRTOT, T1.CODCOMANDA1
                FROM TMP_LIVRTOT T, TMP_TRANSF1 T1
                WHERE T.CODIESINT1 = T1.CODTRANSF1 and  COALESCE( T1.CODCOMANDA1, 0) &gt; 0
               )
  LOOP
    UPDATE TMP_LIVRTOT SET CODLINIECOMANDA = V_REC.CODCOMANDA1 WHERE CODLIVRTOT = V_REC.CODLIVRTOT;
  END LOOP;

  UPDATE TMP_LIVR1 L1
  SET
  CODLINIECOMANDA = (SELECT CODLINIECOMANDA FROM TMP_LIVRTOT WHERE CODLIVRTOT = L1.CODLIVRTOT limit 1);

  -- MEMOREZ STAREA LA INTRARE A LIVRARILOR
  DELETE FROM TMP_LIVR1_INITIAL;
  INSERT INTO TMP_LIVR1_INITIAL  (SELECT * FROM TMP_LIVR1);


  BEGIN
    SELECT (fnc_GetValConstanta('TipPrefixDenObiect', TO_NUMBER(current_setting('PKG_GLOBALS.ANLUCRU', true),'999999999999999999'), TO_NUMBER(current_setting('PKG_GLOBALS.LUNALUCRU', true),'999999999999999999')))
    INTO TIPPREFIX;
  EXCEPTION WHEN OTHERS THEN
    TIPPREFIX := '1';
  END;

  IF  TIPPREFIX = '2' THEN
    UPDATE TMP_TRANSF1 I1
    SET
    DENOBIECT = SUBSTR( COALESCE( (SELECT CODEXTERN FROM NARTOBJ O WHERE O.CODOBIECT = I1.CODOBIECT), '') || ';' || coalesce(DENOBIECT,''), 1, 200)
    WHERE I1.TIPLINIE IN ('=', 'S', 'V');
  ELSE
    IF  TIPPREFIX = '3' THEN
      UPDATE TMP_TRANSF1 I1
      SET
      DENOBIECT = SUBSTR( COALESCE( (SELECT CODINTERN FROM NARTOBJ O WHERE O.CODOBIECT = I1.CODOBIECT), '') || ';' || coalesce(DENOBIECT,''), 1, 200)
      WHERE I1.TIPLINIE IN ('=', 'S', 'V');
    END IF;
  END IF;

  IF  TIPPREFIX &lt;&gt; '1' THEN
    UPDATE TMP_LIVRTOT L1
    SET
    DENOBIECT = (SELECT DENOBIECT FROM TMP_TRANSF1 I1 WHERE I1.CODTRANSF1 = L1.CODIESINT1);

    UPDATE TMP_NIRSTOC NS
    SET
    DENOBIECT = (SELECT DENOBIECT FROM TMP_TRANSF1 I1 WHERE I1.CODTRANSF1 = NS.CODTRANSF1);
  END IF;

  SELECT count( *) INTO acount FROM tmp_livr1;

  IF  acount = 0 THEN
    FOR v_rec IN (SELECT t1.codtransf1, art.d1, art.d2, art.d3, art.relatieum1
                  FROM tmp_transf1 t1
                      INNER JOIN nartobj obj ON  t1.codobiect   = obj.codobiect
                      INNER JOIN nart    art ON  art.codarticol = obj.codarticol
                  WHERE art.relatieum1 &gt; 0
                 )
    LOOP
      UPDATE tmp_transf1
      SET
      d1 = v_rec.d1,
      d2 = v_rec.d2,
      d3 = v_rec.d3,
      relatieum1 = v_rec.relatieum1
      WHERE
       codtransf1 = v_rec.codtransf1;
  END LOOP;

  UPDATE tmp_transf1
  SET
  cantum1 = CASE
               WHEN RELATIEUM1 IN (1, 7) AND  COALESCE( D1, 0) &lt;&gt; 0                                       THEN CANT / D1
               WHEN RELATIEUM1 IN (2, 8) AND  COALESCE( D1, 0) * COALESCE( D2, 0) &lt;&gt; 0                    THEN CANT / (  COALESCE( D1, 0) * COALESCE( D2, 0))
               WHEN RELATIEUM1 IN (3, 9) AND  COALESCE( D1, 0) * COALESCE( D2, 0) * COALESCE( D3, 0) &lt;&gt; 0 THEN CANT / (  COALESCE( D1, 0) * COALESCE( D2, 0) * COALESCE( D3, 0))
               WHEN RELATIEUM1 IN (4, 10) THEN CANT * COALESCE( D1, 0)
               WHEN RELATIEUM1 IN (5, 11) THEN CANT * COALESCE( D1, 0) * COALESCE( D2, 0)
               WHEN RELATIEUM1 IN (6, 12) THEN CANT * COALESCE( D1, 0) * COALESCE( D2, 0) * COALESCE( D3, 0)
            END ;
  END IF;

--  IF  (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(NULL, 'TRANSF1EXT')) = 1 AND  (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(NULL, 'TMP_TRANSF1EXT')) = 1
--  THEN
--    EXECUTE 'INSERT INTO TMP_TRANSF1EXT SELECT * FROM TRANSF1EXT WHERE CODTRANSF1 IN (SELECT CODTRANSF1 FROM TRANSF1 WHERE CODTRANSF = ' || RECID::varchar || ' ) ';
--  END IF;
  PERFORM PKG_CFGTABLES_EXT_GOTORECORD(aTipDoc);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_sp_postrecords</obj_name>
  <obj_hashval>e0c0b2427ddd537044f23a826fa7ffe0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  V_REC RECORD;
  V_TMP RECORD;
  V_REZ RECORD;
  V_REC_SUB RECORD;
  VCOD             numeric;
  OLDCARNETNIR     numeric := 0;
  OLDNRNIR         numeric := 0;
  OLDCARNETLIVR    numeric := 0;
  OLDNRLIVR        numeric := 0;
  ACARNET          numeric := 0;
  ANUMARDOC        numeric := 0;
  ATIPDOC          numeric := 0;
  AANULAT          numeric := 0;
  AOPERAT          NUMERIC(20) := 0;
  NR               numeric := 0;
  aCODSERIE        numeric := 0;
  NOMSERIE         varchar;
  aCURS            double precision := 1;
  PRET_IMB_MF      numeric;
  VAL_ACHIZ_MF     numeric;
  CANT_IMB_MF      numeric;
  aCodSubunit       numeric;
  aDataDoc          date;
  aDoc              varchar;
  aCodComanda1      numeric;
  aRoot             numeric;
  aDirty            numeric;
  aTipNIR           numeric;
  aPretMat         double precision;
  LivrDinRezTransf character varying;
  aTipNS1          numeric;
  aCodRezervats    numeric;
  aDifCant         double precision;
  aCantRez         double precision;
  aCodNirStocOrig  numeric;
  aCantNir         double precision;
  aProd             numeric;
  aCount            numeric;
  aCont             numeric;
  aContIni          numeric;
  aCodMifix         numeric;
  aprefixdoc        varchar;
  aGestIni          numeric;
  aGest             numeric;
  aCountBCAR        numeric;
  aDelegat          numeric;
  aGestBCAR         numeric;
BEGIN
  --Florin 08.12.2025 - sinc. Oracle
  --Florin 18.06.2025 - sinc. Oracle
  --Florin 16.10.2024 - sinc. Oracle
  --Florin 25.09.2024 - sinc. Oracle
  --Florin 18.04.2024 - sinc. Oracle
  --Florin 20.07.2023 - sinc. Oracle
  --Bogdan 15.06.2023 - corectie extensii
  --Florin 01.06.2023 - monitor
  --Florin 11.05.2023 - fixat 58187
  --Florin 12.04.2023 - sinc. Oracle (11.04.2023)
  --Florin 29.12.2022 - fixat 55514
  --Florin 18.10.2022 - sinc. Oracle
  --Florin 29.06.2022 - sinc. Oracle (28.06.2022)
  --Florin 22.01.2022 - sinc. Oracle (29.12.2021)
  --Florin 07.05.2021 - sinc. Oracle
  --Adina 04.05.2021 - sinc.Oracle din 30.04.2021
  --Florin 24.03.2021 - pkg_miscari_interne_sp_postrecords
  --Adina 25.02.2021 -sinc.Oracle
  --Bogdan 15.02.2021
  --Florin adaugat PKG_MISCARI_INTERNE_ pentru functii din pachet
  --Florin 23.10.2020 - rezolvat tichet #40605
  --Bogdan 18.01.2021
  --Florin 29.01.2021 - LivrDinRezTransf = '1' (inainte era = 1)
  perform pkg_miscari_interne_setct_monitor('MON_13');
  PERFORM PKG_STOC_GENERARE_FACTURI_MAKE_CONFIG_LUNA();

  SELECT (fnc_GetValConstanta ('LivrDinRezTransf', to_number (current_setting ('PKG_GLOBALS.ANLUCRU', true) , '999999999999999999') , to_number (current_setting ('PKG_GLOBALS.LUNALUCRU', true) , '999999999999999999')))
  INTO LivrDinRezTransf;

  select CARNETDOC, NRDOC, TIPDOC, ANULAT, OPERAT,
    SUBUNITATEA, DATADOC, coalesce (PREFIXDOC, '') ||coalesce(NRDOC::varchar,'') || '/' || coalesce(to_char (DATADOC, 'dd.mm.yyyy'),'') ,
    prefixdoc, Delegat, CodGestCmd
  into
    ACARNET, ANUMARDOC, ATIPDOC, aANULAT, AOPERAT,
    aCodSubunit, aDataDoc, ADOC, aprefixdoc,
    aDelegat, aGestBCAR
  from TMP_TRANSF;
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT(aTipDoc);

  UPDATE TMP_NIR TN
  SET DATACREARE = current_timestamp
    WHERE OPERAT = 1 AND DATACREARE IS NULL
    AND NOT EXISTS(SELECT 1 FROM NIR N WHERE N.CODNIR = TN.CODNIR AND N.OPERAT = 1);

  update TMP_NIRSTOC NS
    SET (DATAACHIZ, TG, TIPDOCACHIZ, EUDR_RN, EUDR_VN) = (SELECT DATAACHIZ, TG, TIPDOCACHIZ, EUDR_RN, EUDR_VN FROM NIRSTOC NSP WHERE NSP.CODNIRSTOC = NS.CODNIRSTOCPARINTE)
  where
    CODNIRSTOCPARINTE is not null;

  -- sunt transferuri care se fac cu scopul de a modifica TG-ul pe serie; trebuie sa sincronizez tG-ul din nirstoc si nirser
  FOR V_REC IN (SELECT * FROM TMP_NIRSTOC WHERE COALESCE (TIPSERIE, 0) &gt; 0 AND TG IS NOT NULL) LOOP
    UPDATE TMP_NIRSTOC NS
    SET TG = (SELECT TG FROM TMP_NIRSER NSE WHERE NSE.CODNIRSTOC = V_REC.CODNIRSTOC limit 1)
    WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
  END LOOP;

  aCountBCAR := 0;
  IF OPERATION = 0 THEN   -- UPDATE
    select CODTRANSF INTO RECID from TMP_TRANSF;

    if (select PKG_USERFIRME_ValidPostLog.WME_RESULT
        from PKG_USERFIRME_ValidPostLog (null, to_number (current_setting ('PKG_GLOBALS.USERID', true) , '999999999999999999') , current_setting ('PKG_MISCARI_INTERNE.CT_MONITOR', true)))
    then
      perform pkg_userfirme_postlogcucommit('TRANSF', current_setting ('PKG_GLOBALS.USERNAME', true) , 'M', RECID, current_setting ('PKG_GLOBALS.FIRMANAME', true) ,
                                            aCodSubunit, aDataDoc, aDoc, null,
                                            (select PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT from PKG_GLOBALS_GET_EXE_VERSION (null, null))
                                           );
    end if;

    if aTipDoc = 12 then
      select count (1) INTO aCountBCAR
      from tmp_transf1 t1 inner join bcar b on t1.codtransf1 = b.coddoc1 and b.tipdoc = atipdoc
      WHERE (aDelegat &lt;&gt; b.coddelegat or aGestBCAR &lt;&gt; b.codpartener) and t1.codtransf1 &gt; 0;
    end if;

    -- MASTER TRANSF
    update TRANSF
    set
      (
        CODTRANSF, TIPDOC, ANULAT, BLOCAT,
        OPERAT, PREFIXDOC, CARNETDOC, NRDOC,
        DATADOC, CARNETAE, NRAE, VALDOC,
        TVADOC, OBS, AN, LUNA,
        VALSUPLIM, CONTSUPLIM, TIPREPSUPLIM, DELEGAT,
        CODPART, STORNO, TIPMODIFPRET, MIJLTRANSP,
        NRTRANSP, CODGESTCMD, SUBUNITDEST, LISTAT, REEVALUARE,
        SERIADOC, IDIMPORT, AJUSTVALSTOC, STADIUWMS,
        CodAnaliza, CODAUTO, TipET, IS_ETransp, Corectie
      )
      = (select RECID, TIPDOC, ANULAT, BLOCAT,
          OPERAT, PREFIXDOC, CARNETDOC, NRDOC,
          DATADOC, CARNETAE, NRAE, VALDOC,
          TVADOC, OBS, AN, LUNA,
          VALSUPLIM, CONTSUPLIM, TIPREPSUPLIM, DELEGAT,
          CODPART, STORNO, TIPMODIFPRET, MIJLTRANSP,
          NRTRANSP, CODGESTCMD, SUBUNITDEST, LISTAT, REEVALUARE,
          SERIADOC, IDIMPORT, AJUSTVALSTOC, STADIUWMS,
          CodAnaliza, CODAUTO, TipET, is_eTransp, Corectie
        from TMP_TRANSF)
    where
      CODTRANSF = RECID;

    -- Detail IMBTRANSFLINK
    DELETE from IMBMIFIXLINK IL
    WHERE exists (select CODIMBMIFIXLINK from TMP_IMBMIFIXLINK_INITIAL WHERE CODIMBMIFIXLINK = IL.CODIMBMIFIXLINK)
      and not exists (select CODIMBMIFIXLINK from TMP_IMBMIFIXLINK WHERE CODIMBMIFIXLINK = IL.CODIMBMIFIXLINK);

    -- Detail TRANSFLINK
    DELETE from TRANSFLINK
    WHERE CODTRANSF1 in (select CODTRANSF1 from TRANSF1 WHERE CodTRANSF = RecID and CODTRANSF1 not in (select CODTRANSF1 from TMP_TRANSFLINK));

    -- DETAIL TRANSF1
    FOR V_REC IN (SELECT CODTRANSF1
      FROM TRANSF1
      WHERE CODTRANSF = RECID AND CODTRANSF1 NOT IN (SELECT CODTRANSF1 FROM TMP_TRANSF1)
      ) LOOP
        DELETE FROM TRANSF1 WHERE CODTRANSF1 = V_REC.CODTRANSF1;
        UPDATE BCAR SET TIPDOC = NULL, CODDOC1 = NULL, USERIDBLOCAJ = NULL  WHERE CODDOC1 = V_REC.CODTRANSF1 AND TIPDOC = ATIPDOC;
      END LOOP;

    for V_REC in (select  * from TMP_TRANSF1 order BY INDEXLOCAL) loop
      if coalesce (V_REC.CODTRANSF1, 0) &gt; 0 then
        update TRANSF1
        set
          INDEXLOCAL    = V_REC.INDEXLOCAL,
          TIPLINIE      = V_REC.TIPLINIE,
          CODOBIECTORIG = V_REC.CODOBIECTORIG,
          PARITATEORIG  = V_REC.PARITATEORIG,
          CODCONT       = V_REC.CODCONT,
          UMSEC         = V_REC.UMSEC,
          CODOBIECT     = V_REC.CODOBIECT,
          PU            = V_REC.PU / V_REC.PARITATE,
          PUMAXIMAL     = V_REC.PUMAXIMAL / V_REC.PARITATE,
          CANT          = V_REC.CANT * V_REC.PARITATE,
          TVA           = V_REC.TVA,
          CODMIFIX      = V_REC.CODMIFIX,
          PUVAL         = V_REC.PUVAL,
          CodCentru     = V_REC.CodCentru,
          CODCOMANDA1   = V_REC.CODCOMANDA1,
          CodReteta     = V_REC.CodReteta,
          CODTRANSF1    = V_REC.CODTRANSF1,
          CODANALIZANOD = V_REC.CODANALIZANOD,
          D1            = V_REC.D1,
          D2            = V_REC.D2,
          D3            = V_REC.D3,
          CantUM1       = v_rec.CantUM1,
          CantUM2       = v_rec.CantUM2,
          PRELUAT       = V_REC.PRELUAT,
          CODAUTO       = V_REC.CODAUTO,
          OBS           = V_REC.OBS
        where
          CODTRANSF1 = V_REC.CODTRANSF1;

        perform PKG_CANTAR_UNLOCK_RECORDS (aTipDoc, v_rec.CODTRANSF1);
        PERFORM PKG_BCAR_UNLOCK_RECORDS(ATIPDOC, v_rec.CODTRANSF1);
      else
        select nextval ('SEQ_TRANSF1_CODTRANSF1') INTO VCOD;
        PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('TRANSF1', VCOD, V_REC.CODTRANSF1);

--        if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_TRANSF1EXT')) = 1 then
--          execute ' UPDATE TMP_TRANSF1EXT SET CODTRANSF1 = ' || VCOD::varchar || ' WHERE CODTRANSF1 = ' || V_REC.CODTRANSF1::varchar;
--        end if;

        update tmp_jurnal1 set indexlocal = vCod WHERE indexlocal = v_rec.codtransf1;

        insert into TRANSF1 (CODTRANSF1, CODTRANSF, INDEXLOCAL, TIPLINIE,
            CODOBIECTORIG, PARITATEORIG, CODCONT, UMSEC,
            CODOBIECT, PU, PUMAXIMAL, CANT,
            TVA, CODMIFIX, PUVAL, CodReteta,
            CODCENTRU, CODCOMANDA1, CODANALIZANOD, D1,
            D2, D3, CantUM1, CantUM2,
            PRELUAT, CODAUTO, CODEMULARE1, OBS)
          values (VCOD, RECID, V_REC.INDEXLOCAL, V_REC.TIPLINIE,
            V_REC.CODOBIECTORIG, V_REC.PARITATEORIG, V_REC.CODCONT, V_REC.UMSEC,
            V_REC.CODOBIECT, V_REC.PU / V_REC.PARITATE, V_REC.PUMAXIMAL / V_REC.PARITATE, V_REC.CANT * V_REC.PARITATE,
            V_REC.TVA, V_REC.CODMIFIX, V_REC.PUVAL, v_rec.CodReteta,
            V_REC.CODCENTRU, V_REC.CODCOMANDA1, v_rec.codanalizanod, V_REC.D1,
            V_REC.D2, V_REC.D3, v_rec.CantUM1, v_rec.CantUM2,
            V_REC.PRELUAT, V_REC.CODAUTO, V_REC.CODEMULARE1, V_REC.OBS);

        update TMP_LIVR1        set CODIES1 = VCOD    WHERE CODIES1    = V_REC.CODTRANSF1;
        update TMP_NIRSTOC      set CODTRANSF1 = VCOD WHERE CODTRANSF1 = V_REC.CODTRANSF1;
        update TMP_TRANSFLINK   set CODTRANSF1 = vCod WHERE CODTRANSF1 = v_rec.CODTRANSF1;
        update TMP_IMBMIFIXLINK set CODTRANSF1 = vCod WHERE CODTRANSF1 = v_rec.CODTRANSF1;

        perform PKG_CANTAR_UPDATE_RECORDS (aTipDoc, v_rec.CODTRANSF1, vCOD);
        PERFORM PKG_BCAR_UPDATE_RECORDS(ATIPDOC, v_rec.CodTRANSF1, vCOD);
      end if;

      if aANULAT = 1 then
        update CANTAR set TIPDOC = null, CODDOC1 = NULL WHERE TIPDOC = aTipDoc and CODDOC1 = v_rec.CODTRANSF1;
        UPDATE BCAR SET TIPDOC = NULL, CODDOC1 = NULL WHERE TIPDOC = aTipDoc AND CODDOC1 = v_rec.CODTRANSF1;
      end if;
    end loop;

    for V_REC in (select  * from TMP_TRANSFLINK) loop
      select coalesce (count(*), 0) INTO NR from TRANSFLINK WHERE CODTRANSF1 = v_rec.CODTRANSF1;

      if NR = 0 then
        insert  into TRANSFLINK (CODTRANSF1, CODLINIECOMANDA, CANT)
        values (v_rec.CODTRANSF1, v_rec.CODLINIECOMANDA, v_rec.CANT);
      else
        update TRANSFLINK
        set
        CODTRANSF1      = v_Rec.CODTRANSF1,
        CODLINIECOMANDA = v_rec.CODLINIECOMANDA,
        CANT            = v_Rec.Cant
        where
          CODTRANSF1 = v_rec.CODTRANSF1;
      end if;
    end loop;

    for V_REC in (select  * from TMP_IMBMIFIXLINK) loop
      if V_REC.CODIMBMIFIXLINK &lt; 0 then
        insert  into IMBMIFIXLINK (CODIMBMIFIXLINK, CODTRANSF1, CODINTR1, CODIES1, CODNC1, CODMIFIX, CANT)
        values (nextval ('SEQ_IMBMIFIXLINK_CODIMBMF') , v_rec.CODTRANSF1, v_rec.CODINTR1, V_REC.CODIES1, V_REC.CODNC1, V_REC.CODMIFIX, v_rec.CANT);
      else
        update IMBMIFIXLINK
        set
        CODTRANSF1 = v_Rec.CODTRANSF1,
        CODINTR1   = v_rec.CODINTR1,
        CODIES1    = V_REC.CODIES1,
        CODNC1     = V_REC.CODNC1,
        CODMIFIX   = V_REC.CODMIFIX,
        CANT       = v_Rec.Cant
        where
          CODIMBMIFIXLINK = V_REC.CODIMBMIFIXLINK;
      end if;
    end loop;


    -- DETAIL NIR
    -- ATENTIE LA ORDINEA STERGERILOR DIN DETALII
    DELETE from NIRSER
    WHERE CODNIRSTOC in (select CODNIRSTOC from NIRSTOC WHERE CODNIR in (select CODNIR from NIR WHERE CODTRANSF = RECID))
      and CODNIRSER not in (select CODNIRSER from TMP_NIRSER);

    DELETE from tmp_rezervats;

    for v_rec in (select ns.codnirstoc, ns.codnirstocparinte, t1.codcomanda1, ns.rest
                  from nirstoc ns left join tmp_transf1_initial t1 on t1.codtransf1 = ns.codtransf1
                  where ns.CODNIR in (select CODNIR from NIR WHERE CODTRANSF = RECID)
                    and ns.CODNIRSTOC not in (select CODNIRSTOC from TMP_NIRSTOC))
    loop
      insert into tmp_rezervats (codrezervats, codcomanda1, codnirstoc, codnirser, rest, umsec, codcmdprodmat, rezervatini, codobiect, codcomanda1f, codinventar1)
      select codrezervats, codcomanda1, v_rec.codnirstocparinte, codnirser, rest, umsec, codcmdprodmat, rezervatini, codobiect, codcomanda1f, codinventar1
      from rezervats where codnirstoc = v_rec.codnirstoc and (v_rec.codcomanda1 = codcomanda1 or v_rec.codcomanda1 is null);


      if LivrDinRezTransf = '1' and v_rec.CodNirStocParinte &gt; 0 then
        for v_tmp in (select r.* from rezervats r where r.codnirstoc = v_rec.codnirstoc and (v_Rec.codcomanda1 = r.codcomanda1 or v_rec.codcomanda1 is null)) loop
          DELETE from rezervats WHERE codrezervats = v_tmp.codrezervats;

          begin
            select CodRezervatS into STRICT aCodRezervats
            from rezervats
            where
                codcomanda1 = v_tmp.codcomanda1
                and codnirstoc = v_rec.codnirstocparinte
                and (v_Rec.codcomanda1 = codcomanda1 or v_rec.codcomanda1 is null);
          exception
            when others then
              aCodrezervats := 0;
          end;

          if aCodrezervatS &gt; 0 then
              update rezervats set rest = rest + v_tmp.rest WHERE codrezervats = acodrezervats;

          else
              insert  into rezervats (codrezervats, codcomanda1, codnirstoc, codnirser, rest, umsec, codcmdprodmat, rezervatini, codobiect, codcomanda1f, codinventar1)
              values (nextval ('SEQ_REZERVATS_CODREZERVATS') , v_tmp.codcomanda1, v_rec.codnirstocparinte, v_tmp.codnirser,
                      v_tmp.rest, v_tmp.umsec, v_tmp.codcmdprodmat, v_tmp.rezervatini, v_tmp.codobiect, v_tmp.codcomanda1f, v_tmp.codinventar1);
          end if;
        end loop;
      end if;

      DELETE FROM mastermifix where codnirstoc = v_rec.codnirstoc;

      DELETE from NIRSTOC  WHERE codnirstoc = v_rec.codnirstoc;
      DELETE from NIRSTOC1 WHERE codnirstoc = v_rec.codnirstoc;
    end loop;


    -- INAINTE DE STEREGERE DIN NIR REACTIVEZ NUMERELE
    for V_REC in (select  * from NIR WHERE (CODTRANSF = RECID and CODNIR not in (select CODNIR from TMP_NIR))) loop
      perform PKG_CARNETEDOC_RELEASENUMARDOC (V_REC.CARNETNIR, V_REC.NRNIR);
      perform PKG_CARNETEDOC_COMPACTEAZAINTERVALE (V_REC.CARNETNIR);
    end loop;

    DELETE from NIR WHERE (CODTRANSF = RECID and CODNIR not in (select CODNIR from TMP_NIR));

    -- DETAIL LIVR
    /* ATENTIE LA ORDINEA STERGERILOR DIN DETALII */

    DELETE from LIVRVAL WHERE CODLIVR1 in (select CODLIVR1 from LIVR1
                                           where CODLIVR in (select CODLIVR from LIVR WHERE CODTRANSF = RECID)
                                             and CODLIVR1 not in (select CODLIVR1 from TMP_LIVR1)
                                          );

    DELETE from LIVR1
    WHERE CODLIVR in (select CODLIVR from LIVR WHERE CODTRANSF = RECID)
      and CODLIVR1 not in (select CODLIVR1 from TMP_LIVR1);


    -- INAINTE DE STEREGERE DIN LIVR REACTIVEZ NUMERELE
    for V_REC in (select  * from LIVR WHERE (CODTRANSF = RECID and CODLIVR not in (select CODLIVR from TMP_LIVR))) loop
      perform PKG_CARNETEDOC_RELEASENUMARDOC (V_REC.CARNETLIVR, V_REC.NRLIVR);
      perform PKG_CARNETEDOC_COMPACTEAZAINTERVALE (V_REC.CARNETLIVR);
    end loop;

    DELETE from LIVR WHERE (CODTRANSF = RECID and CODLIVR not in (select CODLIVR from TMP_LIVR));

    for V_REC in (select  * from TMP_LIVR order BY CODLIVR) loop
      if coalesce (V_REC.CODLIVR, 0) &lt; 0 then
        begin
          select nextval ('SEQ_LIVR_CODLIVR') INTO VCOD;

          insert  into LIVR (CODLIVR, CODIES, CODTRANSF, CARNETLIVR, NRLIVR, DATALIVR, OBS, TIPLIVR, ANULAT, BLOCAT, OPERAT)
          values (VCOD, V_REC.CODIES, RECID, V_REC.CARNETLIVR, V_REC.NRLIVR, V_REC.DATALIVR, V_REC.OBS, V_REC.TIPLIVR, V_REC.ANULAT, V_REC.BLOCAT, V_REC.OPERAT);

          update TMP_LIVR1 set CODLIVR = VCOD WHERE CODLIVR = V_REC.CODLIVR;
        end;
      else
        begin
          -- VERIFIC DACA S-AU SCHIMBAT CARNETELE DE DOCUMENTE
          select coalesce (CARNETLIVR, 0) , coalesce (NRLIVR, 0) INTO OLDCARNETLIVR, OLDNRLIVR
          from LIVR
          where
            coalesce (CODLIVR, 0) = coalesce (V_REC.CODLIVR, 0);

          if (OLDCARNETLIVR &lt;&gt; 0) and (OLDNRLIVR &lt;&gt; 0) and (V_REC.CARNETLIVR &lt;&gt; OLDCARNETLIVR or V_REC.NRLIVR   &lt;&gt; OLDNRLIVR)
          then
            perform PKG_CARNETEDOC_RELEASENUMARDOC (OLDCARNETLIVR, OLDNRLIVR);
            perform PKG_CARNETEDOC_COMPACTEAZAINTERVALE (OLDCARNETLIVR);
          end if;

          update LIVR
          set
          CARNETLIVR = V_REC.CARNETLIVR,
          NRLIVR     = V_REC.NRLIVR,
          DATALIVR   = V_REC.DATALIVR,
          OBS        = V_REC.OBS,
          TIPLIVR    = V_REC.TIPLIVR,
          ANULAT     = V_REC.ANULAT,
          BLOCAT     = V_REC.BLOCAT,
          OPERAT     = V_REC.OPERAT
          where
            coalesce (CODLIVR, 0) = coalesce (V_REC.CODLIVR, 0);
        end;
      end if;
    end loop;


    -- DETAIL LIVR1

    -- STERGEREA CELOR CE AU DISPARUT E REZOLVATA MAI SUS

    for V_REC in (select  * from TMP_LIVR1 order BY CODLIVR , CODIES1) loop
      -- IESIRI VALORICE : IN RELATIA LIVRVAL - LIVR1, PARITATEA SE AFLA IN LIVR1 IAR PRETURILE IN LIVRVAL ;
      -- TREBUIE SA TREC PRETURILE DIN LIVRVAL PRIN PARITATEA DIN LIVR1
      update TMP_LIVRVAL LV
      set
      PRETINREG = PRETINREG / V_REC.PARITATE,
      PRETACHIZ = PRETACHIZ / V_REC.PARITATE
      where
        LV.CODLIVR1 = V_REC.CODLIVR1;

      if coalesce (V_REC.CODLIVR1, 0) &gt; 0 then
        update LIVR1
        set
        CODLIVR         = V_REC.CODLIVR,
        CODIES1         = V_REC.CODIES1,
        CODNIRSTOC      = V_REC.CODNIRSTOC,
        CANT            = V_REC.CANT * V_REC.PARITATE,
        CANTREZERVAT    = V_REC.CANTREZERVAT * V_REC.PARITATE,
        CANTUM1         = V_REC.CANTUM1,
        CANTUM2         = V_REC.CANTUM2,
        UMSEC           = V_REC.UMSEC,
        CODCERTIF       = V_REC.CODCERTIF,
        CONTINTERMED    = V_REC.CONTINTERMED,
        CODPROIECT      = V_REC.CODPROIECT,
        CODLIVR1PARINTE = V_REC.CODLIVR1PARINTE,
        CODPRODCOMP     =  V_REC.CODPRODCOMP
        where
          CODLIVR1 = V_REC.CODLIVR1;
      else
        select nextval ('SEQ_LIVR1_CODLIVR1') INTO VCOD;

        update TMP_LIVRVAL set CODLIVR1 = VCOD WHERE CODLIVR1 = V_REC.CODLIVR1;

        update TMP_LIVR1 set CODLIVR1 = VCOD WHERE CODLIVR1 = V_REC.CODLIVR1;

        insert into LIVR1 (CODLIVR1, CODLIVR, CODIES1, CODINTR1, CODNIRSTOC, CANT, CANTREZERVAT, CANTUM1, CANTUM2, CODNIRSER, PMP, PMPDOC,
                           PMPVALUTA, PMPVALUTADOC, UMSEC, CODCERTIF, CONTINTERMED, CODPROIECT, CODLIVR1PARINTE, CODPRODCOMP)
        values (VCOD, V_REC.CODLIVR, V_REC.CODIES1, V_REC.CODINTR1, V_REC.CODNIRSTOC, V_REC.CANT * V_REC.PARITATE, V_REC.CANTREZERVAT * V_REC.PARITATE, V_REC.CANTUM1,
                V_REC.CANTUM2, V_REC.CODNIRSER, V_REC.PMP, V_REC.PMPDOC, V_REC.PMPVALUTA, V_REC.PMPVALUTADOC, V_REC.UMSEC, V_REC.CODCERTIF,
                V_REC.CONTINTERMED, V_REC.CODPROIECT, V_REC.CODLIVR1PARINTE, V_REC.CODPRODCOMP );

        update TMP_NIRSTOC set CODLIVR1 = VCOD WHERE CODLIVR1 = V_REC.CODLIVR1;
      end if;
    end loop;


    for V_REC in (select  * from TMP_LIVRVAL) loop
      if V_REC.CODLIVRVAL &lt; 0 then
        insert  into LIVRVAL (CODLIVRVAL, CODLIVR1, CODOBIECT, CODIOART, GEST, PRETINREG, PRETACHIZ, TVANEEX)
        values (nextval ('SEQ_LIVRVAL_CODLIVRVAL') , V_REC.CODLIVR1, V_REC.CODOBIECT, V_REC.CODIOART, V_REC.GEST, V_REC.PRETINREG, V_REC.PRETACHIZ, V_REC.TVANEEX);
      else
        update LIVRVAL
        set
        CODLIVR1  = V_REC.CODLIVR1,
        CODOBIECT = V_REC.CODOBIECT,
        CODIOART  = V_REC.CODIOART,
        GEST      = V_REC.GEST,
        PRETINREG = V_REC.PRETINREG,
        PRETACHIZ = V_REC.PRETACHIZ,
        TVANEEX   = V_REC.TVANEEX
        where
          CODLIVRVAL = V_REC.CODLIVRVAL;
      end if;
    end loop;

    -- ACTUALIZEZ STOCURILE DE PE NIR-URILE DIN CARE LIVREZ;
    update NIRSTOC NS
    set
    REST    = (select PKG_INTRARI_GET_REST_STOC.WME_RESULT     from PKG_INTRARI_GET_REST_STOC     (null, NS.CODNIR, NS.CODNIRSTOC, NS.CANTNIR)) ,
    RESTUM1 = (select PKG_INTRARI_GET_REST_STOC_UM1.WME_RESULT from PKG_INTRARI_GET_REST_STOC_UM1 (null, NS.CODNIR, NS.CODNIRSTOC, NS.CANTUM1)) ,
    RESTUM2 = (select PKG_INTRARI_GET_REST_STOC_UM2.WME_RESULT from PKG_INTRARI_GET_REST_STOC_UM2 (null, NS.CODNIR, NS.CODNIRSTOC, NS.CANTUM2))
    where
      NS.CODNIRSTOC in (select CODNIRSTOC from TMP_LIVR1 UNION select CODNIRSTOC from TMP_LIVR1_INITIAL);

    update NIRSER NS
    set
    REST    = (select PKG_INTRARI_GET_REST_STOC_SERIE.WME_RESULT
               from PKG_INTRARI_GET_REST_STOC_SERIE (null,
                                                     (select CODNIR from NIRSTOC WHERE CODNIRSTOC = NS.CODNIRSTOC) ,
                                                     NS.CODNIRSER, NS.CANTNIR)
              ) ,
    RESTUM1 = (select PKG_INTRARI_GET_REST_STOC_SERIE_UM1.WME_RESULT
               from PKG_INTRARI_GET_REST_STOC_SERIE_UM1 (null,
                                                         (select CODNIR from NIRSTOC WHERE CODNIRSTOC = NS.CODNIRSTOC) ,
                                                         NS.CODNIRSER, NS.CANTUM1)
              ) ,
    RESTUM2 = (select PKG_INTRARI_GET_REST_STOC_SERIE_UM2.WME_RESULT
               from PKG_INTRARI_GET_REST_STOC_SERIE_UM2 (null,
                                                         (select CODNIR from NIRSTOC WHERE CODNIRSTOC = NS.CODNIRSTOC) ,
                                                         NS.CODNIRSER, NS.CANTUM2)
              )
    where
      NS.CODNIRSTOC in (select CODNIRSTOC from TMP_LIVR1 UNION select CODNIRSTOC from TMP_LIVR1_INITIAL);


    -- DETAIL NIR
    -- ATENTIE LA ORDINEA STERGERILOR DIN DETALII
    for V_REC in (select  * from TMP_NIR order BY CODNIR) loop
      if (coalesce (V_REC.CODNIR, 0) &lt; 0) then
        begin
          select nextval ('SEQ_NIR_CODNIR') INTO VCOD;

          insert into NIR (CODNIR, CODINTR, CODTRANSF, CARNETNIR, NRNIR, DATANIR, GEST, OBS, TIPNIR, ANULAT, BLOCAT, OPERAT, USERID, DATACREARE)
          values (VCOD, V_REC.CODINTR, RECID, V_REC.CARNETNIR, V_REC.NRNIR, V_REC.DATANIR, V_REC.GEST, V_REC.OBS,
              V_REC.TIPNIR, V_REC.ANULAT, V_REC.BLOCAT, V_REC.OPERAT,
              case
                when coalesce (V_REC.OPERAT, 0) = 1 then to_number (current_setting ('PKG_GLOBALS.USERID', true) , '999999999999999999')
                else coalesce (V_REC.USERID, 0)
              END, CURRENT_DATE);

          update TMP_NIRSTOC set CODNIR = VCOD WHERE CODNIR = V_REC.CODNIR;
        end;
      else
        begin
          -- VERIFIC DACA S-AU SCHIMBAT CARNETELE DE DOCUMENTE
          select coalesce (CARNETNIR, 0) , coalesce (NRNIR, 0) INTO OLDCARNETNIR, OLDNRNIR
          from NIR WHERE coalesce (CODNIR, 0) = coalesce (V_REC.CODNIR, 0);

          if (OLDCARNETNIR &lt;&gt; 0) and (OLDNRNIR &lt;&gt; 0) and (V_REC.CARNETNIR &lt;&gt; OLDCARNETNIR or V_REC.NRNIR &lt;&gt; OLDNRNIR)
          then
            perform PKG_CARNETEDOC_RELEASENUMARDOC (OLDCARNETNIR, OLDNRNIR);
            perform PKG_CARNETEDOC_COMPACTEAZAINTERVALE (OLDCARNETNIR);
          end if;

          update NIR
          set
          CARNETNIR = V_REC.CARNETNIR,
          NRNIR     = V_REC.NRNIR,
          DATANIR   = V_REC.DATANIR,
          GEST      = V_REC.GEST,
          OBS       = V_REC.OBS,
          TIPNIR    = V_REC.TIPNIR,
          ANULAT    = V_REC.ANULAT,
          BLOCAT    = V_REC.BLOCAT,
          OPERAT    = V_REC.OPERAT,
          USERID    = case
                        when coalesce (V_REC.OPERAT, 0) = 1 and coalesce (OPERAT, 0) = 0 then to_number (current_setting ('PKG_GLOBALS.USERID', true) , '999999999999999999')
                        else coalesce (V_REC.USERID, 0)
                      end
          where
            coalesce (CODNIR, 0) = coalesce (V_REC.CODNIR, 0);
        end;
      end if;
    end loop;

    -- DETAIL NIRSTOC
    for V_REC in (select  NS.*, T1.CODCOMANDA1
                  from TMP_NIRSTOC NS LEFT JOIN TRANSF1 T1 ON T1.CODTRANSF1 = NS.CODTRANSF1
                  order BY CODNIRSTOC
                 )
    loop
      if V_REC.CODNIRSTOC &gt; 0 then
        if LivrDinRezTransf = '1' OR current_setting('pkg_miscari_interne.v$Session_LivrDinRezTransf ', true) = '1' then
          begin
            select ns.cantnir - v_rec.cantnir INTO aDifCant
            from nirstoc ns
            where ns.codnirstoc = v_rec.codnirstoc;
          exception
          when others then
            aDifCant := 0;
          end;

          if aDifCant &lt;&gt; 0 then
            begin
              select coalesce (ns1.tipdoc, 0) , ns1.codnirstocorig INTO aTipNS1, aCodNirStocOrig
              from nirstoc1 ns1
              where ns1.codnirstoc = v_rec.codnirstoc;
            exception
            when others then
              aTipNS1         := 0;
              aCodNirStocOrig := 0;
            end;

            if aDifCant &lt; 0 then
              for v_tmp in (select r.*
                            from rezervats r
                            where r.codnirstoc = v_rec.codnirstoc and (v_Rec.codcomanda1 = r.codcomanda1 or v_rec.codcomanda1 is null)
                           )
              loop
                update rezervats
                set
                rezervatini = rezervatini - abs (aDifCant) ,
                rest        = rest - abs (aDifCant)
                where
                  codrezervats = v_tmp.codrezervats;

                if v_tmp.codcomanda1 &gt; 0 then
                  begin
                    select CodRezervatS INTO aCodRezervats
                    from rezervats
                    where codcomanda1 = v_tmp.codcomanda1 and codnirstoc = v_rec.codnirstocparinte;
                  exception
                  when others then
                    aCodrezervats := 0;
                  end;

                  if aCodrezervatS &gt; 0 then
                    update rezervats
                    set
                    rezervatini = rezervatini + abs (aDifCant) ,
                    rest        = rest + abs (aDifCant)
                    where codrezervats = acodrezervats;
                  else
                    insert  into rezervats (codrezervats, codcomanda1, codnirstoc, codnirser, rest, umsec, codcmdprodmat, rezervatini,
                                            codobiect, codcomanda1f, codinventar1)
                      values (nextval ('SEQ_REZERVATS_CODREZERVATS') , v_tmp.codcomanda1, v_rec.codnirstocparinte, v_tmp.codnirser,
                              abs (aDifCant) , v_tmp.umsec, v_tmp.codcmdprodmat, abs (aDifCant) ,
                              v_tmp.codobiect, v_tmp.codcomanda1f, v_tmp.codinventar1);
                  end if;
                end if;
              end loop;
            else
              for v_tmp in (select r.*
                            from rezervats r
                            where r.codnirstoc = v_rec.codnirstoc and (v_Rec.codcomanda1 = r.codcomanda1 or v_rec.codcomanda1 is null)
                           )
              loop
                update rezervats
                set
                rezervatini = rezervatini + abs (aDifCant) ,
                rest        = rest + abs (aDifCant)
                where codrezervats = v_tmp.codrezervats;

                if v_tmp.codcomanda1 &gt; 0 then
                  begin
                    select CodRezervatS INTO aCodRezervats
                    from rezervats
                    where codcomanda1 = v_tmp.codcomanda1 and codnirstoc = v_rec.codnirstocparinte;
                  exception
                  when others then
                    aCodrezervats := 0;
                  end;

                  if aCodrezervatS &gt; 0 then
                    update rezervats
                    set
                    rezervatini = rezervatini - abs (aDifCant) ,
                    rest        = rest - abs (aDifCant)
                    where codrezervats = acodrezervats;
                  end if;
                end if;
              end loop;
            end if;
          end if;
        end if;

        update NIRSTOC
        set
        CODNIR            = V_REC.CODNIR,
        CODINTR1          = V_REC.CODINTR1,
        CODTRANSF1        = V_REC.CODTRANSF1,
        CODNIRSTOCPARINTE = V_REC.CODNIRSTOCPARINTE,
        CANTNIR           = V_REC.CANTNIR * V_REC.PARITATE,
        CANTUM1           = V_REC.CANTUM1,
        CANTUM2           = V_REC.CANTUM2,
        CANTFURN          = V_REC.CANTFURN * V_REC.PARITATE,
        UMSEC             = V_REC.UMSEC,
        CODOBIECT         = V_REC.CODOBIECT,
        CODIOART          = coalesce (V_REC.CODIOART, 0) ,
        Pret              = round ( (v_rec.Pret / v_rec.Paritate) ::numeric, ( (select PKG_INTRARI_ZECIMALEPRET.WME_RESULT from PKG_INTRARI_ZECIMALEPRET (null, 7 - coalesce (V_REC.ROTLEI, 0)))) ::int) ,
        ROTLEI            = V_REC.ROTLEI,
        ROTVALUTA         = V_REC.ROTVALUTA,
        CODLOCATIE        = V_REC.CODLOCATIE,
        Adaos             = coalesce (v_rec.Adaos, 0) / v_rec.Paritate,
        TVA               = V_REC.TVA,
        TIPSERIE          = V_REC.TIPSERIE,
        CODLIVR1          = V_REC.CODLIVR1,
        REST              = (select PKG_INTRARI_GET_REST_STOC.WME_RESULT from PKG_INTRARI_GET_REST_STOC (null, V_REC.CODNIR, V_REC.CODNIRSTOC, V_REC.CANTNIR * V_REC.PARITATE)) ,
        RESTUM1           = (select PKG_INTRARI_GET_REST_STOC_UM1.WME_RESULT from PKG_INTRARI_GET_REST_STOC_UM1 (null, V_REC.CODNIR, V_REC.CODNIRSTOC, V_REC.CANTUM1)) ,
        RESTUM2           = (select PKG_INTRARI_GET_REST_STOC_UM2.WME_RESULT from PKG_INTRARI_GET_REST_STOC_UM2 (null, V_REC.CODNIR, V_REC.CODNIRSTOC, V_REC.CANTUM2)) ,
        PROCENTADAOS      = V_REC.PROCENTADAOS,
        Supliment         = V_REC.Supliment,
        TG                = V_REC.TG,
        PUMAXIMAL         = V_REC.PUMAXIMAL,
        FURN              = V_REC.FURN,
        CODGESTPROD       = V_REC.CODGESTPROD,
        SUBUNITATEA       = V_REC.SUBUNITATEA,
        DATAACHIZ         = V_REC.DATAACHIZ,
        TIPDOCACHIZ       = V_REC.TIPDOCACHIZ,
        DISCLIKISTOC      = V_REC.DISCLIKISTOC,
        D1                = V_REC.D1,
        D2                = V_REC.D2,
        D3                = V_REC.D3,
        PUVAL             = V_REC.PUVAL,
        PROVIZION         = V_REC.PROVIZION,
        SERIELOT          = V_REC.SERIELOT,
        EUDR_RN           = V_REC.EUDR_RN,
        EUDR_VN           = V_REC.EUDR_VN
        where
          CODNIRSTOC = V_REC.CODNIRSTOC;
      else
        select nextval ('SEQ_NIRSTOC_CODNIRSTOC') INTO VCOD;

        update TMP_NIRSTOC set CODNIRSTOC = VCOD WHERE CODNIRSTOC = V_REC.CODNIRSTOC;

        update TMP_NIRSER set CODNIRSTOC = VCOD WHERE CODNIRSTOC = V_REC.CODNIRSTOC;

        INSERT INTO NIRSTOC( CODNIRSTOC, CODNIR, CODINTR1, CODTRANSF1, CODNIRSTOCPARINTE, CANTNIR, CANTUM1, CANTUM2, CANTFURN, UMSEC,  CODOBIECT, CODIOART, PRET, ROTLEI, ROTVALUTA, CODLOCATIE, ADAOS, TVA, TIPSERIE, CODLIVR1, REST, RESTUM1, RESTUM2, PROCENTADAOS, Supliment, TG, PUMAXIMAL, FURN, DATAACHIZ, TIPDOCACHIZ, CODGESTPROD, SUBUNITATEA, DISCLIKISTOC, D1, D2, D3, PUVAL, PROVIZION, SERIELOT, EUDR_RN, EUDR_VN )
        values (VCOD, V_REC.CODNIR, V_REC.CODINTR1, V_REC.CODTRANSF1,
            V_REC.CODNIRSTOCPARINTE, V_REC.CANTNIR * V_REC.PARITATE, V_REC.CANTUM1, V_REC.CANTUM2,
            V_REC.CANTFURN                         * V_REC.PARITATE, V_REC.UMSEC, V_REC.CODOBIECT, coalesce (V_REC.CODIOART, 0) ,
            round ( (v_rec.Pret / v_rec.Paritate) ::numeric, ( (   select PKG_INTRARI_ZECIMALEPRET.WME_RESULT
              from PKG_INTRARI_ZECIMALEPRET (null, 7 - coalesce (V_REC.ROTLEI, 0)))) ::int) , V_REC.ROTLEI, V_REC.ROTVALUTA, V_REC.CODLOCATIE,
            coalesce (V_REC.ADAOS, 0) / V_REC.PARITATE, V_REC.TVA, V_REC.TIPSERIE, V_REC.CODLIVR1, (   select PKG_INTRARI_GET_REST_STOC.WME_RESULT
              from PKG_INTRARI_GET_REST_STOC (null, V_REC.CODNIR, V_REC.CODNIRSTOC, V_REC.CANTNIR * V_REC.PARITATE)) , (   select PKG_INTRARI_GET_REST_STOC_UM1.WME_RESULT
              from PKG_INTRARI_GET_REST_STOC_UM1 (null, V_REC.CODNIR, V_REC.CODNIRSTOC, V_REC.CANTUM1)) , (   select PKG_INTRARI_GET_REST_STOC_UM2.WME_RESULT
              from PKG_INTRARI_GET_REST_STOC_UM2 (null, V_REC.CODNIR, V_REC.CODNIRSTOC, V_REC.CANTUM2)) , V_REC.PROCENTADAOS, V_REC.Supliment, V_REC.TG,
            V_REC.PUMAXIMAL, V_REC.FURN, V_REC.DATAACHIZ, V_REC.TIPDOCACHIZ,
            V_REC.CODGESTPROD, V_REC.SUBUNITATEA, V_REC.DISCLIKISTOC, V_REC.D1,
            V_REC.D2, V_REC.D3, V_REC.PUVAL, V_REC.PROVIZION,
            V_REC.SERIELOT,
            V_REC.EUDR_RN,
            V_REC.EUDR_VN);

        if atipdoc = 13 and current_setting ('PKG_MISCARI_INTERNE.vSkipMifixAut', true) = 'false' then
          select count(*) INTO aCount from mastermifix WHERE codnirstoc = v_rec.codnirstocparinte;

          if aCount &gt; 0 then
            select ioal.cont INTO acont
            from tmp_ioart_luna ioal
            where ioal.codioart = v_rec.codioart;

            select ioal.cont INTO acontini
            from tmp_ioart_luna  ioal inner join nirstoc ns on ns.codioart = ioal.codioart
            where ns.codnirstoc = v_rec.codnirstocparinte;

            if acont = acontini
              and (select pkg_categconst_ESTEIMBUNATATIREMIFIX.WME_RESULT from pkg_categconst_ESTEIMBUNATATIREMIFIX (null, acont)) &gt; 0
            then
              begin
                select codmifix INTO acodmifix
                from mifix1
                where
                  codnirstoc = v_rec.codnirstocparinte
                  and anstart * 12 + lunastart = (select pkg_globals_GetANLUCRU.WME_RESULT from pkg_globals_GetANLUCRU (null, null)) * 12 + (select pkg_globals_GetLUNALUCRU.WME_RESULT from pkg_globals_GetLUNALUCRU (null, null));
              exception
              when others then
                acodmifix := 0;
              end;

              if acodmifix &gt; 0 then
                select count(*) INTO aCount
                from mifix1
                where
                  codmifix = acodmifix
                  and anstart * 12 + lunastart = (select pkg_globals_GetANLUCRU.WME_RESULT from pkg_globals_GetANLUCRU (null, null)) * 12 + (select pkg_globals_GetLUNALUCRU.WME_RESULT from pkg_globals_GetLUNALUCRU (null, null));

                if aCount &gt; 0 then
                  update mifix1
                  set
                  codnirstoc = v_rec.codnirstoc,
                  pret       = V_REC.PRET
                  where
                    codnirstoc = v_rec.codnirstoc
                    and anstart * 12 + lunastart = (select pkg_globals_GetANLUCRU.WME_RESULT from pkg_globals_GetANLUCRU (null, null)) * 12 + (select pkg_globals_GetLUNALUCRU.WME_RESULT from pkg_globals_GetLUNALUCRU (null, null));

                  insert into mastermifix (codnirstoc, codclasif, duratan, duratanf, duratang, codanaliza)
                  select v_rec.codnirstoc, m.codclasif, m.duratan, m.duratanf, m.duratang, m.codanaliza
                  from mastermifix m
                  where m.codnirstoc = v_rec.codnirstocparinte;

                  select nir.gest INTO agestini
                  from nirstoc ns inner join nir on nir.codnir = ns.codnir
                  where ns.codnirstoc = v_rec.codnirstocparinte;

                  select nir.gest INTO agest
                  from nirstoc ns inner join nir on nir.codnir = ns.codnir
                  where ns.codnirstoc = v_rec.codnirstoc;

                  insert  into fisamf (codfisamf, codmifix, codoperatie, dataoperatie, gestsursa, gestdest, preti, prete, prefixdoc, nrdoc, cant, coddoc1, tipdoc)
                  values (nextval ('SEQ_FISAMF_CODFISAMF') , acodmifix, 3, adatadoc, agestini, agest, v_rec.pretinitial, v_rec.pret,
                          aprefixdoc, anumardoc, V_REC.CANTNIR * V_REC.PARITATE, v_rec.codtransf1, atipdoc);
                end if;
              end if;
            end if;
          end if;
        end if;

        aRoot := (select PKG_LIST_BASE_UTILS_GETCODNIRSTOC_ORIG.WME_RESULT from PKG_LIST_BASE_UTILS_GETCODNIRSTOC_ORIG (null, VCOD));

        begin
          select nir.tipnir, coalesce (ns.pret, 0) - coalesce (ns.adaos, 0) ,
                 CASE when nir.tipnir = 7 then 1 else 0 END ,
                 coalesce (i1.codcmdint1, 0) ,
                 CASE when nir.tipnir = 7 and c1.codobiect = i1.codobiect then 1 else 0 end
          INTO
            aTipNir, aPretMat, aDirty, aCodComanda1, aProd
          from nirstoc ns
            inner join nir        on nir.codnir = ns.codnir
            left join intrari1 i1 on ns.codintr1 = i1.codintr1
            left join comanda1 c1 on c1.codcomanda1 = i1.codcmdint1
          where
            ns.codnirstoc = aRoot;

          insert  into NIRSTOC1 (CODNIRSTOC, CODNIRSTOCORIG, TIPDOC, PRETMAT, DIRTY, DINSTOC, CODCOMANDA1)
          values (VCOD, aRoot, aTIPNIR, aPretMat, aDirty,
                  CASE when aTIPNIR = 7 and aProd = 1 then 0 else 1 end ,
                  CASE when aTIPNIR = 7 and aProd = 1 then aCodComanda1 else NULL end);
        exception
        when others then
          aRoot := 0;
        end;

        if atipdoc = 12 and (LivrDinRezTransf = '1' OR current_setting ('pkg_miscari_interne.v$Session_LivrDinRezTransf ', true) = '1' ) then
          aDifCant := V_REC.CANTNIR * COALESCE(V_REC.PARITATE,1);
          select count(*) INTO acount from rezervats WHERE codnirstoc = v_rec.codnirstocparinte and rest &gt; 0;

          if acount &gt; 0 then
            for v_tmp in (select * from rezervats WHERE codnirstoc = v_rec.codnirstocparinte and rest &gt; 0 and (v_Rec.codcomanda1 = codcomanda1 or v_rec.codcomanda1 is null))
            loop
              aCantRez      := v_tmp.rest;
              acodrezervats := v_tmp.codrezervats;

              if aDifCant &lt; aCantRez then
                insert into rezervats (codrezervats, codcomanda1, codnirstoc, codnirser, rest, umsec, codcmdprodmat,
                                       rezervatini, codobiect, codcomanda1f, codinventar1)
                values (nextval('seq_rezervats_codrezervats'), v_tmp.codcomanda1, vcod, v_tmp.codnirser, aDifCant, v_tmp.umsec, v_tmp.codcmdprodmat,
                        V_REC.CANTNIR * V_REC.PARITATE, v_tmp.codobiect, v_tmp.codcomanda1f, v_tmp.codinventar1);
              else
                insert into rezervats (codrezervats, codcomanda1, codnirstoc, codnirser, rest, umsec, codcmdprodmat, rezervatini,
                                       codobiect, codcomanda1f, codinventar1)
                values (nextval('seq_rezervats_codrezervats'), v_tmp.codcomanda1, vcod, v_tmp.codnirser, aCantRez, v_tmp.umsec, v_tmp.codcmdprodmat, aCantRez,
                        v_tmp.codobiect, v_tmp.codcomanda1f, v_tmp.codinventar1);
              end if;

              if aDifCant &lt; aCantRez then
                update rezervats
                set
                rezervatini = rezervatini - aDifCant,
                rest        = rest - aDifCant
                where codrezervats = acodrezervats;
              else
                DELETE from rezervats WHERE codrezervats = acodrezervats;
              end if;
            end loop;
          else
            for v_rez in (select * from tmp_rezervats WHERE codnirstoc = v_rec.codnirstocparinte limit 1) loop
              insert into rezervats (codrezervats, codcomanda1, codnirstoc, codnirser, rest, umsec, codcmdprodmat, rezervatini, codobiect, codcomanda1f, codinventar1)
              values (nextval('seq_rezervats_codrezervats'), v_rez.codcomanda1, v_rec.codnirstocparinte, v_rez.codnirser,
                      abs (aDifCant) , v_rez.umsec, v_rez.codcmdprodmat, abs (aDifCant) , v_rez.codobiect, v_rez.codcomanda1f, v_rez.codinventar1);

              insert into rezervats (codrezervats, codcomanda1, codnirstoc, codnirser, rest, umsec, codcmdprodmat, rezervatini, codobiect, codcomanda1f, codinventar1)
              values (nextval('seq_rezervats_codrezervats'), v_rez.codcomanda1, vcod, v_rez.codnirser,
                      aCantNir - abs (aDifCant) , v_rez.umsec, v_rez.codcmdprodmat, aCantNir - abs (aDifCant), v_rez.codobiect, v_rez.codcomanda1f, v_rez.codinventar1);
            end loop;
          end if;
        end if;
      end if;
    end loop;


    -- DETAIL NIRSER
    for V_REC in (select  * from TMP_NIRSER) loop
      if V_REC.CODSERIE &lt; 0 then   -- serie noua :1; verific daca trebuie sa actualizez si NSERII
        begin
          select coalesce (CODSERIE, 0) INTO aCODSERIE
          from NSERII
          where
            SERIE = V_REC.SERIE and CODOBIECT = (select CODOBIECT from NIRSTOC WHERE CODNIRSTOC = V_REC.CODNIRSTOC);
        exception
        when others then
          aCODSERIE := 0;
        end;

        if coalesce (aCODSERIE, 0) = 0 then
          select nextval ('SEQ_NSERII_CODSERIE') INTO aCODSERIE;

          insert into NSERII (CODSERIE, SERIE, CODOBIECT)
          values (aCODSERIE, V_REC.SERIE, (select CODOBIECT from NIRSTOC WHERE CODNIRSTOC = V_REC.CODNIRSTOC));
        end if;
      else
        aCODSERIE := V_REC.CODSERIE;
        -- verific daca la editare nu a schimbat seria
        select coalesce (SERIE, '') INTO NOMSERIE from NSERII WHERE CODSERIE = aCODSERIE;

        if coalesce (NOMSERIE, '') &lt;&gt; V_REC.SERIE then
          update NSERII set SERIE = V_REC.SERIE WHERE CODSERIE = aCODSERIE;
        end if;
      end if;

      if V_REC.CODNIRSER &lt; 0 then
        select nextval ('SEQ_NIRSER_CODNIRSER') INTO VCOD;

        update TMP_NIRSER set CODNIRSER = VCOD WHERE CODNIRSER = V_REC.CODNIRSER;

        insert  into NIRSER (CODNIRSER, CODNIRSTOC, CODSERIE, CANTNIR, REST, CANTUM1, CANTUM2, RESTUM1,
                             RESTUM2, OBS, CodCertif, DataProd, TG, Stare, DataProd1, TG1, CODPRODUCATOR)
                values (VCOD, V_REC.CODNIRSTOC, aCODSERIE, V_REC.CANTNIR * V_REC.PARITATE,
                (select PKG_INTRARI_GET_REST_STOC_SERIE.WME_RESULT
                 from PKG_INTRARI_GET_REST_STOC_SERIE (null,
                                                       (select CODNIR from NIRSTOC WHERE CODNIRSTOC = v_rec.CODNIRSTOC) ,
                                                       v_Rec.CodNirSer, v_rec.CantNir * V_REC.PARITATE)
                ),
                V_REC.CANTUM1, V_REC.CANTUM2,
                (select PKG_INTRARI_GET_REST_STOC_SERIE_UM1.WME_RESULT
                 from PKG_INTRARI_GET_REST_STOC_SERIE_UM1 (null, (select CODNIR from NIRSTOC WHERE CODNIRSTOC = v_rec.CODNIRSTOC) , v_Rec.CodNirSer, v_rec.CantUM1)
                ),
                (select PKG_INTRARI_GET_REST_STOC_SERIE_UM2.WME_RESULT
                 from PKG_INTRARI_GET_REST_STOC_SERIE_UM2 (null, (select CODNIR from NIRSTOC WHERE CODNIRSTOC = v_rec.CODNIRSTOC) , v_Rec.CodNirSer, v_rec.CantUM2)
                ),
                V_REC.OBS, V_REC.CodCertif, V_REC.DataProd, V_REC.TG, V_REC.Stare, V_REC.DataProd1, V_REC.TG1, V_REC.CODPRODUCATOR);

        update rezervats set codnirser = vcod WHERE codnirstoc = v_rec.codnirstoc;
      else
        update NIRSER
        set
        CODNIRSER = V_REC.CODNIRSER,
        CODNIRSTOC = V_REC.CODNIRSTOC,
        CODSERIE = aCODSERIE,
        CANTNIR = V_REC.CANTNIR * V_REC.PARITATE,
        CANTUM1 = V_REC.CANTUM1,
        CANTUM2 = V_REC.CANTUM2,
        OBS = V_REC.Obs,
        Codcertif = V_REC.Codcertif,
        DataProd = V_REC.DataProd,
        TG = V_REC.TG,
        DataProd1   = V_REC.DataProd1,
        TG1         = V_REC.TG1,
        Stare = V_REC.Stare,
        CODPRODUCATOR = V_REC.CODPRODUCATOR,
        REST    = (select PKG_INTRARI_GET_REST_STOC_SERIE.WME_RESULT
                   from PKG_INTRARI_GET_REST_STOC_SERIE (null,
                                                         (select CODNIR from NIRSTOC WHERE CODNIRSTOC = v_rec.CODNIRSTOC) ,
                                                         v_Rec.CodNirSer, v_rec.CantNir * V_REC.PARITATE)
                  ) ,
        RESTUM1 = (select PKG_INTRARI_GET_REST_STOC_SERIE_UM1.WME_RESULT
                   from PKG_INTRARI_GET_REST_STOC_SERIE_UM1 (null,
                                                             (select CODNIR from NIRSTOC WHERE CODNIRSTOC = v_rec.CODNIRSTOC) ,
                                                             v_Rec.CodNirSer, v_rec.CantUM1)
                  ) ,
        RESTUM2 = (select PKG_INTRARI_GET_REST_STOC_SERIE_UM2.WME_RESULT
                   from PKG_INTRARI_GET_REST_STOC_SERIE_UM2 (null,
                                                             (select CODNIR from NIRSTOC WHERE CODNIRSTOC = v_rec.CODNIRSTOC) ,
                                                             v_Rec.CodNirSer, v_rec.CantUM2)
                  )
        where
          CODNIRSER = V_REC.CODNIRSER;
      end if;
    end loop;

    -- detail JURNAlL1
    DELETE from JURNAl1 WHERE TIPDOC = ATIPDOC and CODDOC = RECID and CODJURNAL1 not in (select CODJURNAL1 from TMP_JURNAl1);

    for V_REC in (select  * from TMP_JURNAL1) loop
      if V_REC.CODJURNAL1 &gt; 0 then
        update JURNAL1
        set
        CODDOC        = V_REC.CODDOC,
        TIPDOC        = V_REC.TIPDOC,
        INDEXLOCAL    = V_REC.INDEXLOCAL,
        CODBAZAD      = V_REC.CODBAZAD,
        ICONTBAZAD    = V_REC.ICONTBAZAD,
        TIPBAZAD      = V_REC.TIPBAZAD,
        CODBAZAC      = V_REC.CODBAZAC,
        ICONTBAZAC    = V_REC.ICONTBAZAC,
        TIPBAZAC      = V_REC.TIPBAZAC,
        CODDESCRD     = V_REC.CODDESCRD,
        ICONTD        = V_REC.ICONTD,
        TIPCONTD      = V_REC.TIPCONTD,
        ANALITICCONTD = V_REC.ANALITICCONTD,
        CODDESCRC     = V_REC.CODDESCRC,
        ICONTC        = V_REC.ICONTC,
        TIPCONTC      = V_REC.TIPCONTC,
        ANALITICCONTC = V_REC.ANALITICCONTC,
        GEST          = V_REC.GEST,
        VALOARE       = V_REC.VALOARE,
        VALOAREV      = V_REC.VALOAREV,
        VALOAREGRUP   = v_rec.VALOAREGRUP,
        OBS           = V_REC.OBS,
        AN            = V_REC.AN,
        LUNA          = V_REC.LUNA,
        DIRTY         = V_REC.DIRTY,
        SUBUNITATEA   = V_REC.SUBUNITATEA,
        CODCENTRU     = v_rec.CODCENTRU,
        DATADOC       = V_REC.DATADOC,
        document      = V_REC.DOCUMENT,
        CODANALIZANOD = V_REC.CODANALIZANOD
        where
          CODJURNAL1 = V_REC.CODJURNAl1;
      else
        insert into JURNAL1 (CODJURNAL1, CODDOC, TIPDOC, INDEXLOCAL,
            CODBAZAD, ICONTBAZAD, TIPBAZAD, CODDESCRD,
            ICONTD, TIPCONTD, ANALITICCONTD, CODBAZAC,
            ICONTBAZAC, TIPBAZAC, CODDESCRC, ICONTC,
            TIPCONTC, ANALITICCONTC, GEST, VALOARE,
            VALOAREV, VALOAREGRUP, OBS, AN,
            LUNA, DIRTY, SUBUNITATEA, CODCENTRU,
            DATADOC, document, CODANALIZANOD)
        values (nextval ('SEQ_JURNAL1_CODJURNAL1') , RECID, V_REC.TIPDOC, V_REC.INDEXLOCAL,
            V_REC.CODBAZAD, V_REC.ICONTBAZAD, V_REC.TIPBAZAD, V_REC.CODDESCRD,
            V_REC.ICONTD, V_REC.TIPCONTD, V_REC.ANALITICCONTD, V_REC.CODBAZAC,
            V_REC.ICONTBAZAC, V_REC.TIPBAZAC, V_REC.CODDESCRC, V_REC.ICONTC,
            V_REC.TIPCONTC, V_REC.ANALITICCONTC, V_REC.GEST, V_REC.VALOARE,
            V_REC.VALOAREV, v_rec.VALOAREGRUP, V_REC.OBS, V_REC.AN,
            V_REC.LUNA, V_REC.DIRTY, V_REC.SUBUNITATEA, v_rec.CODCENTRU,
            V_REC.DATADOC, V_REC.DOCUMENT, V_REC.CODANALIZANOD);
      end if;
    end loop;

    -- detail JURNAL
    DELETE from JURNAL WHERE TIPDOC = ATIPDOC and CODDOC = RECID and CODJURNAL not in (select CODJURNAL from TMP_JURNAl);

    for V_REC in (select  * from TMP_JURNAL) loop
      if V_REC.CODJURNAL &gt; 0 then
        update JURNAL
        set
        CODDOC        = V_REC.CODDOC,
        TIPDOC        = V_REC.TIPDOC,
        INDEXLOCAL    = V_REC.INDEXLOCAL,
        CONTD         = V_REC.CONTD,
        CONTC         = V_REC.CONTC,
        GEST          = V_REC.GEST,
        VALOARE       = V_REC.VALOARE,
        VALOAREV      = V_REC.VALOAREV,
        VALOAREGRUP   = v_rec.VALOAREGRUP,
        OBS           = V_REC.OBS,
        AN            = V_REC.AN,
        LUNA          = V_REC.LUNA,
        SUBUNITATEA   = V_REC.SUBUNITATEA,
        CODCENTRU     = v_rec.CODCENTRU,
        DATADOC       = V_REC.DATADOC,
        document      = V_REC.DOCUMENT,
        CODANALIZANOD = V_REC.CODANALIZANOD
        where
          CODJURNAL = V_REC.CODJURNAl;
      else
        insert  into JURNAL (CODJURNAL, CODDOC, TIPDOC, INDEXLOCAL, CONTD, CONTC, GEST, VALOARE, VALOAREV, VALOAREGRUP, OBS, AN,
                             LUNA, SUBUNITATEA, CODCENTRU, DATADOC, document, CODANALIZANOD)
          values (nextval ('SEQ_JURNAL_CODJURNAL') , RECID, V_REC.TIPDOC, RECID, V_REC.CONTD, V_REC.CONTC, V_REC.GEST, V_REC.VALOARE,
                  V_REC.VALOAREV, v_rec.VALOAREGRUP, V_REC.OBS, V_REC.AN, V_REC.LUNA, V_REC.SUBUNITATEA, v_rec.CODCENTRU, V_REC.DATADOC,
                  V_REC.DOCUMENT, V_REC.CODANALIZANOD);
      end if;
    end loop;

  ELSE   -- INSERT

    select nextval ('SEQ_TRANSF_CODTRANSF') INTO RECID;
    PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('TRANSF', RecId);

    if (select WME_RESULT
        from winmadmin.PKG_USERFIRME_ValidPostLog (null, to_number (current_setting ('PKG_GLOBALS.USERID', true) , '999999999999999999') , current_setting ('PKG_MISCARI_INTERNE.CT_MONITOR', true)))
    then
      perform winmadmin.pkg_userfirme_postlogcucommit ('TRANSF', current_setting ('PKG_GLOBALS.USERNAME', true) , 'A', RECID,
                                                        current_setting ('PKG_GLOBALS.FIRMANAME', true) , aCodSubunit, aDataDoc, aDoc, null,
                                                        (select PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT from PKG_GLOBALS_GET_EXE_VERSION (null, null)));
    end if;

    insert  into TRANSF (CODTRANSF, TIPDOC, ANULAT, BLOCAT,
        OPERAT, PREFIXDOC, CARNETDOC, NRDOC,
        DATADOC, CARNETAE, NRAE, VALDOC,
        TVADOC, OBS, AN, LUNA,
        VALSUPLIM, CONTSUPLIM, TIPREPSUPLIM, DELEGAT,
        CODPART, STORNO, TIPMODIFPRET, SUBUNITATEA,
        userID, datacreare, MIJLTRANSP, NRTRANSP,
        CODGESTCMD, SUBUNITDEST, LISTAT, REEVALUARE, SERIADOC,
        IDIMPORT, AJUSTVALSTOC, STADIUWMS, CODANALIZA,
        CODAUTO, TipET, Is_Etransp, Corectie)
    select RECID, TIPDOC, ANULAT, BLOCAT,
      OPERAT, PREFIXDOC, CARNETDOC, NRDOC,
      DATADOC, CARNETAE, NRAE, VALDOC,
      TVADOC, OBS, AN, LUNA,
      VALSUPLIM, CONTSUPLIM, TIPREPSUPLIM, DELEGAT,
      CODPART, STORNO, TIPMODIFPRET, SUBUNITATEA,
      to_number (current_setting ('PKG_GLOBALS.USERID', true) , '999999999999999999') , current_timestamp, MIJLTRANSP, NRTRANSP,
      CODGESTCMD, SUBUNITDEST, LISTAT, REEVALUARE, SERIADOC,
      IDIMPORT, AJUSTVALSTOC, STADIUWMS, CODANALIZA,
      CODAUTO, TipET, is_etransp, Corectie
    from TMP_TRANSF;

    for V_REC in (select  * from TMP_TRANSF1 order BY INDEXLOCAL) loop
      -- DETAIL TRANSF1
      select nextval ('SEQ_TRANSF1_CODTRANSF1') INTO VCOD;

--      if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_TRANSF1EXT')) = 1 then
--        execute ' UPDATE TMP_TRANSF1EXT SET CODTRANSF1 = ' || VCOD::varchar || ' WHERE CODTRANSF1 = ' || V_REC.CODTRANSF1::varchar;
--      end if;
      PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('TRANSF1', VCOD, v_rec.codtransf1);

      update tmp_jurnal1 set indexlocal = vCod WHERE indexlocal = v_rec.codtransf1;

      insert  into TRANSF1 (CODTRANSF1, CODTRANSF, INDEXLOCAL, TIPLINIE,
          CODOBIECTORIG, PARITATEORIG, CODCONT, UMSEC,
          CODOBIECT, PU, PUMAXIMAL, CANT,
          TVA, CODMIFIX, PUVAL, CodReteta,
          CODCENTRU, CODCOMANDA1, CODANALIZANOD, D1,
          D2, D3, CANTUM1, CANTUM2,
          PRELUAT, CODAUTO, CODEMULARE1, OBS)
        values (VCOD, RECID, V_REC.INDEXLOCAL, V_REC.TIPLINIE,
          V_REC.CODOBIECTORIG, V_REC.PARITATEORIG, V_REC.CODCONT, V_REC.UMSEC,
          V_REC.CODOBIECT, V_REC.PU / V_REC.PARITATE, V_REC.PUMAXIMAL / V_REC.PARITATE, V_REC.CANT * V_REC.PARITATE,
          V_REC.TVA, V_REC.CODMIFIX, V_REC.PUVAL, v_rec.CodReteta,
          V_REC.CODCENTRU, V_REC.CODCOMANDA1, v_rec.codanalizanod, V_REC.D1,
          V_REC.D2, V_REC.D3, v_rec.CANTUM1, v_rec.CANTUM2,
          V_REC.PRELUAT, V_REC.CODAUTO, V_REC.CODEMULARE1, V_REC.OBS);

      update TMP_LIVR1        set CODIES1    = VCOD WHERE CODIES1    = V_REC.CODTRANSF1;
      update TMP_NIRSTOC      set CODTRANSF1 = VCOD WHERE CODTRANSF1 = V_REC.CODTRANSF1;
      update TMP_TRANSFLINK   set CODTRANSF1 = vCod WHERE CODTRANSF1 = v_rec.CODTRANSF1;
      update TMP_IMBMIFIXLINK set CODTRANSF1 = vCod WHERE CODTRANSF1 = v_rec.CODTRANSF1;

      perform PKG_CANTAR_UPDATE_RECORDS (aTipDoc, v_rec.CODTRANSF1, vCOD);
      PERFORM PKG_BCAR_UPDATE_RECORDS(ATIPDOC, v_rec.CodTRANSF1, vCOD);
    end loop;

    insert into TRANSFLINK (CODTRANSF1, CODLINIECOMANDA, CANT) (select CODTRANSF1, CODLINIECOMANDA, CANT from TMP_TRANSFLINK);

    insert  into IMBMIFIXLINK (CODIMBMIFIXLINK, CODTRANSF1, CODINTR1, CODIES1, CODNC1, CODMIFIX, CANT)
    select nextval ('SEQ_IMBMIFIXLINK_CODIMBMF') , CODTRANSF1, CODINTR1, CODIES1, CODNC1, CODMIFIX, CANT
    from TMP_IMBMIFIXLINK;


    -- LIVR
    for V_REC in (select  * from TMP_LIVR order BY CODLIVR) loop
      select nextval ('SEQ_LIVR_CODLIVR') INTO VCOD;

      insert  into LIVR (CODLIVR, CODIES, CODTRANSF, CARNETLIVR, NRLIVR, DATALIVR, OBS, TIPLIVR, ANULAT, BLOCAT, OPERAT)
      values (VCOD, V_REC.CODIES, RECID, V_REC.CARNETLIVR, V_REC.NRLIVR, V_REC.DATALIVR, V_REC.OBS, V_REC.TIPLIVR, V_REC.ANULAT, V_REC.BLOCAT, V_REC.OPERAT);

      update TMP_LIVR1 set CODLIVR = VCOD WHERE CODLIVR = V_REC.CODLIVR;
    end loop;

    -- LIVR1
    for V_REC in (select  * from TMP_LIVR1 order BY CODLIVR1) loop
      -- IESIRI VALORICE : IN RELATIA LIVRVAL - LIVR1, PARITATEA SE AFLA IN LIVR1 IAR PRETURILE IN LIVRVAL ;
      -- TREBUIE SA TREC PRETURILE DIN LIVRVAL PRIN PARITATEA DIN LIVR1
      update TMP_LIVRVAL LV
      set
      PRETINREG = PRETINREG / V_REC.PARITATE,
      PRETACHIZ = PRETACHIZ / V_REC.PARITATE
      where
        LV.CODLIVR1 = V_REC.CODLIVR1;

      select nextval ('SEQ_LIVR1_CODLIVR1') INTO VCOD;

      update TMP_LIVRVAL set CODLIVR1 = VCOD WHERE CODLIVR1 = V_REC.CODLIVR1;
      update TMP_LIVR1   set CODLIVR1 = VCOD WHERE CODLIVR1 = V_REC.CODLIVR1;

      insert  into LIVR1 (CODLIVR1, CODLIVR, CODIES1, CODINTR1,
          CODNIRSTOC, CANT, CANTREZERVAT, CODNIRSER,
          PMP, PMPDOC, PMPVALUTA, PMPVALUTADOC,
          UMSEC, CANTUM1, CANTUM2, CODCERTIF,
          CONTINTERMED, CODPROIECT, CODLIVR1PARINTE, CODPRODCOMP)
      values (VCOD, V_REC.CODLIVR, V_REC.CODIES1, V_REC.CODINTR1,
          V_REC.CODNIRSTOC, V_REC.CANT * V_REC.PARITATE, V_REC.CANTREZERVAT * V_REC.PARITATE, V_REC.CODNIRSER,
          V_REC.PMP, V_REC.PMPDOC, V_REC.PMPVALUTA, V_REC.PMPVALUTADOC,
          V_REC.UMSEC, V_REC.CANTUM1, V_REC.CANTUM2, V_REC.CODCERTIF,
          V_REC.CONTINTERMED, V_REC.CODPROIECT, V_REC.CODLIVR1PARINTE, V_REC.CODPRODCOMP);

      update TMP_NIRSTOC set CODLIVR1 = VCOD WHERE CODLIVR1 = V_REC.CODLIVR1;
    end loop;

    insert  into LIVRVAL (CODLIVRVAL, CODLIVR1, CODOBIECT, CODIOART, GEST, PRETINREG, PRETACHIZ, TVANEEX)
    select nextval ('SEQ_LIVRVAL_CODLIVRVAL') , CODLIVR1, CODOBIECT, CODIOART, GEST, PRETINREG, PRETACHIZ, TVANEEX
    from TMP_LIVRVAL;

    update NIRSTOC NS
    set
    REST    = (select PKG_INTRARI_GET_REST_STOC.WME_RESULT     from PKG_INTRARI_GET_REST_STOC     (null, NS.CODNIR, NS.CODNIRSTOC, NS.CANTNIR)) ,
    RESTUM1 = (select PKG_INTRARI_GET_REST_STOC_UM1.WME_RESULT from PKG_INTRARI_GET_REST_STOC_UM1 (null, NS.CODNIR, NS.CODNIRSTOC, NS.CANTUM1)) ,
    RESTUM2 = (select PKG_INTRARI_GET_REST_STOC_UM2.WME_RESULT from PKG_INTRARI_GET_REST_STOC_UM2 (null, NS.CODNIR, NS.CODNIRSTOC, NS.CANTUM2))
    where
      NS.CODNIRSTOC in (select CODNIRSTOC from TMP_LIVR1);

    update NIRSER NS
    set
    REST    = (select PKG_INTRARI_GET_REST_STOC_SERIE.WME_RESULT
               from PKG_INTRARI_GET_REST_STOC_SERIE (null, (select CODNIR from NIRSTOC WHERE CODNIRSTOC = NS.CODNIRSTOC) , NS.CODNIRSER, NS.CANTNIR)) ,
    RESTUM1 = (select PKG_INTRARI_GET_REST_STOC_SERIE_UM1.WME_RESULT
               from PKG_INTRARI_GET_REST_STOC_SERIE_UM1 (null, (select CODNIR from NIRSTOC WHERE CODNIRSTOC = NS.CODNIRSTOC) , NS.CODNIRSER, NS.CANTUM1)) ,
    RESTUM2 = (select PKG_INTRARI_GET_REST_STOC_SERIE_UM2.WME_RESULT
               from PKG_INTRARI_GET_REST_STOC_SERIE_UM2 (null, (select CODNIR from NIRSTOC WHERE CODNIRSTOC = NS.CODNIRSTOC) , NS.CODNIRSER, NS.CANTUM2))
    where
      NS.CODNIRSTOC in (select CODNIRSTOC from TMP_LIVR1);


    -- DETAIL NIR
    for V_REC in (select  * from TMP_NIR order BY CODNIR) loop
      select nextval ('SEQ_NIR_CODNIR') INTO VCOD;

      insert  into NIR (CODNIR, CODINTR, CODTRANSF, CARNETNIR, NRNIR, DATANIR, GEST, OBS, TIPNIR, ANULAT, BLOCAT, OPERAT)
      values (VCOD, V_REC.CODINTR, RECID, V_REC.CARNETNIR, V_REC.NRNIR, V_REC.DATANIR, V_REC.GEST, V_REC.OBS, V_REC.TIPNIR, V_REC.ANULAT, V_REC.BLOCAT, V_REC.OPERAT);

      update TMP_NIRSTOC set CODNIR = VCOD WHERE CODNIR = V_REC.CODNIR;
    end loop;


    -- DETAIL NIRSTOC
    DELETE from TMP_NIRSTOC_RECOD;  -- folosit la reevaluari

    for V_REC in (select TMP.*, TL.CODLINIECOMANDA, T1.CODCOMANDA1
                  from TMP_NIRSTOC TMP
                       INNER JOIN TRANSF1   T1 ON T1.CODTRANSF1  = TMP.CODTRANSF1
                       left join TRANSFLINK TL on TMP.CODTRANSF1 = TL.CODTRANSF1
                  order BY TMP.CODNIRSTOC
                 )
    loop
      select nextval ('SEQ_NIRSTOC_CODNIRSTOC') INTO VCOD;

      insert into TMP_NIRSTOC_RECOD (CODVECHI, CODNOU) values (V_REC.CODNIRSTOC, VCOD);

      insert  into NIRSTOC (CODNIRSTOC, CODNIR, CODINTR1, CODTRANSF1,
          CODNIRSTOCPARINTE, CANTNIR, CANTUM1, CANTUM2,
          CANTFURN, UMSEC, CODOBIECT, CODIOART,
          PRET, ROTLEI, ROTVALUTA, CODLOCATIE,
          ADAOS, TVA, TIPSERIE, CODLIVR1,
          REST, RESTUM1, RESTUM2, PROCENTADAOS,
          Supliment, TG, PUMAXIMAL, FURN,
          DATAACHIZ, TIPDOCACHIZ, CODGESTPROD, SUBUNITATEA,
          DISCLIKISTOC, D1, D2, D3,
          PUVAL, PROVIZION, SERIELOT, EUDR_RN, EUDR_VN)
      values (VCOD, V_REC.CODNIR, V_REC.CODINTR1, V_REC.CODTRANSF1,
          V_REC.CODNIRSTOCPARINTE, V_REC.CANTNIR * V_REC.PARITATE, V_REC.CANTUM1, V_REC.CANTUM2,
          V_REC.CANTFURN * V_REC.PARITATE, V_REC.UMSEC, V_REC.CODOBIECT, coalesce (V_REC.CODIOART, 0) ,
          round ( (v_rec.Pret / v_rec.Paritate) ::numeric, ( (select PKG_INTRARI_ZECIMALEPRET.WME_RESULT from PKG_INTRARI_ZECIMALEPRET (null, 7 - coalesce (V_REC.ROTLEI, 0)))) ::int) ,
          V_REC.ROTLEI, V_REC.ROTVALUTA, V_REC.CODLOCATIE,
          coalesce (V_REC.ADAOS, 0) / V_REC.PARITATE, V_REC.TVA, V_REC.TIPSERIE, V_REC.CODLIVR1,
          (select PKG_INTRARI_GET_REST_STOC.WME_RESULT     from PKG_INTRARI_GET_REST_STOC (null, V_REC.CODNIR, V_REC.CODNIRSTOC, V_REC.CANTNIR * V_REC.PARITATE)) ,
          (select PKG_INTRARI_GET_REST_STOC_UM1.WME_RESULT from PKG_INTRARI_GET_REST_STOC_UM1 (null, V_REC.CODNIR, V_REC.CODNIRSTOC, V_REC.CANTUM1)) ,
          (select PKG_INTRARI_GET_REST_STOC_UM2.WME_RESULT from PKG_INTRARI_GET_REST_STOC_UM2 (null, V_REC.CODNIR, V_REC.CODNIRSTOC, V_REC.CANTUM2)) ,
          V_REC.PROCENTADAOS, V_REC.Supliment, V_REC.TG,
          V_REC.PUMAXIMAL, V_REC.FURN, V_REC.DATAACHIZ, V_REC.TIPDOCACHIZ,
          V_REC.CODGESTPROD, V_REC.SUBUNITATEA, V_REC.DISCLIKISTOC, V_REC.D1,
          V_REC.D2, V_REC.D3, V_REC.PUVAL, V_REC.PROVIZION,
          V_REC.SERIELOT, V_REC.EUDR_RN, V_REC.EUDR_VN);

      update TMP_NIRSTOC set CODNIRSTOC = VCOD WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
      update TMP_NIRSER  set CODNIRSTOC = VCOD WHERE CODNIRSTOC = V_REC.CODNIRSTOC;

      aRoot := (select PKG_LIST_BASE_UTILS_GETCODNIRSTOC_ORIG.WME_RESULT from PKG_LIST_BASE_UTILS_GETCODNIRSTOC_ORIG (null, VCOD));

      begin
        select nir.tipnir, coalesce (ns.pret, 0) - coalesce (ns.adaos, 0) ,
               CASE when nir.tipnir = 7 then 1 else 0 end ,
               coalesce (i1.codcmdint1, 0) ,
               CASE when nir.tipnir = 7 and c1.codobiect = i1.codobiect then 1 else 0 end
        INTO
          aTipNir, aPretMat, aDirty, aCodComanda1, aProd
        from nirstoc ns
          inner join nir         on nir.codnir     = ns.codnir
          left  join intrari1 i1 on ns.codintr1    = i1.codintr1
          left  join comanda1 c1 on c1.codcomanda1 = i1.codcmdint1
        where
          ns.codnirstoc = aRoot;

        insert  into NIRSTOC1 (CODNIRSTOC, CODNIRSTOCORIG, TIPDOC, PRETMAT, DIRTY, DINSTOC, CODCOMANDA1)
        values (VCOD, aRoot, aTIPNIR, aPretMat, aDirty,
                CASE when aTIPNIR = 7 and aProd = 1 then 0 else 1 end ,
                CASE when aTIPNIR = 7 and aProd = 1 then aCodComanda1 else NULL end);
      exception
      when others then
        aRoot := 0;
      end;

      if atipdoc = 12 and (LivrDinRezTransf = '1' OR current_setting ('pkg_miscari_interne.v$Session_LivrDinRezTransf ', true) = '1') and V_REC.CODLINIECOMANDA is null then
        aDifCant := V_REC.CANTNIR * COALESCE(V_REC.PARITATE,1);
        select count(*) INTO acount from rezervats WHERE codnirstoc = v_rec.codnirstocparinte and rest &gt; 0 and (v_rec.codcomanda1 = codcomanda1 or v_rec.codcomanda1 is null);

        if acount &gt; 0 then
          for v_tmp in (select  * from rezervats WHERE codnirstoc = v_rec.codnirstocparinte and rest &gt; 0 and (v_rec.codcomanda1 = codcomanda1 or v_rec.codcomanda1 is null))
          loop
            aCantRez      := v_tmp.rest;
            acodrezervats := v_tmp.codrezervats;
            if aDifCant &lt; aCantRez then
              insert  into rezervats (codrezervats, codcomanda1, codnirstoc, codnirser, rest, umsec, codcmdprodmat, rezervatini, codobiect, codcomanda1f, codinventar1)
              values (nextval ('SEQ_REZERVATS_CODREZERVATS') , v_tmp.codcomanda1, vcod, v_tmp.codnirser,
                      aDifCant, v_tmp.umsec, v_tmp.codcmdprodmat, aDifCant, v_tmp.codobiect, v_tmp.codcomanda1f, v_tmp.codinventar1);
            else
              insert  into rezervats (codrezervats, codcomanda1, codnirstoc, codnirser, rest, umsec, codcmdprodmat, rezervatini, codobiect, codcomanda1f, codinventar1)
                values (nextval ('SEQ_REZERVATS_CODREZERVATS') , v_tmp.codcomanda1, vcod, v_tmp.codnirser,
                        aCantRez, v_tmp.umsec, v_tmp.codcmdprodmat, aCantRez, v_tmp.codobiect, v_tmp.codcomanda1f, v_tmp.codinventar1);
            end if;

            if aDifCant &lt; aCantRez then
              update rezervats
              set
              rezervatini = rezervatini - aDifCant,
              rest        = rest - aDifCant
              where
                codrezervats = acodrezervats;
            else
              DELETE from rezervats WHERE codrezervats = acodrezervats;
            end if;
          end loop;
        else
          for v_rez in (select  * from tmp_rezervats WHERE codnirstoc = v_rec.codnirstocparinte limit 1) loop
            insert  into rezervats (codrezervats, codcomanda1, codnirstoc, codnirser, rest, umsec, codcmdprodmat, rezervatini, codobiect, codcomanda1f, codinventar1)
            values (nextval ('SEQ_REZERVATS_CODREZERVATS') , v_rez.codcomanda1, v_rec.codnirstocparinte, v_rez.codnirser,
                    abs (aDifCant) , v_rez.umsec, v_rez.codcmdprodmat, abs (aDifCant) , v_rez.codobiect, v_rez.codcomanda1f, v_rez.codinventar1);

            insert  into rezervats (codrezervats, codcomanda1, codnirstoc, codnirser, rest, umsec, codcmdprodmat, rezervatini, codobiect, codcomanda1f, codinventar1)
            values (nextval ('SEQ_REZERVATS_CODREZERVATS') , v_rez.codcomanda1, vcod, v_rez.codnirser,
                    aCantNir - abs (aDifCant) , v_rez.umsec, v_rez.codcmdprodmat, aCantNir - abs (aDifCant) ,
                    v_rez.codobiect, v_rez.codcomanda1f, v_rez.codinventar1);
          end loop;
        end if;
      end if;

      if atipdoc = 13 and current_setting ('PKG_MISCARI_INTERNE.vSkipMifixAut', true) &lt;&gt; 'true' then
        -- modificarile de pret pt imobilizari in curs -- automatizare
        select count(*) INTO aCount from mastermifix WHERE codnirstoc = v_rec.codnirstocparinte;

        if aCount &gt; 0 then
          select ioal.cont INTO acont from tmp_ioart_luna ioal WHERE ioal.codioart = v_rec.codioart;

          select ioal.cont INTO acontini from tmp_ioart_luna ioal inner join nirstoc ns on ns.codioart = ioal.codioart WHERE ns.codnirstoc = v_rec.codnirstocparinte;

          if acont = acontini
            and (select pkg_categconst_ESTEIMBUNATATIREMIFIX.WME_RESULT from pkg_categconst_ESTEIMBUNATATIREMIFIX (null, acont))&gt; 0
          then
            begin
              select codmifix INTO acodmifix
              from mifix1
              where
                codnirstoc = v_rec.codnirstocparinte
                and anstart * 12 + lunastart = (select pkg_globals_GetANLUCRU.WME_RESULT from pkg_globals_GetANLUCRU (null, null)) * 12 + (select pkg_globals_GetLUNALUCRU.WME_RESULT from pkg_globals_GetLUNALUCRU (null, null));
            exception
            when others then
              acodmifix := 0;
            end;

            if acodmifix &gt; 0 then
              select count(*) INTO aCount
              from mifix1
              where
                codmifix = acodmifix
                and anstart * 12 + lunastart = (select pkg_globals_GetANLUCRU.WME_RESULT from pkg_globals_GetANLUCRU (null, null)) * 12 + (select pkg_globals_GetLUNALUCRU.WME_RESULT from pkg_globals_GetLUNALUCRU (null, null));

              if aCount &gt; 0 then
                update mifix1
                set
                codnirstoc = vcod,
                pret       = V_REC.PRET
                where
                  codmifix = acodmifix
                  and anstart * 12 + lunastart = (select pkg_globals_GetANLUCRU.WME_RESULT from pkg_globals_GetANLUCRU (null, null)) * 12 + (select pkg_globals_GetLUNALUCRU.WME_RESULT from pkg_globals_GetLUNALUCRU (null, null));

                insert into mastermifix (codnirstoc, codclasif, duratan, duratanf, duratang, codanaliza)
                select vcod, m.codclasif, m.duratan, m.duratanf, m.duratang, m.codanaliza
                from mastermifix m WHERE m.codnirstoc = v_rec.codnirstocparinte;

                select nir.gest INTO agestini
                from nirstoc ns inner join nir on nir.codnir = ns.codnir
                where ns.codnirstoc = v_rec.codnirstocparinte;

                select nir.gest INTO agest
                from nirstoc ns inner join nir on nir.codnir = ns.codnir
                where ns.codnirstoc = vcod;

                insert  into fisamf (codfisamf, codmifix, codoperatie, dataoperatie, gestsursa, gestdest, preti, prete, prefixdoc, nrdoc, cant, coddoc1, tipdoc)
                values (nextval ('SEQ_FISAMF_CODFISAMF') , acodmifix, 3, adatadoc, agestini, agest, v_rec.pretinitial, v_rec.pret,
                        aprefixdoc, anumardoc, V_REC.CANTNIR * V_REC.PARITATE, v_rec.codtransf1, atipdoc);
              end if;
            end if;
          end if;
        end if;
      end if;
    end loop;

    -- DETAIL NIRSER
    for V_REC in (select  * from TMP_NIRSER) loop
      if V_REC.CODSERIE &lt; 0 then  -- serie noua; actualizez si NSERII
        begin
          select coalesce (CODSERIE, 0) INTO aCODSERIE
          from NSERII
          where
            SERIE = V_REC.SERIE
            and CODOBIECT = (select CODOBIECT from NIRSTOC WHERE CODNIRSTOC = V_REC.CODNIRSTOC);
        exception
        when others then
          aCODSERIE := 0;
        end;

        if coalesce (aCODSERIE, 0) = 0 then
          select nextval ('SEQ_NSERII_CODSERIE') INTO aCODSERIE;

          insert  into NSERII (CODSERIE, SERIE, CODOBIECT)
          values (aCODSERIE, V_REC.SERIE, (select CODOBIECT from NIRSTOC WHERE CODNIRSTOC = V_REC.CODNIRSTOC));
        end if;
      else
        aCODSERIE := V_REC.CODSERIE;
        -- verific daca la editare nu a schimbat seria
        begin
          select coalesce (SERIE, '') INTO NOMSERIE from NSERII WHERE CODSERIE = aCODSERIE;
        exception
        when others then
          NOMSERIE := '';
        end;

        if coalesce (NOMSERIE, '') &lt;&gt; V_REC.SERIE then
          update NSERII set SERIE = V_REC.SERIE WHERE CODSERIE = aCODSERIE;
        end if;
      end if;

      select nextval ('SEQ_NIRSER_CODNIRSER') INTO VCOD;

      update TMP_NIRSER set CODNIRSER = VCOD WHERE CODNIRSER = V_REC.CODNIRSER;

      insert  into NIRSER (CODNIRSER, CODNIRSTOC, CODSERIE, CANTNIR, REST, CANTUM1, CANTUM2, RESTUM1, RESTUM2, OBS, CodCertif, DataProd, TG, Stare, DataProd1, TG1)
      values (VCOD, V_REC.CODNIRSTOC, aCODSERIE, V_REC.CANTNIR * V_REC.PARITATE,
              (select PKG_INTRARI_GET_REST_STOC_SERIE.WME_RESULT
               from PKG_INTRARI_GET_REST_STOC_SERIE (null, (select CODNIR from NIRSTOC WHERE CODNIRSTOC = v_rec.CODNIRSTOC) , v_Rec.CodNirSer, v_rec.CantNir * V_REC.PARITATE)) ,
              V_REC.CANTUM1, V_REC.CANTUM2,
              (select PKG_INTRARI_GET_REST_STOC_SERIE_UM1.WME_RESULT
               from PKG_INTRARI_GET_REST_STOC_SERIE_UM1 (null, (select CODNIR from NIRSTOC WHERE CODNIRSTOC = v_rec.CODNIRSTOC) , v_Rec.CodNirSer, v_rec.CantUM1)) ,
              (select PKG_INTRARI_GET_REST_STOC_SERIE_UM2.WME_RESULT
               from PKG_INTRARI_GET_REST_STOC_SERIE_UM2 (null, (select CODNIR from NIRSTOC WHERE CODNIRSTOC = v_rec.CODNIRSTOC) , v_Rec.CodNirSer, v_rec.CantUM2)) ,
              V_REC.OBS, V_REC.CodCertif, V_REC.DataProd, V_REC.TG, V_REC.Stare, V_REC.DataProd1, V_REC.TG1);

      update rezervats set codnirser = vcod WHERE codnirstoc = v_rec.codnirstoc;
    end loop;


    insert  into JURNAL1 (CODJURNAL1, CODDOC, TIPDOC, INDEXLOCAL, CODBAZAD, ICONTBAZAD, TIPBAZAD, CODDESCRD, ICONTD, TIPCONTD, ANALITICCONTD, CODBAZAC,
                          ICONTBAZAC, TIPBAZAC, CODDESCRC, ICONTC, TIPCONTC, ANALITICCONTC, GEST, VALOARE, VALOAREV, VALOAREGRUP, OBS, AN,
                          LUNA, DIRTY, SUBUNITATEA, CODCENTRU, DATADOC, document, CODANALIZANOD)
    (select nextval ('SEQ_JURNAL1_CODJURNAL1') , RECID, TIPDOC, INDEXLOCAL, CODBAZAD, ICONTBAZAD, TIPBAZAD, CODDESCRD, ICONTD, TIPCONTD,
            ANALITICCONTD, CODBAZAC, ICONTBAZAC, TIPBAZAC, CODDESCRC, ICONTC, TIPCONTC, ANALITICCONTC, GEST, VALOARE, VALOAREV, VALOAREGRUP,
            OBS, AN, LUNA, DIRTY, SUBUNITATEA, CODCENTRU, DATADOC, document, CODANALIZANOD
     from TMP_JURNAL1);

    insert  into JURNAL (CODJURNAL, CODDOC, TIPDOC, INDEXLOCAL, CONTD, CONTC, GEST, VALOARE, VALOAREV, VALOAREGRUP, OBS, AN,
                         LUNA, SUBUNITATEA, CODCENTRU, DATADOC, document, CODANALIZANOD)
    (select nextval ('SEQ_JURNAL_CODJURNAL') , RECID, TIPDOC, RECID, CONTD, CONTC, GEST, VALOARE, VALOAREV, VALOAREGRUP, OBS,
            AN, LUNA, SUBUNITATEA, CODCENTRU, DATADOC, document, CODANALIZANOD
     from TMP_JURNAL);
  END IF;  -- end INSERT


  perform pkg_pretprod_CheckNirStoc1ByCodTransf (RecId);

  -- ACTUALIZARE CARNETE DOCUMENTE
  if (to_number (current_setting ('PKG_MISCARI_INTERNE.CARNETDOC_I', true) , '999999999999999999') &lt;&gt; 0)
    and (to_number (current_setting ('PKG_MISCARI_INTERNE.NRDOC_I', true) , '999999999999999999') &lt;&gt; 0)
    and (ACARNET &lt;&gt; to_number (current_setting ('PKG_MISCARI_INTERNE.CARNETDOC_I', true) , '999999999999999999')
         or
         ANUMARDOC &lt;&gt; to_number (current_setting ('PKG_MISCARI_INTERNE.NRDOC_I', true) , '999999999999999999')
        )
  then
    perform PKG_CARNETEDOC_RELEASENUMARDOC (to_number (current_setting ('PKG_MISCARI_INTERNE.CARNETDOC_I', true) , '999999999999999999') , to_number (current_setting ('PKG_MISCARI_INTERNE.NRDOC_I', true) , '999999999999999999'));
    perform PKG_CARNETEDOC_COMPACTEAZAINTERVALE (to_number (current_setting ('PKG_MISCARI_INTERNE.CARNETDOC_I', true) , '999999999999999999'));
  end if;

  perform PKG_CARNETEDOC_SOLVENUMARDOC (ACARNET, (ANUMARDOC) ::character varying);

  for V_REC in (select  * from LIVR WHERE CODTRANSF = RECID) loop
    perform PKG_CARNETEDOC_SOLVENUMARDOC (V_REC.CARNETLIVR, (V_REC.NRLIVR) ::character varying);
  end loop;

  for V_REC in (select  * from NIR WHERE CODTRANSF = RECID) loop
    perform PKG_CARNETEDOC_SOLVENUMARDOC (V_REC.CARNETNIR, (V_REC.NRNIR) ::character varying);
  end loop;

  -- ACTUALIZARE RULAJE CONTURI
  for V_REC in (select  * from TMP_RULAJ) loop
    select count(*) INTO NR
    from NCONTRUL
    where
      CODCONT  = V_REC.CODCONT
      and AN   = to_number (current_setting ('PKG_GLOBALS.ANLUCRU'  , true) , '999999999999999999')
      and LUNA = to_number (current_setting ('PKG_GLOBALS.LUNALUCRU', true) , '999999999999999999');

    if NR = 0 then
      insert  into NCONTRUL (CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, AN, LUNA)
      values (nextval ('SEQ_NCONTRUL_CODCONTRUL') , V_REC.CODCONT, 0, 0, 0, 0, 0, 0, 0, 0, to_number (current_setting ('PKG_GLOBALS.ANLUCRU', true) , '999999999999999999') , to_number (current_setting ('PKG_GLOBALS.LUNALUCRU', true) , '999999999999999999'));
    end if;

    update NCONTRUL
    set
    RULAJCD  = RULAJCD  + (CASE when V_REC.TIP = 'D' then V_REC.VALOARE  else 0 end),
    RULAJCC  = RULAJCC  + (CASE when V_REC.TIP = 'C' then V_REC.VALOARE  else 0 end),
    RULAJVCD = RULAJVCD + (CASE when V_REC.TIP = 'D' then V_REC.VALOAREV else 0 end),
    RULAJVCC = RULAJVCC + (CASE when V_REC.TIP = 'C' then V_REC.VALOAREV else 0 end)
    where
      CODCONT  = V_REC.CODCONT
      and AN   = to_number (current_setting ('PKG_GLOBALS.ANLUCRU'  , true) , '999999999999999999')
      and LUNA = to_number (current_setting ('PKG_GLOBALS.LUNALUCRU', true) , '999999999999999999');

    if coalesce (V_REC.SUBUNITATEA, 0) &lt;&gt; 0 then
      for V_REC_SUB in (select  * from NCONTRUL
                        where
                          CODCONT  = V_REC.CODCONT
                          and AN   = to_number (current_setting ('PKG_GLOBALS.ANLUCRU'  , true) , '999999999999999999')
                          and LUNA = to_number (current_setting ('PKG_GLOBALS.LUNALUCRU', true) , '999999999999999999')
                       )
      loop
        select count(*) INTO NR from NCONTRULSUB WHERE CODCONTRUL = V_REC_SUB.CODCONTRUL and SUBUNITATEA = V_REC.SUBUNITATEA;

        if NR = 0 then
          insert  into NCONTRULSUB (CODCONTRULSUB, CODCONTRUL, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, SUBUNITATEA)
          values (nextval ('SEQ_NCONTRULSUB_CODRULSUB') , V_REC_SUB.CODCONTRUL, 0, 0, 0, 0, 0, 0, 0, 0, V_REC.SUBUNITATEA);
        end if;

        update NCONTRULSUB
        set
        RULAJCD  = RULAJCD  + (CASE when V_REC.TIP = 'D' then V_REC.VALOARE  else 0 end),
        RULAJCC  = RULAJCC  + (CASE when V_REC.TIP = 'C' then V_REC.VALOARE  else 0 end),
        RULAJVCD = RULAJVCD + (CASE when V_REC.TIP = 'D' then V_REC.VALOAREV else 0 end),
        RULAJVCC = RULAJVCC + (CASE when V_REC.TIP = 'C' then V_REC.VALOAREV else 0 end)
        where
          CODCONTRUL = V_REC_SUB.CODCONTRUL and SUBUNITATEA = V_REC.SUBUNITATEA;
      end loop;
    end if;
  end loop;

  update COMANDA1 c1
  set
  RestAcceptat = c1.CantAcceptat - (select coalesce (sum (IL.CANT) , 0)
                                    from TRANSFLINK        IL
                                         left join TRANSF1 II1 on II1.CODTRANSF1 = IL.CODTRANSF1
                                         left join TRANSF  II  on II.CODTRANSF   = II1.CODTRANSF
                                    where
                                      IL.CODLINIECOMANDA = c1.CodComanda1
                                      and II.OPERAT = 1
                                      and II.ANULAT = 0
                                   )
  where
    c1.CodComanda1 in (select CODLINIECOMANDA from TMP_TRANSFLINK UNION select CODLINIECOMANDA from TMP_TRANSFLINK_INITIAL);


  for V_REC in (select I.TIPDOC, I1.TVA, I1.CODINTR1, coalesce (I.CURS, 0) as CURS, I1.CANT, I1.PU
                from INTRARI1 I1, INTRARI I
                where
                    exists (select CODINTR1 from TMP_IMBMIFIXLINK WHERE CODINTR1 = I1.CODINTR1
                            union
                            select CODINTR1 from TMP_IMBMIFIXLINK_INITIAL WHERE CODINTR1 = I1.CODINTR1)
                    and I.CODINTR = I1.CODINTR
               )
  loop
    aCurs := V_REC.CURS;
    if aCURS = 0 then aCURS := 1; end if;

    update INTRARI1 I1
    set
    RESTIMBMF = (case
                   when V_REC.TIPDOC = 3 then V_REC.CANT * V_REC.PU * aCURS - coalesce (V_REC.TVA, 0)
                   else V_REC.CANT * V_REC.PU * aCURS
                 END
                )
              - (select coalesce (sum (IL.CANT) , 0)
                 from IMBMIFIXLINK     IL
                      left join TRANSF1 T1 on T1.CODTRANSF1 = IL.CODTRANSF1
                      left join TRANSF  T  on T.CODTRANSF = T1.CODTRANSF
                 where IL.CODINTR1 = I1.CodINTR1 and T.OPERAT = 1 and T.ANULAT = 0
                )
    where
      CODINTR1 = V_REC.CODINTR1;
  end loop;


  for V_REC in (select I1.CODIES1, coalesce (I.CURS, 0) as CURS, I1.CANT, I1.PU
                from IESIRI1 I1, IESIRI I
                where
                  exists (select CODIES1 from TMP_IMBMIFIXLINK WHERE CODIES1 = I1.CODIES1
                          UNION
                          select CODIES1 from TMP_IMBMIFIXLINK_INITIAL WHERE CODIES1 = I1.CODIES1
                         )
                  and I.CODIES = I1.CODIES
               )
  loop
    aCurs := V_REC.CURS;
    if aCURS = 0 then aCURS := 1; end if;

    PRET_IMB_MF  := 0;
    VAL_ACHIZ_MF := 0;
    CANT_IMB_MF  := 0;
    BEGIN
      SELECT SUM (L1.CANT) AS CANTDIMIN, SUM (L1.CANT * (NS.PRET - COALESCE (NS.ADAOS, 0))) AS VALDIMIN
      INTO
        CANT_IMB_MF, VAL_ACHIZ_MF
      FROM LIVR1 L1, LIVR L, NIRSTOC NS
      WHERE
        L1.CODIES1 = V_REC.CODIES1
        AND L1.CODLIVR = L.CODLIVR
        AND L.TIPLIVR = 14
        AND NS.CODNIRSTOC = L1.CODNIRSTOC
      GROUP BY L1.CODIES1;
    EXCEPTION
    WHEN OTHERS THEN
      NULL;
    END;

    IF COALESCE (CANT_IMB_MF, 0) &lt;&gt; 0 THEN
      PRET_IMB_MF := VAL_ACHIZ_MF / CANT_IMB_MF;
    END IF;

    update IESIRI1 I1
    set
    RESTIMBMF = PRET_IMB_MF * V_REC.CANT * aCURS - (SELECT COALESCE (SUM (IL.CANT) , 0)
                                                    from IMBMIFIXLINK     IL
                                                         left join TRANSF1 T1 on T1.CODTRANSF1 = IL.CODTRANSF1
                                                         left join TRANSF  T  on T.CODTRANSF   = T1.CODTRANSF
                                                    where
                                                      IL.CODIES1 = I1.CodIES1 and T.OPERAT = 1 and T.ANULAT = 0)
    where
      CODIES1 = V_REC.CODIES1;
  end loop;


  for V_REC in (select N1.CODNC1, coalesce (N.CURS, 0) as CURS, N1.VALOARE
                from NC1 N1, NC N
                where
                  exists (select CODNC1 from TMP_IMBMIFIXLINK WHERE CODNC1 = N1.CODNC1
                          UNION
                          select CODNC1 from TMP_IMBMIFIXLINK_INITIAL WHERE CODNC1 = N1.CODNC1
                         )
                  and N.CODNC = N1.CODNC
               )
  loop
    aCurs := V_REC.CURS;
    if aCURS = 0 THEN aCURS := 1; end if;

    update NC1 N1
    set
    RESTIMBMF = V_REC.VALOARE * aCURS - (select coalesce (sum (IL.CANT) , 0)
                                         from IMBMIFIXLINK      IL
                                              left join TRANSF1 T1 on T1.CODTRANSF1 = IL.CODTRANSF1
                                              left join TRANSF  T  on T.CODTRANSF   = T1.CODTRANSF
                                         where
                                           IL.CODNC1 = N1.CodNC1 and T.OPERAT = 1 and T.ANULAT = 0
                                        )
    where
      CODNC1 = V_REC.CODNC1;
  end loop;


  for V_REC in (select M.CODMIFIX, M1.PRET as VALOARE
                from MIFIX M, MIFIX1 M1
                where
                  exists (select CODMIFIX from TMP_IMBMIFIXLINK WHERE CODMIFIX = M.CODMIFIX
                          union ALL
                          select CODMIFIX from TMP_IMBMIFIXLINK_INITIAL WHERE CODMIFIX = M.CODMIFIX
                         )
                  and M1.CODMIFIX = M.CODMIFIX
                  and M1.ANSTART * 12 + M1.LUNASTART &lt;= (select PKG_GLOBALS_AnLunaLucru.WME_RESULT from PKG_GLOBALS_AnLunaLucru (null, null))
                  and M1.ANSTART * 12 + M1.LUNASTART  = (select max (ANSTART * 12 + LUNASTART) from MIFIX1 M2
                                                         where
                                                               M2.CODMIFIX = M.CODMIFIX
                                                           and M2.ANSTART * 12 + M2.LUNASTART &lt;= (select PKG_GLOBALS_AnLunaLucru.WME_RESULT from PKG_GLOBALS_AnLunaLucru (null, null)))
                )
  loop
    update MIFIX N1
    set
    RESTIMBMF = V_REC.VALOARE - (select coalesce (sum (IL.CANT) , 0)
                                 from IMBMIFIXLINK      IL
                                      left join TRANSF1 T1 on T1.CODTRANSF1 = IL.CODTRANSF1
                                      left join TRANSF  T  on T.CODTRANSF   = T1.CODTRANSF
                                 where
                                   IL.CODMIFIX = N1.CODMIFIX and T.OPERAT = 1 and T.ANULAT = 0
                                )
    where
      CODMIFIX = V_REC.CODMIFIX;
  end loop;

  if ATIPDOC = 13 then
    perform PKG_MISCARI_INTERNE_CHECK_REZERVARI_MODIPRET_IN();
    perform PKG_MISCARI_INTERNE_CHECK_REZERVARI_MODIPRET_OUT();
  end if;

  if ATIPDOC = 12 and  aOPERAT = 1 AND not (LivrDinRezTransf = '1') AND NOT (current_setting ('pkg_miscari_interne.v$Session_LivrDinRezTransf ', true) = '1') then
    perform PKG_MISCARI_INTERNE_CHECK_REZERVARI_TRANSF_IN();
    perform PKG_MISCARI_INTERNE_CHECK_REZERVARI_TRANSF_OUT();
  end if;


  -- ACTUALIZARE REZERVARESTOC
  for V_REC in (select IL.CODLINIECOMANDA, coalesce (L1.CODNIRSTOC, 0) as CODNIRSTOC, coalesce (L1.CODNIRSER, 0) as CODNIRSER, L1.CANTREZERVAT, L1.PARITATE
                from TMP_LIVR1_INITIAL L1, TMP_TRANSFLINK_INITIAL IL
                where L1.CODIES1 = IL.CODTRANSF1
               )
  loop
    update REZERVATS
    set
    REST = REST + V_REC.CANTREZERVAT * V_REC.PARITATE
    where
      CODCOMANDA1    = V_REC.CODLINIECOMANDA
      and CODNIRSTOC = V_REC.CODNIRSTOC
      and coalesce (CODNIRSER, 0) = V_REC.CODNIRSER;
  end loop;


  -- ACTUALIZARE REZERVARESTOC
  for V_REC in (select IL.CODLINIECOMANDA, coalesce (L1.CODNIRSTOC, 0) as CODNIRSTOC, coalesce (L1.CODNIRSER, 0) as CODNIRSER, L1.CANTREZERVAT, L1.PARITATE
                from TMP_LIVR1 L1, TMP_TRANSFLINK IL
                where L1.CODIES1 = IL.CODTRANSF1
               )
  loop
    update REZERVATS
    set
    REST = REST - V_REC.CANTREZERVAT * V_REC.PARITATE
    where
      CODCOMANDA1 = V_REC.CODLINIECOMANDA
      and CODNIRSTOC = V_REC.CODNIRSTOC
      and coalesce (CODNIRSER, 0) = V_REC.CODNIRSER;
  end loop;

  -- actualizez modif pret nirstoc
  for V_REC in (select CodNirStoc, Pret from Tmp_NIRSTOC WHERE coalesce (ActualizPret, 0) &gt; 0) loop
    perform PKG_Jurnal_setDirtyNirStoc (V_REC.CODNIRSTOC, V_Rec.Pret, '0', 0);
  end loop;

  perform PKG_CANTAR_ELIBEREAZA_ON_SP_POSTRECORDS();
  perform PKG_GLOBALS_MarkDirtyJurnal();
  perform NotifyModif (OPERATION, RECID, 'TRANSF');


  -- VALORICE FARA DESCARCARE GENERATE DE DOCUMENTUL CURENT
  for V_REC in (select L1.CODLIVR1
                from LIVRVAL LV, LIVR1 L1, LIVR L, TMP_IOART_LUNA IOALUNA
                where
                  LV.CODLIVR1 = L1.CODLIVR1
                  and L.CODLIVR = L1.CODLIVR
                  and L.CODTRANSF = RECID
                  and LV.CODIOART = IOALUNA.CODIOART
                  and coalesce (IOALUNA.DESCARCAREG, 0) = 0
               )
  loop
    update LIVR1 L1
    set
    RESTIESVAL = L1.CANT - (select coalesce (sum (IL.CANT) , 0)
                            from IESVALLINK       IL
                              left join IESIRI1 I1 on I1.CODIES1 = IL.CODIES1
                              left join IESIRI  I  on I.CODIES = I1.CODIES
                            where
                              IL.CODLIVR1 = L1.CODLIVR1
                              and IL.CODIES1 = I1.CODIES1
                              and I.CODIES = I1.CODIES
                              and I.OPERAT = 1
                              and I.ANULAT = 0)
    where
      CODLIVR1 = V_REC.CODLIVR1;
  end loop;


--  if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TRANSF1EXT')) = 1
--    and
--     (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_TRANSF1EXT')) = 1
--  then
--    execute 'DELETE FROM TRANSF1EXT WHERE CODTRANSF1 IN (SELECT CODTRANSF1 FROM TMP_TRANSF1_INITIAL)  ';
--    execute 'UPDATE TMP_TRANSF1EXT SET CODTRANSF1EXT = nextval(''SEQ_TRANSF1EXT_CODTRANSF1EXT'')  WHERE CODTRANSF1EXT &lt; 0';
--    execute 'INSERT INTO TRANSF1EXT SELECT * FROM TMP_TRANSF1EXT ';
--  end if;

  if aTIPDOC = 12
    and (fnc_GetValConstanta ('MifixExtins', to_number (current_setting ('PKG_GLOBALS.ANLUCRU', true) , '999999999999999999') , to_number (current_setting ('PKG_GLOBALS.LUNALUCRU', true) , '999999999999999999'))) &lt;&gt; '1'
  then
    perform pkg_miscari_interne_CHECK_TRANSF_MIFIX_SERIEBUCATA (RECID);
    perform pkg_miscari_interne_CHECK_TRANSF_MIFIX_FARASERIE (RECID);
  end if;

  begin
    if coalesce ( (fnc_GetValConstanta ('InchidCmdTransf', to_number (current_setting ('PKG_GLOBALS.ANLUCRU', true) , '999999999999999999') , to_number (current_setting ('PKG_GLOBALS.LUNALUCRU', true) , '999999999999999999'))) , '2') = '1' then
      for v_rec in (select  distinct c.codcomanda
                    from transflink               l
                      inner join transf1        t1 on l.codtransf1 = t1.codtransf1
                      inner join comanda1       c1 on c1.codcomanda1 = l.codliniecomanda
                      inner join comanda        c  on c.codcomanda = c1.codcomanda
                    where
                      coalesce (c.inchisa, 0) = 0 and t1.codtransf = recid
                   )
      loop
        update comanda set inchisa = 1 WHERE codcomanda = v_rec.codcomanda;

        DELETE from rezervats r
        WHERE exists (select c1.codcomanda1 from comanda1 c1 WHERE c1.codcomanda = v_rec.codcomanda and c1.codcomanda1 = r.codcomanda1);
      end loop;
    end if;
  exception
  when others then
    null;
  end;

  if aCountBCAR &gt; 0 then
    for v_rec in (select b.codbcar, t.delegat, t.codgestcmd CODPARTENER
                  from transf1        t1
                    inner join transf t on t.codtransf = t1.codtransf
                    inner join bcar   b on b.coddoc1 = t1.codtransf1 and b.tipdoc = atipdoc
                  where t.codtransf = recid
                 )
    loop
      update bcar
      set
      coddelegat  = v_rec.delegat,
      codpartener = v_rec.codpartener
      where
        codbcar = v_rec.codbcar;
    end loop;
  end if;


  update NIRSTOC NS
  set
  REST    = (select PKG_INTRARI_GET_REST_STOC.WME_RESULT from PKG_INTRARI_GET_REST_STOC (null, NS.CODNIR, NS.CODNIRSTOC, NS.CANTNIR)) ,
  RESTUM1 = (select PKG_INTRARI_GET_REST_STOC_UM1.WME_RESULT from PKG_INTRARI_GET_REST_STOC_UM1 (null, NS.CODNIR, NS.CODNIRSTOC, NS.CANTUM1)) ,
  RESTUM2 = (select PKG_INTRARI_GET_REST_STOC_UM2.WME_RESULT from PKG_INTRARI_GET_REST_STOC_UM2 (null, NS.CODNIR, NS.CODNIRSTOC, NS.CANTUM2))
  where
    NS.CODNIRSTOC in (select CODNIRSTOC from TMP_LIVR1 UNION select CODNIRSTOC from TMP_LIVR1_INITIAL);

  update NIRSER NS
  set
  REST    = (select PKG_INTRARI_GET_REST_STOC_SERIE.WME_RESULT
             from PKG_INTRARI_GET_REST_STOC_SERIE (null, (select CODNIR from NIRSTOC WHERE CODNIRSTOC = NS.CODNIRSTOC) , NS.CODNIRSER, NS.CANTNIR)) ,
  RESTUM1 = (select PKG_INTRARI_GET_REST_STOC_SERIE_UM1.WME_RESULT
             from PKG_INTRARI_GET_REST_STOC_SERIE_UM1 (null, (select CODNIR from NIRSTOC WHERE CODNIRSTOC = NS.CODNIRSTOC) , NS.CODNIRSER, NS.CANTUM1)) ,
  RESTUM2 = (select PKG_INTRARI_GET_REST_STOC_SERIE_UM2.WME_RESULT
             from PKG_INTRARI_GET_REST_STOC_SERIE_UM2 (null, (select CODNIR from NIRSTOC WHERE CODNIRSTOC = NS.CODNIRSTOC) , NS.CODNIRSER, NS.CANTUM2))
  where
    NS.CODNIRSTOC in (select CODNIRSTOC from TMP_LIVR1 UNION select CODNIRSTOC from TMP_LIVR1_INITIAL);

  update NIRSTOC NS
  set
  REST    = (select PKG_INTRARI_GET_REST_STOC.WME_RESULT from PKG_INTRARI_GET_REST_STOC (null, NS.CODNIR, NS.CODNIRSTOC, NS.CANTNIR)) ,
  RESTUM1 = (select PKG_INTRARI_GET_REST_STOC_UM1.WME_RESULT from PKG_INTRARI_GET_REST_STOC_UM1 (null, NS.CODNIR, NS.CODNIRSTOC, NS.CANTUM1)) ,
  RESTUM2 = (select PKG_INTRARI_GET_REST_STOC_UM2.WME_RESULT from PKG_INTRARI_GET_REST_STOC_UM2 (null, NS.CODNIR, NS.CODNIRSTOC, NS.CANTUM2))
  where
    NS.CODNIRSTOC in (select CODNIRSTOC from TMP_NIRSTOC);

  update NIRSER NS
  set
  REST    = (select PKG_INTRARI_GET_REST_STOC_SERIE.WME_RESULT
             from PKG_INTRARI_GET_REST_STOC_SERIE (null, (select CODNIR from NIRSTOC WHERE CODNIRSTOC = NS.CODNIRSTOC) , NS.CODNIRSER, NS.CANTNIR)) ,
  RESTUM1 = (select PKG_INTRARI_GET_REST_STOC_SERIE_UM1.WME_RESULT
             from PKG_INTRARI_GET_REST_STOC_SERIE_UM1 (null, (select CODNIR from NIRSTOC WHERE CODNIRSTOC = NS.CODNIRSTOC) , NS.CODNIRSER, NS.CANTUM1)) ,
  RESTUM2 = (select PKG_INTRARI_GET_REST_STOC_SERIE_UM2.WME_RESULT
             from PKG_INTRARI_GET_REST_STOC_SERIE_UM2 (null, (select CODNIR from NIRSTOC WHERE CODNIRSTOC = NS.CODNIRSTOC) , NS.CODNIRSER, NS.CANTUM2))
  where
    NS.CODNIRSTOC in (select CODNIRSTOC from TMP_NIRSER);

  IF aOPERAT = 0 THEN
    DELETE FROM EXPERT1 WHERE CODEXPERT in (SELECT CODEXPERT FROM EXPERT WHERE CODDOC = RecID and TIPDOC = aTIPDOC);
    DELETE FROM EXPERT WHERE CODDOC = RecID and TIPDOC = aTIPDOC;
  END IF;

  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS(ATIPDOC, operation);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_sp_postrecords_from_import</obj_name>
  <obj_hashval>3a842a4c0cf39c983d3ccf93daa34c41</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_sp_postrecords_from_import(INOUT recid numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC         RECORD;
  VCOD          numeric;
  OLDCARNETNIR  numeric := 0;
  OLDNRNIR      numeric := 0;
  OLDCARNETLIVR numeric := 0;
  OLDNRLIVR     numeric := 0;
  ACARNET       numeric := 0;
  ANUMARDOC     numeric := 0;
  ATIPDOC       numeric := 0;
  NR            numeric := 0;
  aCODSERIE     numeric := 0;
  NOMSERIE      varchar;
  aCodComanda1  numeric;
  aRoot         numeric;
  aDirty        numeric;
  aTipNIR       numeric;
  aPretMat      double precision;
BEGIN
  --Florin 25.09.2024 - sinc. Oracle
  --Adina 05.05.2021 - sinc.Oracle
  SELECT CARNETDOC, NRDOC, TIPDOC INTO ACARNET, ANUMARDOC, ATIPDOC FROM TMP_TRANSF;

  -- POZITII NOI IN INTRARI
  INSERT INTO INTRARI(CODINTR, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, DATADOC, PARTENER, AN, LUNA)
  SELECT CODINTR, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, DATADOC, PARTENER, AN, LUNA FROM TMP_INTRARI;

  INSERT INTO INTRARI1(CODINTR1, CODINTR, INDEXLOCAL, TIPLINIE, CODOBIECTORIG, PARITATEORIG, UMSEC, AN, LUNA, CODOBIECT, PRETORIG, PU, CANT, TG)
  SELECT CODINTR1, CODINTR, INDEXLOCAL, TIPLINIE, CODOBIECTORIG, PARITATEORIG, UMSEC, AN, LUNA, CODOBIECT, PRETORIG, PU, 0, TG FROM TMP_INTRARI1;

  UPDATE TMP_NIR TN
  SET DATACREARE = current_timestamp
    WHERE OPERAT = 1 AND DATACREARE IS NULL
    AND NOT EXISTS(SELECT 1 FROM NIR N WHERE N.CODNIR = TN.CODNIR AND N.OPERAT = 1);

  UPDATE TMP_NIRSTOC NS
  SET (DATAACHIZ, TG, TIPDOCACHIZ) = (SELECT DATAACHIZ, TG, TIPDOCACHIZ FROM NIRSTOC WHERE CODNIRSTOC = NS.CODNIRSTOCPARINTE);

  -- sunt transferuri care se fac cu scopul de a modifica TG-ul pe serie; trebuie sa sincronizez tG-ul din nirstoc si nirser
  FOR V_REC IN (SELECT * FROM TMP_NIRSTOC WHERE coalesce(TIPSERIE, 0) &gt; 0 AND TG IS NOT NULL)
  LOOP
    UPDATE TMP_NIRSTOC NS
    SET
      TG = (SELECT TG FROM TMP_NIRSER NSE WHERE NSE.CODNIRSTOC = V_REC.CODNIRSTOC limit 1)
    WHERE
       CODNIRSTOC = V_REC.CODNIRSTOC;
  END LOOP;

  SELECT NEXTVAL('SEQ_TRANSF_CODTRANSF') INTO RECID;

  INSERT INTO TRANSF(CODTRANSF, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, CARNETDOC, NRDOC, DATADOC, CARNETAE, NRAE, VALDOC, TVADOC, OBS, AN, LUNA, VALSUPLIM, CONTSUPLIM, TIPREPSUPLIM, DELEGAT, CODPART, STORNO, TIPMODIFPRET, SUBUNITATEA, userID, datacreare, MIJLTRANSP, NRTRANSP, CODGESTCMD, IDIMPORT, AJUSTVALSTOC)
  SELECT RECID, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, CARNETDOC, NRDOC, DATADOC, CARNETAE, NRAE, VALDOC, TVADOC, OBS, AN, LUNA, VALSUPLIM, CONTSUPLIM, TIPREPSUPLIM, DELEGAT, CODPART, STORNO, TIPMODIFPRET, SUBUNITATEA, TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999'), CURRENT_TIMESTAMP, MIJLTRANSP, NRTRANSP, CODGESTCMD, IDIMPORT, AJUSTVALSTOC
  FROM TMP_TRANSF;

  FOR V_REC IN (SELECT * FROM TMP_TRANSF1 ORDER BY INDEXLOCAL) LOOP
    SELECT NEXTVAL('SEQ_TRANSF1_CODTRANSF1') INTO VCOD;

    UPDATE tmp_jurnal1 SET indexlocal = vCod WHERE indexlocal = v_rec.codtransf1;

    INSERT INTO TRANSF1(CODTRANSF1, CODTRANSF, INDEXLOCAL, TIPLINIE, CODOBIECTORIG, PARITATEORIG, CODCONT, UMSEC, CODOBIECT, PU, PUMAXIMAL, CANT, TVA, D1, D2, D3)
    VALUES(VCOD, RECID, V_REC.INDEXLOCAL, V_REC.TIPLINIE, V_REC.CODOBIECTORIG, V_REC.PARITATEORIG, V_REC.CODCONT, V_REC.UMSEC, V_REC.CODOBIECT, V_REC.PU / V_REC.PARITATE, V_REC.PUMAXIMAL / V_REC.PARITATE, V_REC.CANT * V_REC.PARITATE, V_REC.TVA, V_REC.D1, V_REC.D2, V_REC.D3);

    UPDATE TMP_LIVR1   SET CODIES1    = VCOD WHERE CODIES1 = V_REC.CODTRANSF1;
    UPDATE TMP_NIRSTOC SET CODTRANSF1 = VCOD WHERE CODTRANSF1 = V_REC.CODTRANSF1;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_LIVR ORDER BY CODLIVR) LOOP
    SELECT NEXTVAL('SEQ_LIVR_CODLIVR') INTO VCOD;

    INSERT INTO LIVR(CODLIVR, CODIES, CODTRANSF, CARNETLIVR, NRLIVR, DATALIVR, OBS, TIPLIVR, ANULAT, BLOCAT, OPERAT)
    VALUES(VCOD, V_REC.CODIES, RECID, V_REC.CARNETLIVR, V_REC.NRLIVR, V_REC.DATALIVR, V_REC.OBS, V_REC.TIPLIVR, V_REC.ANULAT, V_REC.BLOCAT, V_REC.OPERAT);

    UPDATE TMP_LIVR1 SET CODLIVR = VCOD WHERE CODLIVR = V_REC.CODLIVR;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_LIVR1 ORDER BY CODLIVR1) LOOP
    UPDATE TMP_LIVRVAL LV
    SET
    PRETINREG = PRETINREG / V_REC.PARITATE,
    PRETACHIZ = PRETACHIZ / V_REC.PARITATE
    WHERE
     LV.CODLIVR1 = V_REC.CODLIVR1;

    SELECT NEXTVAL('SEQ_LIVR1_CODLIVR1') INTO VCOD;

    UPDATE TMP_LIVRVAL SET CODLIVR1 = VCOD WHERE CODLIVR1 = V_REC.CODLIVR1;

    INSERT INTO LIVR1(CODLIVR1, CODLIVR, CODIES1, CODINTR1, CODNIRSTOC, CANT, CANTUM1, CANTUM2, CODNIRSER, PMP, PMPDOC, PMPVALUTA, PMPVALUTADOC, UMSEC)
    VALUES(VCOD, V_REC.CODLIVR, V_REC.CODIES1, V_REC.CODINTR1, V_REC.CODNIRSTOC, V_REC.CANT * V_REC.PARITATE, V_REC.CANTUM1, V_REC.CANTUM2, V_REC.CODNIRSER, V_REC.PMP, V_REC.PMPDOC, V_REC.PMPVALUTA, V_REC.PMPVALUTADOC, V_REC.UMSEC);

    UPDATE TMP_NIRSTOC SET CODLIVR1 = VCOD WHERE CODLIVR1 = V_REC.CODLIVR1;
  END LOOP;

  INSERT INTO LIVRVAL(CODLIVRVAL, CODLIVR1, CODOBIECT, CODIOART, GEST, PRETINREG, PRETACHIZ, TVANEEX)
  SELECT NEXTVAL('SEQ_LIVRVAL_CODLIVRVAL'), CODLIVR1, CODOBIECT, CODIOART, GEST, PRETINREG, PRETACHIZ, TVANEEX FROM TMP_LIVRVAL;

  UPDATE NIRSTOC NS
  SET
  REST    = (SELECT PKG_INTRARI_GET_REST_STOC.WME_RESULT     FROM PKG_INTRARI_GET_REST_STOC    (NULL, NS.CODNIR, NS.CODNIRSTOC, NS.CANTNIR)),
  RESTUM1 = (SELECT PKG_INTRARI_GET_REST_STOC_UM1.WME_RESULT FROM PKG_INTRARI_GET_REST_STOC_UM1(NULL, NS.CODNIR, NS.CODNIRSTOC, NS.CANTUM1)),
  RESTUM2 = (SELECT PKG_INTRARI_GET_REST_STOC_UM2.WME_RESULT FROM PKG_INTRARI_GET_REST_STOC_UM2(NULL, NS.CODNIR, NS.CODNIRSTOC, NS.CANTUM2))
  WHERE NS.CODNIRSTOC IN (SELECT CODNIRSTOC FROM TMP_LIVR1);

  UPDATE NIRSER NS
  SET
  REST    = (SELECT PKG_INTRARI_GET_REST_STOC_SERIE.WME_RESULT     FROM PKG_INTRARI_GET_REST_STOC_SERIE    (NULL, (SELECT CODNIR FROM NIRSTOC WHERE CODNIRSTOC = NS.CODNIRSTOC), NS.CODNIRSER, NS.CANTNIR)),
  RESTUM1 = (SELECT PKG_INTRARI_GET_REST_STOC_SERIE_UM1.WME_RESULT FROM PKG_INTRARI_GET_REST_STOC_SERIE_UM1(NULL, (SELECT CODNIR FROM NIRSTOC WHERE CODNIRSTOC = NS.CODNIRSTOC), NS.CODNIRSER, NS.CANTUM1)),
  RESTUM2 = (SELECT PKG_INTRARI_GET_REST_STOC_SERIE_UM2.WME_RESULT FROM PKG_INTRARI_GET_REST_STOC_SERIE_UM2(NULL, (SELECT CODNIR FROM NIRSTOC WHERE CODNIRSTOC = NS.CODNIRSTOC), NS.CODNIRSER, NS.CANTUM2))
  WHERE NS.CODNIRSTOC IN (SELECT CODNIRSTOC FROM TMP_LIVR1);

  -- DETAIL NIR
  FOR V_REC IN (SELECT * FROM TMP_NIR ORDER BY CODNIR) LOOP
    SELECT NEXTVAL('SEQ_NIR_CODNIR') INTO VCOD;

    IF V_REC.TIPNIR IN (12, 13) THEN
      INSERT INTO NIR(CODNIR, CODINTR, CODTRANSF, CARNETNIR, NRNIR, DATANIR, GEST, OBS, TIPNIR, ANULAT, BLOCAT, OPERAT)
      VALUES(VCOD, V_REC.CODINTR, RECID, V_REC.CARNETNIR, V_REC.NRNIR, V_REC.DATANIR, V_REC.GEST, V_REC.OBS, V_REC.TIPNIR, V_REC.ANULAT, V_REC.BLOCAT, V_REC.OPERAT);
    ELSE
      INSERT INTO NIR(CODNIR, CODINTR, CARNETNIR, NRNIR, DATANIR, GEST, OBS, TIPNIR, ANULAT, BLOCAT, OPERAT)
      VALUES(VCOD, V_REC.CODINTR, V_REC.CARNETNIR, V_REC.NRNIR, V_REC.DATANIR, V_REC.GEST, V_REC.OBS, V_REC.TIPNIR, V_REC.ANULAT, V_REC.BLOCAT, V_REC.OPERAT);
    END IF;

    UPDATE TMP_NIRSTOC SET CODNIR = VCOD WHERE CODNIR = V_REC.CODNIR;
  END LOOP;

  -- DETAIL NIRSTOC
  DELETE FROM TMP_NIRSTOC_RECOD;  -- folosit la reevaluari

  FOR V_REC IN (SELECT * FROM TMP_NIRSTOC ORDER BY CODNIRSTOC) LOOP
    IF  V_REC.CODNIRSTOC &lt; 0 THEN
      SELECT NEXTVAL('SEQ_NIRSTOC_CODNIRSTOC') INTO VCOD;
    ELSE
      VCOD := V_REC.CODNIRSTOC;
    END IF;

    INSERT INTO TMP_NIRSTOC_RECOD(CODVECHI, CODNOU) VALUES(V_REC.CODNIRSTOC, VCOD);

    INSERT INTO NIRSTOC(CODNIRSTOC, CODNIR, CODINTR1, CODTRANSF1, CODNIRSTOCPARINTE, CANTNIR, CANTFURN, UMSEC, CODOBIECT, CODIOART, PRET, ROTLEI, ROTVALUTA, CODLOCATIE, ADAOS, TVA, TIPSERIE, CODLIVR1, REST, RESTUM1, RESTUM2, PROCENTADAOS, Supliment, TG, PUMAXIMAL, FURN, DATAACHIZ, TIPDOCACHIZ, CODGESTPROD, SUBUNITATEA, CANTUM1, CANTUM2)
    VALUES(VCOD, V_REC.CODNIR, V_REC.CODINTR1, V_REC.CODTRANSF1, V_REC.CODNIRSTOCPARINTE, V_REC.CANTNIR * V_REC.PARITATE, V_REC.CANTFURN * V_REC.PARITATE, V_REC.UMSEC, V_REC.CODOBIECT, COALESCE( V_REC.CODIOART, 0), V_REC.PRET / V_REC.PARITATE, V_REC.ROTLEI, V_REC.ROTVALUTA, V_REC.CODLOCATIE, V_REC.ADAOS, V_REC.TVA, V_REC.TIPSERIE, V_REC.CODLIVR1, (SELECT PKG_INTRARI_GET_REST_STOC.WME_RESULT FROM PKG_INTRARI_GET_REST_STOC(NULL, V_REC.CODNIR, V_REC.CODNIRSTOC, V_REC.CANTNIR * V_REC.PARITATE)), (SELECT PKG_INTRARI_GET_REST_STOC_UM1.WME_RESULT FROM PKG_INTRARI_GET_REST_STOC_UM1(NULL, V_REC.CODNIR, V_REC.CODNIRSTOC, V_REC.CANTUM1)), (SELECT PKG_INTRARI_GET_REST_STOC_UM2.WME_RESULT FROM PKG_INTRARI_GET_REST_STOC_UM2(NULL, V_REC.CODNIR, V_REC.CODNIRSTOC, V_REC.CANTUM2)), V_REC.PROCENTADAOS, V_REC.Supliment, V_REC.TG, V_REC.PUMAXIMAL, V_REC.FURN, V_REC.DATAACHIZ, V_REC.TIPDOCACHIZ, V_REC.CODGESTPROD, V_REC.SUBUNITATEA, V_REC.CANTUM1, V_REC.CANTUM2);

    UPDATE TMP_NIRSER SET CODNIRSTOC = VCOD WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
  END LOOP;

  -- Detail NirSer
  FOR V_REC IN (SELECT * FROM TMP_NIRSER) LOOP
    IF  V_REC.CODSERIE &lt; 0 THEN  -- serie noua; actualizez si NSERII
      BEGIN
        SELECT COALESCE( CODSERIE, 0) INTO aCODSERIE FROM NSERII WHERE SERIE = V_REC.SERIE AND CODOBIECT = (SELECT CODOBIECT FROM NIRSTOC WHERE CODNIRSTOC = V_REC.CODNIRSTOC);
      EXCEPTION WHEN OTHERS THEN
        aCODSERIE := 0;
      END;

      IF  COALESCE( aCODSERIE, 0) = 0 THEN
        SELECT NEXTVAL('SEQ_NSERII_CODSERIE') INTO aCODSERIE;

        INSERT INTO NSERII(CODSERIE, SERIE, CODOBIECT) VALUES(aCODSERIE, V_REC.SERIE, (SELECT CODOBIECT FROM NIRSTOC WHERE CODNIRSTOC = V_REC.CODNIRSTOC));
      END IF;
    ELSE
      aCODSERIE := V_REC.CODSERIE;
      -- verific daca la editare nu a schimbat seria
      BEGIN
        SELECT COALESCE( SERIE, '') INTO NOMSERIE FROM NSERII WHERE CODSERIE = aCODSERIE;
      EXCEPTION WHEN OTHERS THEN
        NOMSERIE := '';
      END;

      IF  COALESCE( NOMSERIE, '') &lt;&gt; V_REC.SERIE THEN
        UPDATE NSERII SET SERIE = V_REC.SERIE WHERE CODSERIE = aCODSERIE;
      END IF;
    END IF;

    IF  V_REC.CODNIRSER &lt; 0 THEN
      SELECT NEXTVAL('SEQ_NIRSER_CODNIRSER') INTO vCod;
    ELSE
      VCOD := V_REC.CODNIRSER;
    END IF;

    INSERT INTO NIRSER(CODNIRSER, CODNIRSTOC, CODSERIE, CANTNIR, REST, CANTUM1, CANTUM2)
    VALUES(vCod, V_REC.CODNIRSTOC, aCODSERIE, V_REC.CANTNIR, V_REC.CANTNIR, V_REC.CANTUM1, V_REC.CANTUM2);
  END LOOP;

  INSERT INTO JURNAL1(CODJURNAL1, CODDOC, TIPDOC, INDEXLOCAL, CODBAZAD, ICONTBAZAD, TIPBAZAD, CODDESCRD, ICONTD, TIPCONTD, ANALITICCONTD, CODBAZAC, ICONTBAZAC, TIPBAZAC, CODDESCRC, ICONTC, TIPCONTC, ANALITICCONTC, GEST, VALOARE, VALOAREV, VALOAREGRUP, OBS, AN, LUNA, DIRTY, SUBUNITATEA, DATADOC, CODANALIZANOD)
  (SELECT NEXTVAL('SEQ_JURNAL1_CODJURNAL1'), RECID, TIPDOC, INDEXLOCAL, CODBAZAD, ICONTBAZAD, TIPBAZAD, CODDESCRD, ICONTD, TIPCONTD, ANALITICCONTD, CODBAZAC, ICONTBAZAC, TIPBAZAC, CODDESCRC, ICONTC, TIPCONTC, ANALITICCONTC, GEST, VALOARE, VALOAREV, VALOAREGRUP, OBS, AN, LUNA, DIRTY, SUBUNITATEA, DATADOC, CODANALIZANOD
   FROM TMP_JURNAL1);

  INSERT INTO JURNAL(CODJURNAL, CODDOC, TIPDOC, INDEXLOCAL, CONTD, CONTC, GEST, VALOARE, VALOAREV, VALOAREGRUP, OBS, AN, LUNA, SUBUNITATEA, DATADOC, CODANALIZANOD)
  (SELECT NEXTVAL('SEQ_JURNAL_CODJURNAL'), RECID, TIPDOC, RECID, CONTD, CONTC, GEST, VALOARE, VALOAREV, VALOAREGRUP, OBS, AN, LUNA, SUBUNITATEA, DATADOC, CODANALIZANOD
   FROM TMP_JURNAL);

  -- ACTUALIZARE CARNETE DOCUMENTE
  IF (TO_NUMBER(current_setting('PKG_MISCARI_INTERNE.CARNETDOC_I', true),'999999999999999999') &lt;&gt; 0)
     AND
     (TO_NUMBER(current_setting('PKG_MISCARI_INTERNE.NRDOC_I', true),'999999999999999999') &lt;&gt; 0)
     AND (ACARNET &lt;&gt; TO_NUMBER(current_setting('PKG_MISCARI_INTERNE.CARNETDOC_I', true),'999999999999999999') OR  ANUMARDOC &lt;&gt; TO_NUMBER(current_setting('PKG_MISCARI_INTERNE.NRDOC_I', true),'999999999999999999'))
  THEN
    PERFORM PKG_CARNETEDOC_RELEASENUMARDOC( TO_NUMBER(current_setting('PKG_MISCARI_INTERNE.CARNETDOC_I', true),'999999999999999999'), TO_NUMBER(current_setting('PKG_MISCARI_INTERNE.NRDOC_I', true),'999999999999999999'));
    PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE( TO_NUMBER(current_setting('PKG_MISCARI_INTERNE.CARNETDOC_I', true),'999999999999999999'));
  END IF;

  PERFORM PKG_CARNETEDOC_SOLVENUMARDOC( ACARNET, (ANUMARDOC)::character varying);

  FOR V_REC IN (SELECT * FROM LIVR WHERE CODTRANSF = RECID) LOOP
    PERFORM PKG_CARNETEDOC_SOLVENUMARDOC( V_REC.CARNETLIVR, (V_REC.NRLIVR)::character varying);
  END LOOP;

  FOR V_REC IN (SELECT * FROM NIR WHERE CODTRANSF = RECID) LOOP
    PERFORM PKG_CARNETEDOC_SOLVENUMARDOC( V_REC.CARNETNIR, (V_REC.NRNIR)::character varying);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_monede_setmonedacurenta</obj_name>
  <obj_hashval>110a716b2d06339f4daf75431d2e9fae</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_monede_setmonedacurenta(amonedacurenta numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_MONEDE.MONEDACURENTA',to_char(aMONEDACURENTA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_monede_sp_insertrecord</obj_name>
  <obj_hashval>4f92688581d3e032ca535eadee89c5ef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_monede_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NMONEDE (codmoneda) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_motivep_sp_gotorecord</obj_name>
  <obj_hashval>746b080b9c8cbfe30016dab7972e5101</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_motivep_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Florin 16.11.2021 - fixat 52001
  perform pkg_motivep_setct_monitor('MON_57');
  INSERT INTO Tmp_MotiveP(CodMotiv, DenMotiv, Motiv)
  (SELECT CodMotiv, DenMotiv, Motiv FROM MotiveP WHERE CodMotiv = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_debug</obj_name>
  <obj_hashval>dc0931ef60338a2ae844012bba4e974c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_debug()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM tmp_manevra_liste;
  INSERT INTO tmp_manevra_liste(filtru, valoare) VALUES('CODOBIECT', 105);

  PERFORM PKG_GLOBALS_SetLunaLucru( 2012, 6,NULL);
  PERFORM PKG_NOM_ARTICOL_UpdateNArtObj1Double( 'PretReferinta', 123);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_getcodobiectgeneric</obj_name>
  <obj_hashval>961cb7314fca0310acf2a1f2e16382a1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_getcodobiectgeneric(INOUT wme_result numeric, INOUT acodarticol numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare aCodgeneric numeric;
begin
aCodGeneric := 0;
begin
select
  O.CODOBIECT
into
  aCodGeneric
from
  NARTOBJ O
where
  O.CODARTICOL = aCodArticol
  and not exists (
  select
    A.CODOBIECT
  from
    NATROBJ A
  where
    A.CODOBIECT = O.CODOBIECT );

exception
when others then aCodGeneric := 0;
end;

WME_Result := aCodGeneric;

return;
end;

$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_getct_monitor</obj_name>
  <obj_hashval>27b0ddab836d62bbbaadc1292efda913</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_NOM_ARTICOL.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_6';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_set_codobiect_analizat</obj_name>
  <obj_hashval>277353473309e8b76862a8ce6b1e4e4f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_set_codobiect_analizat(INOUT wme_result character varying, INOUT acodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult varchar;
BEGIN
  perform set_config('PKG_NOM_ARTICOL.gCodObiect',to_char(aCodObiect,'999999999999999999'),false);

  BEGIN
    SELECT denumire
    INTO sResult
    FROM nartobj
    WHERE codobiect = aCodObiect;
  EXCEPTION WHEN others THEN
    sResult := '???';
  END;

  WME_Result :=  sResult;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_umplestocuri</obj_name>
  <obj_hashval>45e26ecc18329db2eb49c6c8f1838375</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_umplestocuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_obj record;
  v_gest record;
BEGIN
  --Florin 15.05.2023 - sinc. Oracle (11.05.2023)
  for v_obj in (select to_number(valoare) codobiect from tmp_manevra_liste where filtru = 'CODOBIECT') LOOP
    for v_gest in (select * from tmp_nartobjsubunit where codgest &gt; 0) loop
      if v_gest.stocmin is not null then
--        MERGE INTO nartobjsubunit s
--        USING (
--               SELECT v_obj.codobiect codobiect, v_gest.codgest codgest, v_gest.subunitate subunitate, v_gest.stocmin stocmin
--               FROM dual
--              ) t
--        ON (t.CODOBIECT = s.CODOBIECT and s.CODGEST = t.CODGEST AND s.subunitate = t.subunitate)
--        WHEN NOT MATCHED THEN INSERT (cods,codobiect, subunitate, codgest, stocmin)
--                                      VALUES
--                                     (seq_nartobjsubunit_cods.nextval, t.codobiect, t.subunitate, t.codgest, t.stocmin)
--        WHEN MATCHED THEN UPDATE SET s.stocmin = t.stocmin;
        update nartobjsubunit set stocmin = (select sum(coalesce(stocmin,0)) from nartobjsubunit where codobiect = v_obj.codobiect and coalesce(codgest,0) &gt; 0 and subunitate = v_gest.subunitate)
        where codobiect = v_obj.codobiect and coalesce(codgest,0) = 0 and subunitate = v_gest.subunitate;
        update nartobj set stocmin = (select sum(stocmin) from nartobjsubunit where codobiect = v_obj.codobiect and coalesce(codgest,0) = 0)
        where codobiect = v_obj.codobiect;
      end if;
      if v_gest.stocmax is not null then
--        MERGE INTO nartobjsubunit s
--        USING (
--               SELECT v_obj.codobiect codobiect, v_gest.codgest codgest, v_gest.subunitate subunitate, v_gest.stocmax stocmax
--               FROM dual
--              ) t
--        ON (t.CODOBIECT = s.CODOBIECT and s.CODGEST = t.CODGEST AND s.subunitate = t.subunitate)
--        WHEN NOT MATCHED THEN INSERT (cods, codobiect, subunitate, codgest, stocmax)
--                                      VALUES
--                                     (seq_nartobjsubunit_cods.nextval, t.codobiect, t.subunitate, t.codgest, t.stocmax)
--        WHEN MATCHED THEN UPDATE SET s.stocmax = t.stocmax;
        update nartobjsubunit set stocmax = (select sum(coalesce(stocmax,0)) from nartobjsubunit where codobiect = v_obj.codobiect and coalesce(codgest,0) &gt; 0 and subunitate = v_gest.subunitate)
        where codobiect = v_obj.codobiect and coalesce(codgest,0) = 0 and subunitate = v_gest.subunitate;
        update nartobj set stocmax = (select sum(stocmax) from nartobjsubunit where codobiect = v_obj.codobiect and coalesce(codgest,0) = 0)
        where codobiect = v_obj.codobiect;
      end if;
      if v_gest.stocmed is not null then
--        MERGE INTO nartobjsubunit s
--        USING (
--               SELECT v_obj.codobiect codobiect, v_gest.codgest codgest, v_gest.subunitate subunitate, v_gest.stocmed stocmed
--               FROM dual
--              ) t
--        ON (t.CODOBIECT = s.CODOBIECT and s.CODGEST = t.CODGEST AND s.subunitate = t.subunitate)
--        WHEN NOT MATCHED THEN INSERT (cods, codobiect, subunitate, codgest, stocmed)
--                                      VALUES
--                                     (seq_nartobjsubunit_cods.nextval, t.codobiect, t.subunitate, t.codgest, t.stocmed)
--        WHEN MATCHED THEN UPDATE SET s.stocmed = t.stocmed;
        update nartobjsubunit set stocmed = (select sum(coalesce(stocmed,0)) from nartobjsubunit where codobiect = v_obj.codobiect and coalesce(codgest,0) &gt; 0 and subunitate = v_gest.subunitate)
        where codobiect = v_obj.codobiect and coalesce(codgest,0) = 0 and subunitate = v_gest.subunitate;
        update nartobj set stocmed = (select sum(stocmed) from nartobjsubunit where codobiect = v_obj.codobiect and coalesce(codgest,0) = 0)
        where codobiect = v_obj.codobiect;
      end if;
    end loop;
  end loop;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomactivit_sp_gotorecord</obj_name>
  <obj_hashval>a8b601935a58b4c0c3bfcab5d3b07007</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomactivit_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Florin 16.11.2021 - fixat 52001
  perform pkg_nomactivit_setct_monitor('MON_7');
  INSERT INTO TMP_NACTIVIT(codactivit, den_activit) (SELECT codactivit, den_activit FROM NACTIVIT WHERE codactivit = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomcarsupart_sp_insertrecord</obj_name>
  <obj_hashval>301d286227bc6202b350f85b5d4ee7e9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomcarsupart_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NCARSUPART(codcarsupart) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgest_setct_monitor</obj_name>
  <obj_hashval>722371ed49ddfe3af4c2a0a7352ca65d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgest_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMGEST.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_getpartener_editat</obj_name>
  <obj_hashval>a1c90ddc0e7dbf795f51d829d799969d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_getpartener_editat(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOMPART.PARTENER_EDITAT')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_sp_gotorecord</obj_name>
  <obj_hashval>fafdd84660de1dcd83fdf46cd6b4c72a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  V_REC        RECORD;
  V_REC_AG     RECORD;
  aANSFARSIT   numeric;
  aLUNASFARSIT numeric;
  aCODFISCAL   varchar := '';
  vIND         numeric := 0;
  vDATA        date;
BEGIN
  --Florin 09.12.2025 - sinc. Oracle
  --Florin 17.10.2025 - sinc. Oracle
  --Florin 11.09.2025 - sinc. Oracle
  --Florin 07.02.2025 - sinc. Oracle
  --Florin 09.09.2024 - sinc. Oracle
  --Florin 26.06.2024 - sinc. Oracle
  --Florin 14.05.2024 - sinc. Oracle
  --Florin 17.11.2023 - sinc. Oracle
  --Florin 19.10.2023 - sinc. Oracle
  --Florin 12.04.2023 - sinc. Oracle
  --Florin 16.02.2023 - sinc. Oracle
  --Florin 14.02.2023 - sinc. Oracle(13.02.2023)
  --Florin 06.12.2022 - sinc. Oracle (05.12.2022)
  --Bogdan 29.09.2022 - 55428 : Oferte furnizori - data/termen
  --Florin 16.06.2022 - sinc. Oracle
  --Florin 21.02.2022 - sinc. Oracle (18.02.2022)
  --Laura 13.10.2021 - sinc Oracle (08.10.2021)
  --Florin 26.08.2021 - fixat 51177
  --Bogdan 09.03.2020 - #44650 PG - Nomenclator parteneri: informatii la nivel de luna (PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA)
  --Florin 16.11.2021 - fixat 52001
  perform pkg_nompart_setct_monitor('MON_4');
  insert  into TMP_NPART (CodPart, Den_part, CodExtern, CodMoneda,
      RegCom, EXPIRAREAUTORIZ, CODSTATISTICBNR, Autorizatie,
      CodIntern, CodClasa, CodCategPret, TipPart,
      ScadentaC, ScadentaV, Discount, CodCategDisc,
      Blocat, TIPPARTENER, DATAADAUGARII, OBS,
      POZA, PERSOANAFIZICA, VERFACT, VERDISPLIVR,
      COLDISCOUNT, INFOBLOCAT, MusaiColet, STRATEGIC,
      CifraAfaceri, DomeniuActiv, NrAngajati, SursaLead,
      lead, TVALAINCASARE, MODAPLICPROCDISC, PROCCURSTRANSF,
      VERPROFORMA, FIDELIZARE, Majorari, TipBlocaj,
      SPLITTVA, POPRIRE_ANAF, codresponsabil, CodDomeniuAct,
      DocDefOnorCom, ModPromoFactCom, VAlidarePretOferta, IESCUCOMANDA,
      VERFACTAVIZ, ZIAPROVIZ, PERAPROVIZ, CODCONTRACTCadru,
      EF_Item, EF_Party,
      DATANASTERE, GDPR, ZILELIVRARE, SAFT_EXPORT, Farapenalizari, INACTIV, preOfeFurnVar, Tipanalizapret,  VerAvizIes, ef_ImpArtGen, EF_CUSTOM, EF_PROIECT, EF_Taxe,
      CategTarif, ZileAchiz, Culoare)
  select CodPart,
    Den_part,
    CodExtern,
    CodMoneda,
    RegCom,
    EXPIRAREAUTORIZ,
    CODSTATISTICBNR,
    Autorizatie,
    CodIntern,
    CodClasa,
    CodCategPret,
    TipPart,
    ScadentaC,
    ScadentaV,
    Discount,
    CodCategDisc,
    Blocat,
    TIPPARTENER,
    DATAADAUGARII,
    OBS,
    POZA,
    PERSOANAFIZICA,
    VERFACT,
    VERDISPLIVR,
    COLDISCOUNT,
    INFOBLOCAT,
    MusaiColet,
    STRATEGIC,
    CifraAfaceri,
    DomeniuActiv,
    NrAngajati,
    SursaLead,
    lead,
    TVALAINCASARE,
    coalesce (MODAPLICPROCDISC, 0) ,
    PROCCURSTRANSF,
    VERPROFORMA,
    FIDELIZARE,
    Majorari,
    TipBlocaj,
    SPLITTVA,
    POPRIRE_ANAF,
    codresponsabil,
    CodDomeniuAct,
    coalesce (DocDefOnorCom, 0) ,
    coalesce (ModPromoFactCom, 0) ,
    coalesce (ValidarePretOferta, 0) ,
    coalesce (IESCUCOMANDA, 0) ,
    VERFACTAVIZ,
    ZIAPROVIZ,
    PERAPROVIZ,
    CODCONTRACTCadru,
    EF_Item, EF_Party,
    DATANASTERE,
    GDPR,
    ZILELIVRARE,
    COALESCE(SAFT_EXPORT,0),
    coalesce(FaraPenalizari,0),
    coalesce(INACTIV, 0),
    coalesce( preOfeFurnVar, 0),
    COALESCE(Tipanalizapret, 0),
    VerAvizIes,
    ef_ImpArtGen,
    EF_CUSTOM,
    EF_PROIECT,
    COALESCE(EF_Taxe, 0),
    Coalesce(CategTarif,0),
    ZileAchiz, Culoare
  from NPART
  where
    CodPart = RecId;

  INSERT INTO  TMP_NPART1 (CodPart, CodIOPART, CodPart1, CreditFurn, VolumTranzC, CreditClient,SCADENTAV,SCADENTAC,CASSBAZAMIN, SimbolCASS, GDPR ,DISCOUNT, VolumTranzF, anstart, lunastart, alstart, alstop)
  SELECT                   CodPart, CodIOPART, CodPart1, CreditFurn, VolumTranzC, CreditClient,SCADENTAV,SCADENTAC,CASSBAZAMIN, SimbolCASS, GDPR ,DISCOUNT, VolumTranzF, anstart, lunastart, alstart, alstop
  from NPART1
  where
    CodPart = RecId;

  aANSFARSIT   := 0;
  aLUNASFARSIT := 0;

  for V_REC in (select CODPART1, ANSTART, LUNASTART from TMP_NPART1 order BY ANSTART * 12 + LUNASTART desc) loop
    if (aANSFARSIT &lt;&gt; 0) and (aLUNASFARSIT &lt;&gt; 0) then
      update TMP_NPART1
      set ANSFARSIT = aANSFARSIT,
        LUNASFARSIT = aLUNASFARSIT
      where
        CODPART1 = V_REC.CODPART1;
    end if;

    select newan,newluna from
    PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA (V_REC.ANSTART, V_REC.LUNASTART, aANSFARSIT, aLUNASFARSIT) into aANSFARSIT, aLUNASFARSIT ;
  end loop;

  insert  into TMP_NPARTB (CodPartB, CodPart, CodBank, implicit, CodLocalit, ContBanca, Sucursala, CODSWIFT, TIPCOMISION, CONTTVA, OBS, CODMONEDA, SIMBOL)
  select PB.CodPartB,
    PB.CodPart,
    PB.CodBank,
    PB.Implicit,
    PB.CodLocalit,
    PB.ContBanca,
    PB.Sucursala,
    PB.CODSWIFT,
    PB.TIPCOMISION,
    PB.CONTTVA,
    PB.OBS,
    PB.CODMONEDA,
    M.SIMBOL
  from NPARTB PB left join NMONEDE M on M.CODMONEDA = coalesce (PB.CODMONEDA, 0)
  where
    CodPart = RecId;

  insert  into TMP_NPARTCODFISC  select  * from NPARTCODFISC  WHERE CODPART = RecId;
  insert  into TMP_NPARTLSTCLASE select  * from NPARTLSTCLASE WHERE CODPART = RecId;

  insert  into TMP_NAGENDA (obs, codagenda, tip, codlocalit,
      sediusocial, telefon, fax, email,
      sector, strada, nr1, nr2,
      bloc, scara, etaj, apart,
      codpostal, km, Inactiv, CodCoresp,
      TranspClient, codbankcont, codpart, codgest,
      codsubunit, CODTIPSEDIU, CODFISCAL, CODAGENT,
      adresa, COEFUTILAJE, SUPRAFATA, MODSERVIRE,
      IDSEDIU, COD_CODFISCAL, Codclient, CODTRASEU,
      POZTRASEU, CODTRASEU1, POZTRASEU1, EDI_EXPTIP,
      EDI_PARTTIP, EDI_PARTID, EDI_OBJTIP, GLN,
      GESTLIVRARE, LONGITUDINE, LATITUDINE, OBS2,
      Facturare, CODANTREPOZIT, ZileTransport, Judet, VERFACT, VERDISPLIVR, VERPROFORMA, VERFACTAVIZ, VERAVIZIES)
  select A.obs,
    A.codagenda,
    A.tip,
    A.codlocalit,
    A.sediusocial,
    A.telefon,
    A.fax,
    replace (replace (A.email, ' ', '') , ';', chr (13)
      || chr (10)) EMAIL,
    A.sector,
    A.strada,
    A.nr1,
    A.nr2,
    A.bloc,
    A.scara,
    A.etaj,
    A.apart,
    A.codpostal,
    A.km,
    A.Inactiv,
    A.CodCoresp,
    coalesce (A.TranspClient, 3) ,
    A.codbankcont,
    A.codpart,
    A.codgest,
    A.codsubunit,
    A.CODTIPSEDIU,
    A.CODFISCAL,
    A.CODAGENT,
    L.DEN_LOCALIT
      || chr (13)
      || (select GetAdresa.WME_RESULT from GetAdresa (null, A.sector, A.strada, A.nr1, A.nr2, A.bloc, A.scara, A.etaj, A.apart, A.codpostal)) ,
    A.COEFUTILAJE,
    A.SUPRAFATA,
    A.MODSERVIRE,
    A.IDSEDIU,
    A.COD_CODFISCAL,
    A.codclient,
    A.codtraseu,
    A.poztraseu,
    A.codtraseu1,
    A.poztraseu1,
    coalesce (A.EDI_EXPTIP, 0) ,
    coalesce (A.EDI_PARTTIP, 0) ,
    A.EDI_PARTID,
    coalesce (A.EDI_OBJTIP, 0) ,
    A.GLN,
    A.GESTLIVRARE,
    A.LONGITUDINE,
    A.LATITUDINE,
    A.OBS2,
    C.Obs,
    A.CODANTREPOZIT,
    A.ZileTransport,
    j.den_judet,
    A.VERFACT, A.VERDISPLIVR, A.VERPROFORMA, A.VERFACTAVIZ, A.VERAVIZIES
  from NAGENDA           A
    left join NLOCALIT   L on A.CodLocalit = L.CodLocalit
    left join NJUDET     J on L.CODJUDET   = J.CODJUDET
    left join TRASEULIVR T on A.Codtraseu  = T.CODTRASEULIVR
    left join NAGENDA    C on coalesce (A.CodCoresp, 0) = C.CODAGENDA
  where
    A.codpart = RecId;

  UPDATE TMP_NAGENDA A SET
    SVERFACT     = (SELECT L.NAME FROM WINMADMIN.LISTS L WHERE L.LISTID = 101 AND L.LISTVER = A.VERFACT),
    SVERDISPLIVR = (SELECT L.NAME FROM WINMADMIN.LISTS L WHERE L.LISTID = 102 AND L.LISTVER = A.VERDISPLIVR),
    SVERPROFORMA = (SELECT L.NAME FROM WINMADMIN.LISTS L WHERE L.LISTID = 189 AND L.LISTVER = A.VERPROFORMA),
    SVERFACTAVIZ = (SELECT L.NAME FROM WINMADMIN.LISTS L WHERE L.LISTID = 141 AND L.LISTVER = A.VERFACTAVIZ),
    SVERAVIZIES  = (SELECT L.NAME FROM WINMADMIN.LISTS L WHERE L.LISTID = 140 AND L.LISTVER = A.VERAVIZIES);

  insert  into TMP_NAGENDA1 (CODAGENDA1, CODAGENDA, ANSTART, LUNASTART, CREDITCLIENT, ZILEDEPASIRE, NRFACTSOLD, SCADENTAV)
  select CODAGENDA1, CODAGENDA, ANSTART, LUNASTART, CREDITCLIENT, ZILEDEPASIRE, NRFACTSOLD, SCADENTAV
  from NAGENDA1 A1 WHERE exists (select CODAGENDA from TMP_NAGENDA WHERE CODAGENDA = A1.CODAGENDA);

  for V_REC_AG in (select CODAGENDA from TMP_NAGENDA) loop
    aANSFARSIT   := 0;
    aLUNASFARSIT := 0;

    for V_REC in (select CODAGENDA1, ANSTART, LUNASTART from TMP_NAGENDA1 WHERE CODAGENDA = V_REC_AG.CODAGENDA order BY ANSTART * 12 + LUNASTART desc) loop
      if (aANSFARSIT &lt;&gt; 0) and (aLUNASFARSIT &lt;&gt; 0) then
        update TMP_NAGENDA1
        set ANSFARSIT = aANSFARSIT,
          LUNASFARSIT = aLUNASFARSIT
        where
          CODAGENDA1 = V_REC.CODAGENDA1;
      end if;

      select newan,newluna from
      PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA (V_REC.ANSTART, V_REC.LUNASTART, aANSFARSIT, aLUNASFARSIT) into aANSFARSIT, aLUNASFARSIT;
    end loop;
  end loop;

  insert  into TMP_NPARTTR (CodPartTr, CodPart, Delegat, cnp, doc, SerieDoc, NrDoc, Eliberat, MijlTransp, NrTransp, ACTIV, DATADOC,
                            implicit, OBS, PERMIS, NRPASS, CODTARA, ADRESA, CODLOCALIT, TELEFON, EMAIL)
  select CodPartTr,
    CodPart,
    Delegat,
    cnp,
    doc,
    SerieDoc,
    NrDoc,
    Eliberat,
    MijlTransp,
    NrTransp,
    ACTIV,
    DATADOC,
    implicit,
    OBS,
    PERMIS,
    NRPASS,
    CODTARA,
    ADRESA,
    CODLOCALIT,
    TELEFON,
    EMAIL
  from NPARTTR
  where
    CodPart = RecId;

  insert  into TMP_NPERSCONTACT (codpersc, nume, prenume, telefon, email, functie, datanastere, SERIEBI, NRBI, ELIBERATBI, DATABI, CNP,
                                 rzona, id, tip, codbankcont, codpart, implicit, Obs, CODLOCATIE, NUMELOCATIE)
  SELECT codpersc,
         PC.nume,
         PC.prenume,
         PC.telefon,
         PC.email,
         PC.functie,
         PC.datanastere,
         PC.SERIEBI,
         PC.NRBI,
         PC.ELIBERATBI,
         PC.DATABI,
         PC.CNP,
         PC.rzona,
         PC.id,
         PC.tip,
         PC.codbankcont,
         PC.codpart,
         Coalesce(PC.implicit,0),
         PC.Obs,
         PC.CODLOCATIE,
         A.OBS
  from NPERSCONTACT PC
    LEFT JOIN NAGENDA A ON A.CODAGENDA = PC.CODLOCATIE
  WHERE PC.codpart = RecId;

  insert  into TMP_PARTTOT (CodPartTot, CodPart, SoldReal, Neoperat, anstart, lunastart)
  select CodPartTot, CodPart, SoldReal, Neoperat, anstart, lunastart
  from PARTTOT
  where
    CodPart = RecId
    and (select getdata.WME_RESULT from getdata (null, anstart, lunastart))
        =
        (select max ( (select getdata.WME_RESULT from getdata (null, anstart, lunastart)))
         from logusertab, PARTTOT
         where
           user = trim (upper (numeuser))
           and (select getdata.WME_RESULT from getdata (null, anstart, lunastart)) &lt;= (select getdata.WME_RESULT from getdata (null, ancurent, lunacurenta))
           and CodPart = RecId);

  insert  into TMP_SOLDPART (CodSoldPart, CodPart, CodCont, CodMoneda, SoldLei, SoldValuta, anstart, lunastart)
  select CodSoldPart, CodPart, CodCont, CodMoneda, SoldLei, SoldValuta, anstart, lunastart
  from SOLDPART
  where
    CodPart = RecId
    and (select getdata.WME_RESULT from getdata (null, anstart, lunastart))
        =
        (select max ( (select getdata.WME_RESULT from getdata (null, anstart, lunastart)))
         from logusertab, SOLDPART
         where
           user = trim (upper (numeuser))
           and (select getdata.WME_RESULT from getdata (null, anstart, lunastart)) &lt;= (select getdata.WME_RESULT from getdata (null, ancurent, lunacurenta))
           and CodPart = RecId);

  insert  into TMP_NPARTDISC (CodPartDisc, CodPart, CodCategDisc, Indexlocal, Cumulat, Offinvoice)
  select P.CodPartDisc, P.CodPart, P.CodCategDisc, P.Indexlocal,
         CASE when coalesce (D.PUNCTE, 0) = 0 then D.Cumulat end ,
         CASE when coalesce (D.PUNCTE, 0) = 1 then 5
              when coalesce (D.PUNCTE, 0) = 0 and coalesce (D.Offinvoice, 0) = 0 then 4
              else D.Offinvoice
         END
  from NPARTDISC P, CRITERIIDISC D
  where
    P.CodPart = RecId and D.CODCRITERIU = P.CodCategDisc;

  insert into TMP_NPARTTR_LNK (CODPARTTRLNK, CODPARTTR, CODPART, SEDII, DELEGAT, MIJLTRANSP, NRTRANSP)
  select LNK.CODPARTTRLNK, LNK.CODPARTTR, LNK.CODPART, LNK.SEDII, TR.DELEGAT, TR.MIJLTRANSP, TR.NRTRANSP
  from NPARTTR_LNK LNK, NPARTTR TR
  where
    LNK.CODPART = RECID and LNK.CODPARTTR = TR.CODPARTTR;

  insert  into TMP_NPARTTR_LNK1 (CODPARTTRLNK1, CODPARTTRLNK, CODAGENDA, SEDIU)
  select CODPARTTRLNK1, CODPARTTRLNK, AG.CODAGENDA, AG.OBS
  from NPARTTR_LNK1 LNK1, NAGENDA AG
  where
    AG.CODAGENDA = LNK1.CODAGENDA and exists (select CODPARTTRLNK from TMP_NPARTTR_LNK WHERE CODPARTTRLNK = LNK1.CODPARTTRLNK);

  for V_REC in (select  * from TMP_NAGENDA) loop
    if coalesce (V_REC.COD_CODFISCAL, 0) &lt;&gt; 0 then
      begin
        select coalesce (CODFISCAL, '') INTO ACODFISCAL from NPARTCODFISC WHERE COD_CODFISCAL = V_REC.COD_CODFISCAL;
      exception
      when others then
        ACODFISCAL := '?';
      end;

      if aCODFISCAL &lt;&gt; '?' then
        update TMP_NAGENDA set CODFISCAL = aCODFISCAL WHERE CODAGENDA = V_REC.CODAGENDA;
      end if;
    end if;
  end loop;

  DELETE from TMP_NPARTCONCURENTI;

  insert  into TMP_NPARTCONCURENTI (CodPartConcurent, CodPart, CodConcurent, DenConcurent, Codpart1crm)
  select PC.CodPartConcurent, PC.CodPart, PC.CodConcurent, C.DenConcurent, PC.Codpart1crm
  from NPARTCONCURENTI    PC
    inner join CONCURENTI C  on C.CodConcurent = PC.CodConcurent
    inner join NPART1CRM  P1 on P1.CODPART = PC.CODPART and P1.CODPART1CRM = PC.CODPART1CRM
  where
    PC.CodPart = RecId;

  DELETE from TMP_NPARTACTIVIT;

  insert  into TMP_NPARTACTIVIT (CodPartActivit, CodPart, Dim, CodActivit, DenActivit, Codpart1crm)
  select PA.CodPartActivit, PA.CodPart, PA.Dim, PA.CodActivit, A.Den_Activit, PA.Codpart1crm
  from NPARTACTIVIT     PA
    inner join NACTIVIT A on A.CodActivit = PA.CodActivit
  where
    PA.CodPart = RecId;

  DELETE from TMP_NPARTOPORTUNITATI;

  insert  into TMP_NPARTOPORTUNITATI (CodOportunitate, PrefixDoc, NrDoc, DataDoc, CodCarnetDoc, CodPartener, CodMoneda, Tip, CodAgent, VenitEst, VenitProb)
  select O.CodOportunitate, O.PrefixDoc, O.NrDoc, O.DataDoc, O.CodCarnetDoc, O.CodPartener, O.CodMoneda, O.Tip, O.CodAgent, O.VenitEst, O.VenitProb
  from OPORTUNITATI O
  where
    O.CodPartener = RecId;

  insert  into TMP_NPARTSUBUNIT (CODPARTSUBUNIT, CODPART, SUBUNITATEA, ZIAPROVIZ, PERAPROVIZ)
  select CODPARTSUBUNIT, CODPART, SUBUNITATEA, ZIAPROVIZ, PERAPROVIZ
  from NPARTSUBUNIT
  where
    CODPART = RECID
    and coalesce (SUBUNITATEA, 1) =
    case
      when (select PKG_GLOBALS_GETSUBUNITATE.WME_RESULT from PKG_GLOBALS_GETSUBUNITATE (null, null)) = 1 then coalesce (SUBUNITATEA, 1)
      else (select PKG_GLOBALS_GETSUBUNITATE.WME_RESULT from PKG_GLOBALS_GETSUBUNITATE (null, null))
    end;

  insert  into TMP_NPARTDOMACT (CODPARTDOMACT, CODPART, CODDOMENIUACT, DENDOMENIUACT, CODCAEN, CODPART1CRM)
  select D.CODPARTDOMACT, D.CODPART, D.CODDOMENIUACT, DA.DENDOMENIUACT, DA.CODCAEN, D.CODPART1CRM
  from NPARTDOMACT       D
    left join DOMENIIACT DA on DA.CODDOMENIUACT = D.CODDOMENIUACT
  where
    D.CODPART = RECID;

  insert  into TMP_NPART1CRM (codpart1crm, codpart, anstart, lunastart, cifraafaceri, nrangajati, lead, sursalead, Stare,
                              codresponsabil, MODPLATA, CIP, DATASTART, DATAEND, Profit)
  select codpart1crm, codpart, anstart, lunastart, cifraafaceri, nrangajati, lead, sursalead, coalesce (Stare, 0) ,
         codresponsabil, MODPLATA, CIP, DATASTART, DATAEND, Profit
  from npart1crm
  where
    codpart = recid;

  update TMP_NPART1CRM
  set DATASTART = to_date ('01.' || LUNASTART || '.' || ANSTART, 'dd.mm.yyyy')
  where
    DATASTART is NULL and ANSTART is not NULL and LUNASTART is not null;

  vInd := 0;
  for v_rec in (select  * from TMP_NPART1CRM order BY DataStart desc) loop
    if vInd &gt; 0 and V_REC.DATAEND is null then
      update Tmp_NPART1CRM set DataEnd = vDATA WHERE CODPART1CRM = v_rec.CODPART1CRM;
    end if;

    vDATA := v_rec.DATASTART - 1;
    vInd  := vInd            + 1;
  end loop;
  PERFORM PKG_CFGTABLES_EXT_GOTORECORD(500);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_sp_gotorecord</obj_name>
  <obj_hashval>fbdaf2848e775d7f981e9c5b4f0b66d7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  V_REC        RECORD;
  AANSFARSIT   numeric;
  ALUNASFARSIT numeric;
  ACODAGENDA   numeric;
  aCodFunctie  numeric := 0;
  vInd         numeric;
  vData        date;
BEGIN
  --Florin 12.04.2023 - sinc. Oracle
  --Bogdan 16.03.2023 - 57584 - PG - Nomenclator personal - eroare la detalii
  --Florin 07.03.2023 - sinc. Oracle
  --Florin 16.11.2021 - fixat 52001
  perform pkg_nompers_setct_monitor('MON_5');
  INSERT INTO TMP_NPERS (
    CODPERS,
    MARCA,
    NUME,
    PRENUME,
    CNP,
    BISERIA,
    BINR,
    LOCNASTERE,
    ADRESA,
    PRENUMET,
    PRENUMEM,
    LOCALITN,
    DATAN,
    SCIVILA,
    SMILITAR,
    ACTIV,
    STRAINATATE,
    AGENT,
    DELEGAT,
    LOGONNAME,
    ACCMAS,
    COMISION,
    CODGEST,
    AGENDA,
    BIELIBERATDE,
    LADATADE,
    TARAN,
    CETATENIE,
    codanalizanod,
    codanaliza,
    POZA,
    codsubunit,
    DataPlecarii,
    DataAngajarii,
    codloc,
    Obs,
    OrePeZi,
    CodCentru,
    codcatpret,
    IBAN,
    CodBank ) (
    select
      p.CODPERS,
      p.MARCA,
      p.NUME,
      p.PRENUME,
      p.CNP,
      p.BISERIA,
      p.BINR,
      p.LOCNASTERE,
      p.ADRESA,
      p.PRENUMET,
      p.PRENUMEM,
      p.LOCALITN,
      p.DATAN,
      p.SCIVILA,
      p.SMILITAR,
      coalesce( p.ACTIV, 1),
      p.STRAINATATE,
      p.AGENT,
      p.DELEGAT,
      p.LOGONNAME,
      p.ACCMAS,
      p.COMISION,
      p.CODGEST,
      p.AGENDA,
      p.BIELIBERATDE,
      p.LADATADE,
      p.TARAN,
      p.CETATENIE,
      p.codanalizanod,
      n.codanaliza,
      p.POZA,
      p.codsubunit,
      p.DataPlecarii,
      DataAngajarii,
      p.codloc,
      p.Obs,
      p.OrePeZi,
      P.CodCentru,
      p.codcatpret,
      P.IBAN,
      P.CodBank
    FROM NPERS p left join analizanod n ON n.codanalizanod = coalesce( p.codanalizanod, 0)
    WHERE p.CODPERS = RECID );

  SELECT AGENDA INTO ACODAGENDA FROM TMP_NPERS;

  INSERT INTO TMP_NPERS1 (
    CODPERS1,
    CODPERS,
    CODIOPERS,
    CODFORMATIE,
    CODFUNCTIE,
    CODMESERIE,
    ANSTART,
    LUNASTART,
    SCHIMB ) (
    select
      CODPERS1,
      CODPERS,
      CODIOPERS,
      CODFORMATIE,
      CODFUNCTIE,
      CODMESERIE,
      ANSTART,
      LUNASTART,
      SCHIMB
    FROM NPERS1
    WHERE CODPERS = RECID );

  INSERT INTO TMP_NAGENDA_PERS (
    obs,
    codagenda,
    tip,
    codlocalit,
    sediusocial,
    telefon,
    fax,
    email,
    sector,
    strada,
    nr1,
    nr2,
    bloc,
    scara,
    etaj,
    apart,
    codpostal,
    km,
    codbankcont,
    codpart,
    codgest,
    codsubunit,
    codtraseu,
    poztraseu,
    adresa,
    telefonp ) (
    select
      obs,
      codagenda,
      tip,
      codlocalit,
      sediusocial,
      telefon,
      fax,
      email,
      sector,
      strada,
      nr1,
      nr2,
      bloc,
      scara,
      etaj,
      apart,
      codpostal,
      km,
      codbankcont,
      codpart,
      codgest,
      codsubunit,
      codtraseu,
      poztraseu,
      (SELECT GetAdresa.WME_RESULT FROM GetAdresa(null, sector, strada, nr1, nr2, bloc, scara, etaj, apart, codpostal)),
      telefonp
    FROM NAGENDA
    WHERE CODAGENDA = ACODAGENDA );

  INSERT INTO TMP_NPERSCURSX (
    CODNPERSCURS,
    CODPERS,
    CODFUNCTIE,
    CODCURS,
    CODTEMA,
    STARE,
    data,
    NOTA,
    DATAPLAN,
    ORE_REALIZ,
    SUPLIM,
    DEN_CURS,
    DEN_TEMA,
    SSTARE,
    ORE_AFER,
    TipFormare,
    NivelFormare,
    CodObiectiv,
    Den_Obiectiv )
  with CF as (SELECT distinct P1.CodPers, F1.CodCurs, F1.CodTema, 0 SUPLIM
              FROM TMP_NPERS1 P1 inner join FUNCTII1 F1 ON F1.CodFunctie = P1.Codfunctie ),
       PC as (SELECT NP.CodPers, NP.CODNPERSCURS, coalesce( NP.codfunctie, 0) CODFUNCTIE, NP.CodCurs, NP.CodTema, coalesce( NP.STARE, 0) STARE,
                     CASE when coalesce( NP.codfunctie, 0) = 0 then 1 else 0 end SUPLIM,
                     NP.Nota, NP.Data, NP.DataPlan, NP.TipFormare, NP.NivelFormare, NP.CodObiectiv, NP.ORE_REALIZ
              FROM NPERSCURS NP WHERE NP.CodPers = RecID )
  select
    TMP.CODNPERSCURS,
    TMP.CODPERS,
    TMP.CodFunctie,
    TMP.CODCURS,
    TMP.CODTEMA,
    TMP.STARE,
    TMP.DATA,
    TMP.NOTA,
    TMP.DATAPLAN,
    TMP.ORE_REALIZ,
    TMP.Suplim,
    CC.DEN_CURS,
    TT.DEN_TEMA,
    'xxxxxxxxxx',
    TT.ORE,
    TMP.TipFormare,
    TMP.NivelFormare,
    TMP.CodObiectiv,
    O.Den_Obiectiv
  from
    (
    select
      PC.CODNPERSCURS,
      PC.CodPers,
      coalesce( PC.CodFunctie, 0) CODFUNCTIE,
      PC.CodCurs,
      PC.CodTema,
      PC.DATA,
      PC.DATAPLAN,
      PC.ORE_REALIZ,
      coalesce( PC.STARE, 0) STARE,
      PC.Nota,
      PC.Suplim,
      coalesce( PC.TipFormare, 0) TIPFORMARE,
      coalesce( PC.NivelFormare, 0) NIVELFORMARE,
      coalesce( PC.CodObiectiv, 0) CODOBIECTIV
    FROM PC
  union all
    select
      --Row_NumBER OVER () CODNPERSCURS,
      -row_number() over (
      order by CF.CODPERS) CODNPERSCURS,
      CF.CODPERS,
      -1 CODFUNCTIE,
      coalesce( CF.CodCurs, 0) CODCURS,
      coalesce( CF.CodTema, 0) CODTEMA,
      null as data,
      null DATAPLAN,
      0 ORE_REALIZ,
      0 STARE,
      null NOTA,
      0 SUPLIM,
      0 TIPFORMARE,
      0 NIVELFORMARE,
      0 CODOBIECTIV
    FROM CF
    where
      not exists (SELECT CodNPERSCURS FROM NPERSCURS WHERE coalesce( CodFunctie, 0) &lt;&gt; 0 and CodCurs = CF.CodCurs and CodTema = CF.CodTema and Codpers = CF.CodPers )
    ) TMP
    left join CURSURI   CC ON CC.CodCurs = TMP.CodCurs
    left join TEME      TT ON TT.CodTema = TMP.CodTEMA
    left join OBIECTIVE O  ON O.CodObiectiv = TMP.CodObiectiv;

  INSERT INTO TMP_NPERSCVSCOL ( CODPERSCVSCOL, CODPERS, INDEXLOCAL, DELA, PANALA, SCOALA )
  (SELECT CODPERSCVSCOL, CODPERS, INDEXLOCAL, DELA, PANALA, SCOALA FROM NPERSCVSCOL WHERE CODPERS = RECID );

  INSERT INTO TMP_NPERSCVLOCM ( CODPERSCVLOCM, CODPERS, INDEXLOCAL, DELA, PANALA, LOCMUNCA, CODFISCAL )
  (SELECT CODPERSCVLOCM, CODPERS, INDEXLOCAL, DELA, PANALA, LOCMUNCA, CODFISCAL FROM NPERSCVLOCM WHERE CODPERS = RECID );

  INSERT INTO TMP_NPERSCVSKIL ( CODPERSCVSKIL, CODPERS, INDEXLOCAL, SKILL )
  (SELECT CODPERSCVSKIL, CODPERS, INDEXLOCAL, SKILL FROM NPERSCVSKIL WHERE CODPERS = RECID );

  INSERT INTO TMP_NPERSCVPAS ( CODPERSCVPAS, CODPERS, INDEXLOCAL, PASIUNE )
  (SELECT CODPERSCVPAS, CODPERS, INDEXLOCAL, PASIUNE FROM NPERSCVPAS WHERE CODPERS = RECID );

  INSERT INTO TMP_NAGENTI1 ( CODAGENT1, CODPERS, DATASTART )
  SELECT CODAGENT1, CODPERS, DATASTART FROM NAGENTI1 WHERE CODPERS = RECID;

  vInd := 0;

  for v_rec in (SELECT * FROM NAGENTI1 WHERE CODPERS = RECID order BY DataStart desc ) loop
    if vInd &gt; 0 then
      UPDATE Tmp_NAGENTI1 SET DataEnd = vDATA WHERE CODAGENT1 = v_rec.CODAGENT1 ;
    end if;

    vDATA := (v_rec.DATASTART - 1)::date ;
    vInd := vInd + 1;
  end loop;

  INSERT INTO TMP_NAGENTIPROC ( CODAGENTPROC, CODAGENT1, CODPERS, CODOBIECT, PECLASEA, CODPART, PECLASEP, PROC )
  SELECT CODAGENTPROC, CODAGENT1, CODPERS, CODOBIECT, PECLASEA, CODPART, PECLASEP, PROC FROM NAGENTIPROC WHERE CODPERS = RECID;

  for V_REC in (SELECT TMP.CODAGENTPROC, O.DENUMIRE DENART
                FROM TMP_NAGENTIPROC TMP left join NARTOBJ O ON TMP.CODOBIECT = O.CODOBIECT
                WHERE coalesce( TMP.PECLASEA, 0) = 0
                union all
                SELECT TMP.CODAGENTPROC, CLS.DEN_CLASEA DENART
                FROM TMP_NAGENTIPROC TMP left join NCLASEA CLS ON TMP.CODOBIECT = CLS.CODCLASEA
                WHERE TMP.PECLASEA = 1
               )
  loop
    UPDATE TMP_NAGENTIPROC SET DENART = V_REC.DENART WHERE CODAGENTPROC = V_REC.CODAGENTPROC ;
  end loop;

  for V_REC in (SELECT TMP.CODAGENTPROC, P.DEN_PART DENPART
                FROM TMP_NAGENTIPROC TMP left join NPART P ON TMP.CODPART = P.CODPART
                WHERE coalesce( TMP.PECLASEP, 0) = 0
                union all
                SELECT TMP.CODAGENTPROC, CLS.DEN_CLASEP DENPART
                FROM TMP_NAGENTIPROC TMP left join NCLASEP CLS ON TMP.CODPART = CLS.CODCLASEP
                WHERE TMP.PECLASEP = 1
               )
  loop
    UPDATE TMP_NAGENTIPROC SET DENPART = V_REC.DENPART WHERE CODAGENTPROC = V_REC.CODAGENTPROC ;
  end loop;

  INSERT INTO TMP_NAGENTIVAL ( CODAGENTVAL, CODAGENT1, CODPERS, CODMONEDA, VALMAX, SIMBOL )
  SELECT V.CODAGENTVAL, V.CODAGENT1, V.CODPERS, V.CODMONEDA, V.VALMAX, M.SIMBOL
  FROM NAGENTIVAL V inner join NMONEDE M ON V.CODMONEDA = M.CODMONEDA
  WHERE V.CODPERS = RECID;

  AANSFARSIT   := 0;
  ALUNASFARSIT := 0;

  for V_REC in (SELECT CODPERS1, ANSTART, LUNASTART FROM TMP_NPERS1 order BY ANSTART * 12 + LUNASTART desc ) loop
    if ( AANSFARSIT &lt;&gt; 0) and ( ALUNASFARSIT &lt;&gt; 0) then
      UPDATE TMP_NPERS1
      SET
      ANSFARSIT   = AANSFARSIT,
      LUNASFARSIT = ALUNASFARSIT
      WHERE CODPERS1 = V_REC.CODPERS1 ;
    end if;

    SELECT NEWAN, NEWLUNA INTO aANSFARSIT, aLUNASFARSIT
    FROM PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA( V_REC.ANSTART, V_REC.LUNASTART, AANSFARSIT, ALUNASFARSIT);
  end loop;

  IF fnc_TmpExists('NPERSEXT') = 1 AND fnc_TmpExists('TMP_NPERSEXT') = 1 THEN
     DELETE FROM TMP_NPERSEXT;
   EXECUTE 'INSERT INTO TMP_NPERSEXT SELECT * FROM NPERSEXT WHERE CODPERS = '||RECID;
  END IF;
  PERFORM PKG_CFGTABLES_EXT_GOTORECORD(502);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_sp_postrecords</obj_name>
  <obj_hashval>805b2b950f042d57efb01cf63cba02ad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC      RECORD;
  ACODAGENDA numeric;
  Acount     numeric;
  aDoc       varchar;
  ACOD       numeric;
BEGIN
  --Florin 01.06.2023 - monitor
  --Florin 12.04.2023 - sinc. Oracle
  --Bogdan 16.03.2023 - 57584 - PG - Nomenclator personal - eroare la detalii
  --Florin 07.03.2023 - sinc. Oracle
  --Adina 11.03.2021 - add prc_al_refresh
  --Florin 214.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_nompers_setct_monitor('MON_5');
  SELECT 'Persoana "' || Nume || ' ' || Prenume || '"' INTO aDoc FROM TMP_NPERS;
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT (502);

  IF  OPERATION = 0 THEN
    SELECT CODPERS INTO RECID FROM TMP_NPERS;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_NOMPERS.CT_MONITOR', true))))
    THEN
      PERFORM pkg_userfirme_postlogcucommit( 'NPERS', (current_setting('PKG_GLOBALS.USERNAME', true)), 'M', RECID, (current_setting('PKG_GLOBALS.FIRMANAME', true)), TO_NUMBER((current_setting('PKG_GLOBALS.SUBUNITATE', true)),'999999999999999999'), null, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    UPDATE NPERS
    SET
    (CODPERS, MARCA, NUME, PRENUME, CNP, BISERIA, BINR, LOCNASTERE, ADRESA, PRENUMET, PRENUMEM, LOCALITN, DATAN, SCIVILA, SMILITAR, ACTIV, STRAINATATE, AGENT, DELEGAT, LOGONNAME, ACCMAS, COMISION, CODGEST, AGENDA, BIELIBERATDE, LADATADE, TARAN, CETATENIE, codanalizanod, POZA, CODSUBUNIT, DataPlecarii, DataAngajarii, CODLOC, OBS, OrePeZi, CodCentru,
     CodCatPret,IBAN,CodBank)
    =
    (
    SELECT CODPERS, MARCA, NUME, PRENUME, CNP, BISERIA, BINR, LOCNASTERE, ADRESA, PRENUMET, PRENUMEM, LOCALITN, DATAN, SCIVILA, SMILITAR, ACTIV, STRAINATATE, AGENT, DELEGAT, LOGONNAME, ACCMAS, COMISION, CODGEST, AGENDA, BIELIBERATDE, LADATADE, TARAN, CETATENIE, codanalizanod, POZA, CODSUBUNIT, DataPlecarii, DataAngajarii, CODLOC, OBS, OrePeZi, CodCentru,
     CodCatPret,IBAN,CodBank
    FROM TMP_NPERS
    )
    WHERE
     CODPERS = RECID;

    DELETE FROM NPERS1 WHERE CODPERS = RECID AND CODPERS1 NOT IN (SELECT CODPERS1 FROM TMP_NPERS1);

    INSERT INTO NPERS1(CODPERS1, CODPERS, CODIOPERS, CODFORMATIE, CODFUNCTIE, CODMESERIE, ANSTART, LUNASTART, SCHIMB)
    SELECT NEXTVAL('SEQ_NPERS1_CODPERS1'), RECID, CODIOPERS, CODFORMATIE, CODFUNCTIE, CODMESERIE, ANSTART, LUNASTART, SCHIMB
    FROM TMP_NPERS1 WHERE CODPERS1 &lt; 0;

    DELETE FROM NPERSCVSCOL WHERE CODPERS = RECID AND CODPERSCVSCOL NOT IN (SELECT CODPERSCVSCOL FROM TMP_NPERSCVSCOL);

    INSERT INTO NPERSCVSCOL(CODPERSCVSCOL, CODPERS, INDEXLOCAL, DELA, PANALA, SCOALA)
    (SELECT NEXTVAL('SEQ_NPERSCVSCOL_CODPERSCVSCOL'), RECID, INDEXLOCAL, DELA, PANALA, SCOALA FROM TMP_NPERSCVSCOL WHERE CODPERSCVSCOL &lt; 0);

    FOR v_rec IN (SELECT * FROM TMP_NPERSCVSCOL WHERE COALESCE( codPERSCVSCOL, -1) &gt; 0 ORDER BY codPERSCVSCOL) LOOP
      UPDATE NPERSCVSCOL
      SET
      CODPERSCVSCOL = v_rec.CODPERSCVSCOL,
      CODPERS       = v_rec.CODPERS,
      INDEXLOCAL    = v_rec.INDEXLOCAL,
      DELA          = v_rec.DELA,
      PANALA        = v_rec.PANALA,
      SCOALA        = v_rec.scoala
      WHERE
       CODPERSCVSCOL = v_rec.CODPERSCVSCOL;
    END LOOP;

    DELETE FROM NPERSCVLOCM WHERE CODPERS = RECID AND CODPERSCVLOCM NOT IN (SELECT CODPERSCVLOCM FROM TMP_NPERSCVLOCM);

    INSERT INTO NPERSCVLOCM(CODPERSCVLOCM, CODPERS, INDEXLOCAL, DELA, PANALA, LOCMUNCA, CODFISCAL)
    (SELECT NEXTVAL('SEQ_NPERSCVLOCM_CODPERSCVLOCM'), RECID, INDEXLOCAL, DELA, PANALA, LOCMUNCA, CODFISCAL FROM TMP_NPERSCVLOCM WHERE CODPERSCVLOCM &lt; 0);

    FOR v_rec IN (SELECT * FROM TMP_NPERSCVLOCM WHERE COALESCE( codPERSCVLOCM, -1) &gt; 0 ORDER BY codPERSCVLOCM) LOOP
      UPDATE NPERSCVLOCM
      SET
      CODPERSCVLOCM = v_rec.CODPERSCVLOCM,
      CODPERS       = v_rec.CODPERS,
      INDEXLOCAL    = v_rec.INDEXLOCAL,
      DELA          = v_rec.DELA,
      PANALA        = v_rec.PANALA,
      LOCMUNCA      = v_rec.LOCMUNCA,
      CODFISCAL     = v_rec.Codfiscal
      WHERE
       CODPERSCVLOCM = v_rec.CODPERSCVLOCM;
    END LOOP;

    DELETE FROM NPERSCVSKIL WHERE CODPERS = RECID AND CODPERSCVSKIL NOT IN (SELECT CODPERSCVSKIL FROM TMP_NPERSCVSKIL);

    INSERT INTO NPERSCVSKIL(CODPERSCVSKIL, CODPERS, INDEXLOCAL, SKILL)
    (SELECT NEXTVAL('SEQ_NPERSCVSKIL_CODPERSCVSKIL'), RECID, INDEXLOCAL, SKILL FROM TMP_NPERSCVSKIL WHERE CODPERSCVSKIL &lt; 0);

    FOR v_rec IN (SELECT * FROM TMP_NPERSCVSKIL WHERE COALESCE( codPERSCVSKIL, -1) &gt; 0 ORDER BY codPERSCVSKIL) LOOP
      UPDATE NPERSCVSKIL
      SET
      CODPERSCVSKIL = v_rec.CODPERSCVSKIL,
      CODPERS       = v_rec.CODPERS,
      INDEXLOCAL    = v_rec.INDEXLOCAL,
      SKILL         = v_rec.SKILL
      WHERE
       CODPERSCVSKIL = v_rec.CODPERSCVSKIL;
    END LOOP;

    DELETE FROM NPERSCVPAS WHERE CODPERS = RECID AND CODPERSCVPAS NOT IN (SELECT CODPERSCVPAS FROM TMP_NPERSCVPAS);

    INSERT INTO NPERSCVPAS(CODPERSCVPAS, CODPERS, INDEXLOCAL, PASIUNE)
    (SELECT NEXTVAL('SEQ_NPERSCVPAS_CODPERSCVPAS'), RECID, INDEXLOCAL, PASIUNE FROM TMP_NPERSCVPAS WHERE CODPERSCVPAS &lt; 0);

    FOR v_rec IN (SELECT * FROM TMP_NPERSCVPAS WHERE COALESCE( codPERSCVPAS, -1) &gt; 0 ORDER BY codPERSCVPAS) LOOP
      UPDATE NPERSCVPAS
      SET
      CODPERSCVPAS = v_rec.CODPERSCVPAS,
      CODPERS      = v_rec.CODPERS,
      INDEXLOCAL   = v_rec.INDEXLOCAL,
      PASIUNE      = v_rec.PASIUNE
      WHERE
       CODPERSCVPAS = v_rec.CODPERSCVPAS;
    END LOOP;

    SELECT COALESCE( AGENDA, -1) INTO ACODAGENDA FROM NPERS WHERE CODPERS = RECID;

    IF  ACODAGENDA = -1 THEN
      SELECT NEXTVAL('SEQ_NAGENDA_CODAGENDA') INTO ACODAGENDA;

      INSERT INTO NAGENDA(obs, codagenda, tip, codlocalit, sediusocial, telefon, fax, email, sector, strada, nr1, nr2, bloc, scara, etaj, apart, codpostal, km, codbankcont, codpart, codgest, codsubunit, codtraseu, poztraseu, telefonp)
      (SELECT obs, ACODAGENDA, tip, codlocalit, sediusocial, telefon, fax, email, sector, strada, nr1, nr2, bloc, scara, etaj, apart, codpostal, km, codbankcont, codpart, codgest, codsubunit, codtraseu, poztraseu, telefonp
       FROM TMP_NAGENDA_PERS
      );

      UPDATE npers SET agenda = acodagenda WHERE codpers = recid;
    ELSE
      SELECT count( *) INTO acount FROM nagenda WHERE codagenda = acodagenda;

      IF  acount = 0 THEN
        INSERT INTO NAGENDA(obs, codagenda, tip, codlocalit, sediusocial, telefon, fax, email, sector, strada, nr1, nr2, bloc, scara, etaj, apart, codpostal, km, codbankcont, codpart, codgest, codsubunit, codtraseu, poztraseu, telefonp)
        (SELECT obs, ACODAGENDA, tip, codlocalit, sediusocial, telefon, fax, email, sector, strada, nr1, nr2, bloc, scara, etaj, apart, codpostal, km, codbankcont, codpart, codgest, codsubunit, codtraseu, poztraseu, telefonp
         FROM TMP_NAGENDA_PERS
        );
      ELSE
        UPDATE NAGENDA
        SET
        (obs, tip, codlocalit, sediusocial, telefon, fax, email, sector, strada, nr1, nr2, bloc, scara, etaj, apart, codpostal, km, codbankcont, codpart, codgest, codsubunit, codtraseu, poztraseu, telefonp)
        =
        (
        SELECT obs, tip, codlocalit, sediusocial, telefon, fax, email, sector, strada, nr1, nr2, bloc, scara, etaj, apart, codpostal, km, codbankcont, codpart, codgest, codsubunit, codtraseu, poztraseu, telefonp
        FROM TMP_NAGENDA_PERS
        )
        WHERE
         codagenda = Acodagenda;
      END IF;
    END IF;

    FOR V_REC IN (SELECT * FROM TMP_NPERS1 WHERE COALESCE( CODPERS1, 0) &gt; 0 ORDER BY CODPERS1) LOOP
      UPDATE NPERS1
      SET
      CODIOPERS   = V_REC.CODIOPERS,
      CODFORMATIE = V_REC.CODFORMATIE,
      CODFUNCTIE  = V_REC.CODFUNCTIE,
      CODMESERIE  = V_REC.CODMESERIE,
      ANSTART     = V_REC.ANSTART,
      LUNASTART   = V_REC.LUNASTART,
      SCHIMB      = V_REC.SCHIMB
      WHERE
       CODPERS1 = V_REC.CODPERS1;
    END LOOP;

    DELETE FROM NAGENTI1 AG1 WHERE AG1.CODPERS = RECID AND  NOT  EXISTS (SELECT TMP.CODAGENT1 FROM TMP_NAGENTI1 TMP WHERE TMP.CODAGENT1 = AG1.CODAGENT1);

    FOR V_REC IN (SELECT * FROM TMP_NAGENTI1) LOOP
      IF  V_REC.CODAGENT1 &gt; 0 THEN
        UPDATE NAGENTI1 SET DATASTART = V_REC.DATASTART WHERE CODAGENT1 = V_REC.CODAGENT1;
      ELSE
        SELECT NEXTVAL('SEQ_NAGENTI1_CODAGENT1') INTO ACOD;

        UPDATE TMP_NAGENTIVAL  SET CODAGENT1 = ACOD WHERE CODAGENT1 = V_REC.CODAGENT1;
        UPDATE TMP_NAGENTIPROC SET CODAGENT1 = ACOD WHERE CODAGENT1 = V_REC.CODAGENT1;

        INSERT INTO NAGENTI1(CODAGENT1, CODPERS, DATASTART)
        VALUES(ACOD, RECID, V_REC.DATASTART);
      END IF;
    END LOOP;

    DELETE FROM NAGENTIVAL AGV WHERE AGV.CODPERS = RECID AND  NOT  EXISTS (SELECT TMP.CODAGENTVAL FROM TMP_NAGENTIVAL TMP WHERE TMP.CODAGENTVAL = AGV.CODAGENTVAL);

    FOR V_REC IN (SELECT * FROM TMP_NAGENTIVAL) LOOP
      IF  V_REC.CODAGENTVAL &gt; 0 THEN
        UPDATE NAGENTIVAL
        SET
        CODMONEDA = V_REC.CODMONEDA,
        VALMAX    = V_REC.VALMAX
        WHERE
         CODAGENTVAL = V_REC.CODAGENTVAL;
      ELSE
        INSERT INTO NAGENTIVAL(CODAGENTVAL, CODAGENT1, CODPERS, CODMONEDA, VALMAX)
        VALUES(NEXTVAL('SEQ_NAGENTIVAL_CODAGENTVAL'), V_REC.CODAGENT1, RECID, V_REC.CODMONEDA, V_REC.VALMAX);
      END IF;
    END LOOP;

    DELETE FROM NAGENTIPROC AGP WHERE AGP.CODPERS = RECID AND  NOT  EXISTS (SELECT TMP.CODAGENTPROC FROM TMP_NAGENTIPROC TMP WHERE TMP.CODAGENTPROC = AGP.CODAGENTPROC);

    FOR V_REC IN (SELECT * FROM TMP_NAGENTIPROC) LOOP
      IF  V_REC.CODAGENTPROC &gt; 0 THEN
        UPDATE NAGENTIPROC
        SET
        CODOBIECT = V_REC.CODOBIECT,
        PECLASEA  = V_REC.PECLASEA,
        CODPART   = V_REC.CODPART,
        PECLASEP  = V_REC.PECLASEP,
        PROC      = V_REC.PROC
        WHERE
         CODAGENTPROC = V_REC.CODAGENTPROC;
      ELSE
        INSERT INTO NAGENTIPROC(CODAGENTPROC, CODAGENT1, CODPERS, CODOBIECT, PECLASEA, CODPART, PECLASEP, PROC)
        VALUES(NEXTVAL('SEQ_NAGENTIPROC_CODAGENTPROC'), V_REC.CODAGENT1, RECID, V_REC.CODOBIECT, V_REC.PECLASEA, V_REC.CODPART, V_REC.PECLASEP, V_REC.PROC);
      END IF;
    END LOOP;
  ELSE
    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_NOMPERS.CT_MONITOR', true))))
    THEN
      PERFORM pkg_userfirme_postlogcucommit( 'NPERS', (current_setting('PKG_GLOBALS.USERNAME', true)), 'A', RECID, (current_setting('PKG_GLOBALS.FIRMANAME', true)), TO_NUMBER((current_setting('PKG_GLOBALS.SUBUNITATE', true)),'999999999999999999'), null, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    SELECT NEXTVAL('SEQ_NPERS_CODPERS')     INTO RECID;
    PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('NPERS', RecId);
    SELECT NEXTVAL('SEQ_NAGENDA_CODAGENDA') INTO ACODAGENDA;

    INSERT INTO NPERS(CODPERS, MARCA, NUME, PRENUME, CNP, BISERIA, BINR, LOCNASTERE, ADRESA, PRENUMET, PRENUMEM, LOCALITN, DATAN, SCIVILA, SMILITAR, ACTIV, STRAINATATE, AGENT, DELEGAT, LOGONNAME, ACCMAS, COMISION, CODGEST, AGENDA, BIELIBERATDE, LADATADE, TARAN, CETATENIE, codanalizanod, POZA, CODSUBUNIT, DataPlecarii, DataAngajarii, CODLOC, OBS, OrePeZi, CodCentru,
                      CodCatPret,IBAN,CodBank
                     )
    (SELECT RecId, MARCA, NUME, PRENUME, CNP, BISERIA, BINR, LOCNASTERE, ADRESA, PRENUMET, PRENUMEM, LOCALITN, DATAN, SCIVILA, SMILITAR, ACTIV, STRAINATATE, AGENT, DELEGAT, LOGONNAME, ACCMAS, COMISION, CODGEST, ACODAGENDA, BIELIBERATDE, LADATADE, TARAN, CETATENIE, codanalizanod, POZA, CODSUBUNIT, DataPlecarii, DataAngajarii, CODLOC, OBS, OrePeZi, CodCentru,
            CodCatPret,IBAN,CodBank
     FROM TMP_NPERS
    );

    INSERT INTO NPERS1(CODPERS1, CODPERS, CODIOPERS, CODFORMATIE, CODFUNCTIE, CODMESERIE, ANSTART, LUNASTART, SCHIMB)
    (SELECT NEXTVAL('SEQ_NPERS1_CODPERS1'), RECID, CODIOPERS, CODFORMATIE, CODFUNCTIE, CODMESERIE, ANSTART, LUNASTART, SCHIMB FROM TMP_NPERS1);

    INSERT INTO NPERSCVSCOL(CODPERSCVSCOL, CODPERS, INDEXLOCAL, DELA, PANALA, SCOALA)
    (SELECT NEXTVAL('SEQ_NPERSCVSCOL_CODPERSCVSCOL'), RecId, INDEXLOCAL, DELA, PANALA, SCOALA FROM TMP_NPERSCVSCOL);

    INSERT INTO NPERSCVLOCM(CODPERSCVLOCM, CODPERS, INDEXLOCAL, DELA, PANALA, LOCMUNCA, CODFISCAL)
    (SELECT NEXTVAL('SEQ_NPERSCVLOCM_CODPERSCVLOCM'), RECID, INDEXLOCAL, DELA, PANALA, LOCMUNCA, CODFISCAL FROM TMP_NPERSCVLOCM);

    INSERT INTO NPERSCVSKIL(CODPERSCVSKIL, CODPERS, INDEXLOCAL, SKILL)
    (SELECT NEXTVAL('SEQ_NPERSCVSKIL_CODPERSCVSKIL'), RECID, INDEXLOCAL, SKILL FROM TMP_NPERSCVSKIL);

    INSERT INTO NPERSCVPAS(CODPERSCVPAS, CODPERS, INDEXLOCAL, PASIUNE)
    (SELECT NEXTVAL('SEQ_NPERSCVPAS_CODPERSCVPAS'), RECID, INDEXLOCAL, PASIUNE FROM TMP_NPERSCVPAS);

    INSERT INTO NAGENDA(codagenda, tip, codlocalit, sediusocial, telefon, fax, email, sector, strada, nr1, nr2, bloc, scara, etaj, apart, codpostal, km, codbankcont, codpart, codgest, codsubunit, obs, codtraseu, poztraseu, telefonp)
    (SELECT ACODAGENDA, tip, codlocalit, sediusocial, telefon, fax, email, sector, strada, nr1, nr2, bloc, scara, etaj, apart, codpostal, km, codbankcont, codpart, codgest, codsubunit, obs, codtraseu, poztraseu, telefonp
     FROM TMP_NAGENDA_PERS
    );

    FOR V_REC IN (SELECT * FROM TMP_NAGENTI1) LOOP
      SELECT NEXTVAL('SEQ_NAGENTI1_CODAGENT1') INTO ACOD;

      UPDATE TMP_NAGENTIVAL  SET CODAGENT1 = ACOD WHERE CODAGENT1 = V_REC.CODAGENT1;
      UPDATE TMP_NAGENTIPROC SET CODAGENT1 = ACOD WHERE CODAGENT1 = V_REC.CODAGENT1;

      INSERT INTO NAGENTI1(CODAGENT1, CODPERS, DATASTART)
      VALUES(ACOD, RECID, V_REC.DATASTART);
    END LOOP;

    INSERT INTO NAGENTIVAL(CODAGENTVAL, CODAGENT1, CODPERS, CODMONEDA, VALMAX)
    SELECT NEXTVAL('SEQ_NAGENTIVAL_CODAGENTVAL'), CODAGENT1, RECID, CODMONEDA, VALMAX FROM TMP_NAGENTIVAL;

    INSERT INTO NAGENTIPROC(CODAGENTPROC, CODAGENT1, CODPERS, CODOBIECT, PECLASEA, CODPART, PECLASEP, PROC)
    SELECT NEXTVAL('SEQ_NAGENTIPROC_CODAGENTPROC'), CODAGENT1, RECID, CODOBIECT, PECLASEA, CODPART, PECLASEP, PROC FROM TMP_NAGENTIPROC;
  END IF;

  CALL PRC_AL_REFRESH('npers1', RECID);
  PERFORM NotifyModif( OPERATION, RECID, 'NPERS');

  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS(502);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_adaugastruct</obj_name>
  <obj_hashval>6df3dbd92c9719189f40a3b5c2297889</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_adaugastruct(acodncredit1 numeric, acodies1 numeric, aval numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  aCodPart     numeric;
  aCodLocatie  numeric;
  aDataDoc     date;
  aSubunitate  numeric;
  aCodObiect   numeric;
  aCant        numeric;
  aCodDiscount numeric;
  aCodClasa    numeric;
  aCount       numeric;
  aProc        numeric;
BEGIN
  --Adina 18.05.2021 - sinc.Oracle din 17.05.2021
  SELECT i.partener, i.codlocatie, i.datadoc, i.subunitatea, i1.codobiect, i1.cant, COALESCE(a.clasa, 0)
  INTO aCodPart, aCodLocatie, aDataDoc, aSubunitate, aCodObiect, aCant, aCodClasa
  FROM iesiri1 i1
      INNER JOIN iesiri  i ON  i1.codies    = i.codies
      INNER JOIN nartobj o ON  o.codobiect  = i1.codobiect
      INNER JOIN nart    a ON  a.codarticol = o.codarticol
  WHERE i1.codies1 = aCodIes1;

  SELECT count(*) INTO aCount FROM TMP_NCVDISC_VOL WHERE codobiect = aCodObiect;

  IF  aCount = 0 THEN
    INSERT INTO tmp_ncvdisc_vol(codobiect, valoare)
    VALUES(aCodObiect, aVal);
  ELSE
    UPDATE tmp_ncvdisc_vol SET Valoare = COALESCE(Valoare, 0) + aVal;
  END IF;

  FOR v_rec IN
  (
    SELECT  DISTINCT d.coddiscount, di.procent
    FROM NPARTDISC PD
        INNER JOIN criteriidisc   CD  ON  PD.CODCATEGDISC = CD.CODCRITERIU
        INNER JOIN criteriidisc1  CD1 ON  CD.CODCRITERIU  = CD1.CODCRITERIU
        INNER JOIN DISCOUNT       D   ON  CD.CODCRITERIU  = D.CODCRITERIU AND  CD1.CODCRITERIU1 = D.CODCRITERIU1
        INNER JOIN DISCINTERVAL   DI  ON  DI.CODDISCOUNT  = D.CODDISCOUNT
        INNER JOIN DISCART        DA  ON  DA.CODDISCOUNT  = D.CODDISCOUNT AND  DA.CODOBIECT     = aCODOBIECT
        LEFT  JOIN NAGENDA        AG  ON  D.CODTIPSEDIU   = AG.CODTIPSEDIU
    WHERE CD.peclase = 0 and  CD.offinvoice = 1 and (AG.CODAGENDA = aCodLocatie or  COALESCE(D.Codtipsediu, 0) = 0)
      and CD1.Subunitatea = aSubunitate and  PD.CodPart = aCodPart and  cd.tipinterval = 0
  )
  LOOP
    SELECT count(*) INTO aCount FROM TMP_NCVDISC WHERE codncredit1 = aCodNCredit1 and  coddiscount = v_rec.CodDiscount;

    IF  aCount = 0 THEN
      INSERT INTO tmp_ncvdisc(codncredit1, coddiscount)
      VALUES(acodncredit1, v_rec.coddiscount);
    END IF;

    SELECT count(*) INTO aCount FROM TMP_NCVDISC_MAN WHERE coddiscount = v_rec.CodDiscount;

    IF  aCount = 0 THEN
      INSERT INTO tmp_ncvdisc_man(coddiscount, proc)
      VALUES(v_rec.CodDiscount, v_rec.procent);
    END IF;
  END LOOP;

  BEGIN
    SELECT  DISTINCT d.coddiscount
    INTO aCodDiscount
    FROM NPARTDISC PD
      INNER JOIN criteriidisc   CD  ON  PD.CODCATEGDISC = CD.CODCRITERIU
      INNER JOIN criteriidisc1  CD1 ON  CD.CODCRITERIU  = CD1.CODCRITERIU
      INNER JOIN DISCOUNT       D   ON  CD.CODCRITERIU  = D.CODCRITERIU AND  CD1.CODCRITERIU1 = D.CODCRITERIU1
      INNER JOIN DISCART        DA  ON  DA.CODDISCOUNT  = D.CODDISCOUNT AND  DA.CODOBIECT     = aCODOBIECT
      LEFT  JOIN NAGENDA        AG  ON  D.CODTIPSEDIU   = AG.CODTIPSEDIU
    WHERE  CD.peclase = 0 and  CD.offinvoice = 1 and (   AG.CODAGENDA = aCodLocatie or  COALESCE(D.Codtipsediu, 0) = 0)
      and  CD1.Subunitatea = aSubunitate and  PD.CodPart = aCodPart and  cd.tipinterval = 2;
  EXCEPTION WHEN others THEN
    aCodDiscount := 0;
  END;

  IF  aCodDiscount &gt; 0 THEN
    SELECT count(*) INTO aCount FROM TMP_NCVDISC WHERE codncredit1 = aCodNCredit1 and  coddiscount = aCodDiscount;

    IF  aCount = 0 THEN
      INSERT INTO tmp_ncvdisc(codncredit1, coddiscount)
      VALUES(acodncredit1, acoddiscount);
    END IF;

    SELECT count(*) INTO aCount FROM TMP_NCVDISC_MAN WHERE coddiscount = aCodDiscount;

    IF  aCount = 0 THEN
      INSERT INTO tmp_ncvdisc_man(coddiscount, cant)
      VALUES(aCodDiscount, aCant);
    ELSE
      UPDATE tmp_ncvdisc_man SET cant = COALESCE(cant, 0) + acant WHERE coddiscount = acoddiscount;
    END IF;
  END IF;

  FOR v_rec IN
  (
    SELECT  DISTINCT d.coddiscount
    FROM NPARTDISC PD
      INNER JOIN criteriidisc   CD  ON  PD.CODCATEGDISC = CD.CODCRITERIU
      INNER JOIN criteriidisc1  CD1 ON  CD.CODCRITERIU  = CD1.CODCRITERIU
      INNER JOIN DISCOUNT       D   ON  CD.CODCRITERIU  = D.CODCRITERIU AND  CD1.CODCRITERIU1 = D.CODCRITERIU1
      INNER JOIN DISCART        DA  ON  DA.CODDISCOUNT  = D.CODDISCOUNT AND  DA.CODOBIECT     = aCODOBIECT
      LEFT  JOIN NAGENDA        AG  ON  D.CODTIPSEDIU   = AG.CODTIPSEDIU
    WHERE  CD.peclase = 0 and  CD.offinvoice = 1 and (   AG.CODAGENDA = aCodLocatie or  COALESCE(D.Codtipsediu, 0) = 0)
      and  CD1.Subunitatea = aSubunitate and  PD.CodPart = aCodPart and  cd.tipinterval = 6
  )
  LOOP
    SELECT count(*) INTO aCount FROM TMP_NCVDISC WHERE codncredit1 = aCodNCredit1 and  coddiscount = v_Rec.CodDiscount;
    IF  aCount = 0 THEN
      INSERT INTO tmp_ncvdisc(codncredit1, coddiscount)
      VALUES(acodncredit1, v_Rec.coddiscount);
    END IF;

    SELECT count(*)  INTO aCount FROM TMP_NCVDISC_MAN WHERE coddiscount = v_rec.CodDiscount;
    IF  aCount = 0 THEN
      INSERT INTO tmp_ncvdisc_man(coddiscount, valoare)
      VALUES(v_rec.CodDiscount, aVal);
    ELSE
      UPDATE tmp_ncvdisc_man SET valoare = COALESCE(valoare, 0) + aVal WHERE coddiscount = v_rec.coddiscount;
    END IF;
  END LOOP;

  -- toate articolele
  begin
    select distinct d.coddiscount, di.procent into aCodDiscount, aProc
    from NPARTDISC PD
        INNER JOIN criteriidisc  CD  ON PD.CODCATEGDISC = CD.CODCRITERIU
        INNER JOIN criteriidisc1 CD1 ON CD.CODCRITERIU  = CD1.CODCRITERIU
        INNER JOIN DISCOUNT      D   ON CD.CODCRITERIU  = D.CODCRITERIU and CD1.CODCRITERIU1 = D.CODCRITERIU1
        INNER JOIN DISCINTERVAL  DI  ON DI.CODDISCOUNT  = D.CODDISCOUNT
        LEFT  JOIN NAGENDA       AG  ON D.CODTIPSEDIU   = AG.CODTIPSEDIU
    where CD.peclase = 3 and CD.offinvoice = 1 and (AG.CODAGENDA = aCodLocatie or coalesce(D.Codtipsediu, 0) = 0)
      and CD1.Subunitatea = aSubunitate
      and PD.CodPart = aCodPart and cd.tipinterval = 0;
  exception when others then aCodDiscount := 0;
  end;

  if aCodDiscount &gt; 0 then
    select count(*) into aCount from TMP_NCVDISC where codncredit1 = aCodNCredit1 and coddiscount = aCodDiscount;
    if aCount = 0 then
      insert into tmp_ncvdisc(codncredit1, coddiscount)
      values (acodncredit1,acoddiscount);
    end if;
    select count(*) into aCount from TMP_NCVDISC_MAN where coddiscount = aCodDiscount;
    if aCount = 0 then
      insert into tmp_ncvdisc_man(coddiscount,proc)
      values (aCodDiscount,aproc);
    end if;
  end if;

  --pe clase
  BEGIN
    SELECT  DISTINCT d.coddiscount, di.procent
    INTO aCodDiscount, aProc
    FROM NPARTDISC PD
        INNER JOIN criteriidisc   CD  ON  PD.CODCATEGDISC = CD.CODCRITERIU
        INNER JOIN criteriidisc1  CD1 ON  CD.CODCRITERIU  = CD1.CODCRITERIU
        INNER JOIN DISCOUNT       D   ON  CD.CODCRITERIU  = D.CODCRITERIU AND  CD1.CODCRITERIU1 = D.CODCRITERIU1
        INNER JOIN DISCINTERVAL   DI  ON  DI.CODDISCOUNT  = D.CODDISCOUNT
        INNER JOIN DISCART        DA  ON  DA.CODDISCOUNT  = D.CODDISCOUNT AND  DA.CODCLASA      = aCODCLASA
        LEFT  JOIN NAGENDA        AG  ON  D.CODTIPSEDIU   = AG.CODTIPSEDIU
    WHERE  CD.peclase = 1 and  CD.offinvoice = 1 and (   AG.CODAGENDA = aCodLocatie or  COALESCE(D.Codtipsediu, 0) = 0)
      and  CD1.Subunitatea = aSubunitate and  PD.CodPart = aCodPart and  cd.tipinterval = 0;
  EXCEPTION WHEN others THEN
    aCodDiscount := 0;
  END;

  IF  aCodDiscount &gt; 0 THEN
    SELECT count(*) INTO aCount FROM TMP_NCVDISC WHERE codncredit1 = aCodNCredit1 and  coddiscount = aCodDiscount;
    IF  aCount = 0 THEN
      INSERT INTO tmp_ncvdisc(codncredit1, coddiscount)
      VALUES(acodncredit1, acoddiscount);
    END IF;

    SELECT count(*) INTO aCount FROM TMP_NCVDISC_MAN WHERE coddiscount = aCodDiscount;
    IF  aCount = 0 THEN
      INSERT INTO tmp_ncvdisc_man(coddiscount, proc)
      VALUES(aCodDiscount, aproc);
    END IF;
  END IF;

  BEGIN
    SELECT  DISTINCT d.coddiscount
    INTO aCodDiscount
    FROM NPARTDISC PD
      INNER JOIN criteriidisc   CD  ON  PD.CODCATEGDISC = CD.CODCRITERIU
      INNER JOIN criteriidisc1  CD1 ON  CD.CODCRITERIU  = CD1.CODCRITERIU
      INNER JOIN DISCOUNT       D   ON  CD.CODCRITERIU  = D.CODCRITERIU AND  CD1.CODCRITERIU1 = D.CODCRITERIU1
      INNER JOIN DISCART        DA  ON  DA.CODDISCOUNT  = D.CODDISCOUNT AND  DA.CODCLASA      = aCODCLASA
      LEFT  JOIN NAGENDA        AG  ON  D.CODTIPSEDIU   = AG.CODTIPSEDIU
    WHERE  CD.peclase = 1 and  CD.offinvoice = 1 and (AG.CODAGENDA = aCodLocatie or COALESCE(D.Codtipsediu, 0) = 0)
      and  CD1.Subunitatea = aSubunitate and  PD.CodPart = aCodPart and  cd.tipinterval = 2;
  EXCEPTION WHEN others THEN
    aCodDiscount := 0;
  END;

  IF  aCodDiscount &gt; 0 THEN
    SELECT count(*) INTO aCount FROM TMP_NCVDISC WHERE codncredit1 = aCodNCredit1 and  coddiscount = aCodDiscount;
    IF  aCount = 0 THEN
      INSERT INTO tmp_ncvdisc(codncredit1, coddiscount)
      VALUES(acodncredit1, acoddiscount);
    END IF;

    SELECT count(*) INTO aCount FROM TMP_NCVDISC_MAN WHERE coddiscount = aCodDiscount;
    IF  aCount = 0 THEN
      INSERT INTO tmp_ncvdisc_man(coddiscount, cant)
      VALUES(aCodDiscount, aCant);
    ELSE
      UPDATE tmp_ncvdisc_man SET cant = COALESCE(cant, 0) + acant WHERE coddiscount = acoddiscount;
    END IF;
  END IF;

  FOR v_rec IN
  (
    SELECT  DISTINCT d.coddiscount
    FROM NPARTDISC PD
      INNER JOIN criteriidisc   CD  ON  PD.CODCATEGDISC = CD.CODCRITERIU
      INNER JOIN criteriidisc1  CD1 ON  CD.CODCRITERIU  = CD1.CODCRITERIU
      INNER JOIN DISCOUNT       D   ON  CD.CODCRITERIU  = D.CODCRITERIU AND  CD1.CODCRITERIU1 = D.CODCRITERIU1
      INNER JOIN DISCART        DA  ON  DA.CODDISCOUNT  = D.CODDISCOUNT AND  DA.CODCLASA      = aCODCLASA
      LEFT  JOIN NAGENDA        AG  ON  D.CODTIPSEDIU   = AG.CODTIPSEDIU
    WHERE  CD.peclase = 1 and  CD.offinvoice = 1 and (AG.CODAGENDA = aCodLocatie or  COALESCE(D.Codtipsediu, 0) = 0)
      and  CD1.Subunitatea = aSubunitate and  PD.CodPart = aCodPart and  cd.tipinterval = 6
  )
  LOOP
    SELECT count(*) INTO aCount FROM TMP_NCVDISC WHERE codncredit1 = aCodNCredit1 and  coddiscount = v_rec.CodDiscount;
    IF  aCount = 0 THEN
      INSERT INTO tmp_ncvdisc(codncredit1, coddiscount)
      VALUES(acodncredit1, v_rec.coddiscount);
    END IF;

    SELECT count(*) INTO aCount FROM TMP_NCVDISC_MAN WHERE coddiscount = v_rec.CodDiscount;
    IF  aCount = 0 THEN
      INSERT INTO tmp_ncvdisc_man(coddiscount, valoare)
      VALUES(v_rec.CodDiscount, aVal);
    ELSE
      UPDATE tmp_ncvdisc_man SET valoare = COALESCE(valoare, 0) + aVal WHERE coddiscount = v_rec.coddiscount;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_gen_tmp_pen</obj_name>
  <obj_hashval>c1569d1d3695c9942cf692837e0c4e13</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_gen_tmp_pen(vzilegratie numeric, vdataref character varying, vini numeric, vallpart numeric, vallmon numeric, sdataref character varying, vrestzero numeric DEFAULT 0, vlitigii numeric DEFAULT 0, anlunaini numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  V_TMP   RECORD;
  V_XXX   RECORD;
  dataref date;
  aVal    numeric;
  aRest   numeric;
  aIdx    numeric;
  vAnLunaIni NUMERIC(20);
BEGIN
  --Florin 22.05.2025 - fixat 65713
  --Florin 11.04.2025 - sinc. Oracle
  --Florin 25.03.2025 - fixat 65131
  --Florin 16.02.2024 - sinc. Oracle
  --Florin 01.07.2022 - fixat 54780
  --Florin 09.06.2022 - fixat 54563
  --Florin 08.06.2022 - fixat 54556
  --Florin 31.05.2022 - sinc. Oracle
  --Florin 18.03.2022 - sinc. Oracle (17.03.2022)
  --Florin 21.02.2022 - sinc. Oracle (18.02.2022)
  --Florin 13.01.2022 - sinc. Oracle (28.12.2021)
  --Adina 25.03.2021 - tichet 46025
  --Bogdan 11.09.2020 aranjat, numeric+date
  --Florin 05.03.2021 - fixat 44465
  --Florin 31.03.2021 - fixat 46446
    select aninitial*12+lunainitiala into vAnLunaIni from firmaluni;
    if vAnLunaIni = AnLunaIni THEN
      vAnLunaIni := vAnLunaIni - 1;
    ELSE
      vAnLunaIni := AnLunaIni;
    END IF;

  DELETE FROM tmp_gen_penalitati;
  delete FROM tmp_cmd_tmp;

  insert into tmp_cmd_tmp(codobiect,datadoc,tip)
  SELECT CODSTINSPIF, MAX(DATADOC), 'DATA_LAST_PLATA'
  FROM
  (
  SELECT T1.DATADOC, S.CODSTINSPIF
  FROM STINGERE S
       INNER JOIN OBLIGPIF OS ON OS.CODOBLIGPIF = S.CODSTINGATORPIF
       INNER JOIN GENERAL GS ON GS.CODGENERAL = OS.CODGENERAL
       INNER JOIN TREZOR T ON GS.TIPDOC = T.TIPDOC AND GS.TIPDOC IN (29,30,31)
       INNER JOIN TREZOR1 T1 ON T.CODTREZOR = T1.CODTREZOR AND T1.CODTREZOR1 = GS.CODDOC
  UNION ALL
  SELECT CO.DATADOC, S.CODSTINSPIF
  FROM STINGERE S
       INNER JOIN OBLIGPIF OS ON OS.CODOBLIGPIF = S.CODSTINGATORPIF
       INNER JOIN GENERAL GS ON GS.CODGENERAL = OS.CODGENERAL
       INNER JOIN COMPENS CO ON CO.CODCOMPENS = GS.CODDOC AND GS.TIPDOC = 28
  ) a_pg GROUP BY CODSTINSPIF;
  insert into tmp_cmd_tmp(codobiect,resta,tip)
  SELECT
    GV.CODDOC,SUM(OV.VALOARE),'VAL210'
  FROM
    OBLIGPIF OV
    INNER JOIN GENERAL GV ON OV.CODGENERAL = GV.CODGENERAL
  WHERE
    OV.SEMNIFICATIE = 210 AND GV.TIPDOC IN (19,21,22,26)
  GROUP BY GV.CODDOC;

  insert into tmp_cmd_tmp(codobiect,resta,tip)
  SELECT CODSTINSPIF, SUM(VALOARE), 'STINS'
  FROM STINGERE
  GROUP BY CODSTINSPIF;
  insert into tmp_cmd_tmp(codobiect,resta,tip)
  SELECT S.CODSTINSPIF, SUM(S.VALOARE), 'STINS1'
  FROM STINGERE S
  WHERE S.CODSTINGERE &lt; (SELECT MAX(SS.CODSTINGERE) FROM STINGERE SS WHERE SS.CODSTINSPIF = S.CODSTINSPIF)
  GROUP BY S.CODSTINSPIF;

  insert into tmp_cmd_tmp(codobiect,resta,datadoc,tip)
  select I1.CODOBLIGMAJORAT, SUM(I1.PU * I1.CANT),MAX(I.DATADOC),'MAJ'
  FROM IESIRI1 I1, IESIRI I
  WHERE I.ANULAT = 0 AND I.CODIES = I1.CODIES AND I.DATADOC &lt;= to_date(vDataRef,'dd.mm.yyyy')
  GROUP BY I1.CODOBLIGMAJORAT;
  IF (fnc_GetValConstanta('MajTermLivr', getAnLucru(), getLunaLucru())) = '2' THEN
    IF vIni   &lt;&gt; 1 THEN
       insert into tmp_gen_penalitati
      SELECT
          O.CODOBLIGPIF,
          I.PREFIXDOC,
          I.NRDOC,
          I.DATADOC,
          I.VALDOC,
          ADD_DAYS(COALESCE ( (SELECT MIN (DATALIVR) FROM LIVR L WHERE L.CODIES = I.CODIES) , I.DATADOC)::DATE, (O.TERMEN - I.DATADOC::date)::INTEGER) AS TERMEN,
          O.VALOARE - COALESCE(TMP210.RESTA,0) - COALESCE(TMPS.RESTA,0) AS REST,
          O.MAJORARI AS MAJORARI,
          0 AS PRELUAT,
          A.OBS AS LOCATIE,
          P.DEN_PART,
          P.CODPART,
          I.CODLOCATIE,
          S.DEN_SUBUNIT,
          G.MONEDA,
          COALESCE(CFA.COD_CODFISCAL,CFP.COD_CODFISCAL) CODFISCAL,
          COALESCE(TMPJ.RESTA,0) AS MAJANTERIOARE,
          TMPJ.DATADOC AS DATA_LAST_FACTMAJ,
          TMP.DATADOC DATA_LAST_PLATA,
          O.REST,
          O.VALOARE,
          COALESCE(I.GRATIE,0),
          0,
          P.SCADENTAV,
          0,
          0,
          0,
          O.VALOARE,
          i.codies,
          i.tipdoc,
          i.seriadoc
        FROM
          OBLIGPIF O
          LEFT JOIN TMP_CMD_TMP TMP ON TMP.CODOBIECT = O.CODOBLIGPIF AND TMP.TIP = 'DATA_LAST_PLATA'
          LEFT JOIN TMP_CMD_TMP TMPS ON TMPS.CODOBIECT = O.CODOBLIGPIF AND TMPS.TIP = 'STINS'
          LEFT JOIN TMP_CMD_TMP TMPJ ON TMPJ.CODOBIECT = O.CODOBLIGPIF AND TMPJ.TIP = 'MAJ',
          GENERAL G,
          IESIRI I
          LEFT JOIN TMP_CMD_TMP TMP210 ON TMP210.CODOBIECT = I.CODIES AND TMP210.TIP = 'VAL210'
          LEFT JOIN NAGENDA A ON A.CODAGENDA = I.CODLOCATIE
          LEFT JOIN NPARTCODFISC CFA ON A.COD_CODFISCAL = CFA.COD_CODFISCAL,
          NPART P
          LEFT JOIN NPARTCODFISC CFP ON P.CODPART = CFP.CODPART AND CFP.PRINCIPAL = 1,
          NSUBUNIT S
        WHERE
          O.SEMNIFICATIE   = 200
          AND G.CODGENERAL = O.CODGENERAL
          AND G.TIPDOC     = I.TIPDOC
          AND COALESCE(I.ANULAT, 0) = 0
          AND COALESCE(I.TIPFACTURA, 0) &lt;&gt; 15
          AND G.CODDOC     = I.CODIES
          AND COALESCE(O.MAJORARI, 0) &lt;&gt; 0
          AND O.REST &gt; 0 AND I.AN*12+I.LUNA &gt;= vANLUNAINI
          AND ADD_DAYS(COALESCE((SELECT MIN (DATALIVR) FROM LIVR L WHERE L.CODIES = I.CODIES) , I.DATADOC)::DATE, (O.TERMEN - I.DATADOC::date)::INTEGER
                     + CASE WHEN COALESCE (i.gratie, 0) = 0 THEN vZileGratie::integer ELSE i.gratie ::integer END
                    ) &lt; to_date (vDataRef, 'dd.mm.yyyy')AND S.CODSUBUNIT = I.SUBUNITATEA
          AND (vAllPart = 1 or exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = 'CODPART' and tmp.valoare = p.codpart::varchar))
          AND (vAllMon = 1 or exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = 'CODMONEDA' and tmp.valoare = g.moneda::varchar))
          AND COALESCE(I.CODMONETAR,0) = 0 AND P.CODPART = I.PARTENER
          AND COALESCE(P.FARAPENALIZARI,0) = 0;
          /*AND NOT EXISTS (SELECT SS.CODSTINGERE
                          FROM STINGERE SS
                               INNER JOIN OBLIGPIF OST ON OST.CODOBLIGPIF = SS.CODSTINGATORPIF
                               INNER JOIN GENERAL GST ON OST.CODGENERAL = GST.CODGENERAL
                          WHERE SS.CODSTINSPIF = O.CODOBLIGPIF AND GST.TIPDOC = 16)*/

        insert into tmp_gen_penalitati
        SELECT
          O.CODOBLIGPIF,
          'COMP' PREFIXDOC,
          I.NRDOC,
          I.DATADOC,
          O.REST VALDOC,
          O.TERMEN,
          O.VALOARE - COALESCE(TMPS.RESTA,0) AS REST,
          O.MAJORARI AS MAJORARI,
          0 AS PRELUAT,
          A.OBS AS LOCATIE,
          P.DEN_PART,
          P.CODPART,
          A.CODAGENDA CODLOCATIE,
          S.DEN_SUBUNIT,
          G.MONEDA,
          COALESCE(CFA.COD_CODFISCAL,CFP.COD_CODFISCAL) CODFISCAL,
          COALESCE(TMPJ.RESTA,0) AS MAJANTERIOARE,
          TMPJ.DATADOC AS DATA_LAST_FACTMAJ,
          TMP.DATADOC DATA_LAST_PLATA,
          O.REST,
          O.VALOARE,
          0,
          0,
          P.SCADENTAV,
          0,
          0,
          0,
          O.VALOARE,
          i.codcompens,
          28,
          ''
        FROM
          OBLIGPIF O
          LEFT JOIN TMP_CMD_TMP TMP ON TMP.CODOBIECT = O.CODOBLIGPIF AND TMP.TIP = 'DATA_LAST_PLATA'
          LEFT JOIN TMP_CMD_TMP TMPS ON TMPS.CODOBIECT = O.CODOBLIGPIF AND TMPS.TIP = 'STINS'
          LEFT JOIN TMP_CMD_TMP TMPJ ON TMPJ.CODOBIECT = O.CODOBLIGPIF AND TMPJ.TIP = 'MAJ',
          GENERAL G,
          COMPENS I,
          NPART P
          LEFT JOIN NPARTCODFISC CFP ON P.CODPART = CFP.CODPART AND CFP.PRINCIPAL = 1,
          NAGENDA A
          LEFT JOIN NPARTCODFISC CFA ON A.COD_CODFISCAL = CFA.COD_CODFISCAL,
          NSUBUNIT S
        WHERE
          O.SEMNIFICATIE   = 1301
          AND I.CODCOMPENS = G.CODDOC
          AND P.CODPART = O.CODPART
          AND P.CODPART = A.CODPART AND A.SEDIUSOCIAL BETWEEN 4 AND 7
          AND G.CODGENERAL = O.CODGENERAL
          AND G.TIPDOC     = 28
          AND COALESCE(O.MAJORARI, 0) &lt;&gt; 0
          AND O.REST &gt; 0 AND I.AN*12+I.LUNA &gt;= vANLUNAINI
          AND ADD_DAYS(O.TERMEN, vZileGratie::INTEGER) &lt; to_date (vDataRef, 'dd.mm.yyyy')
          AND S.CODSUBUNIT = I.SUBUNITATEA
          AND (vAllPart = 1 or exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = 'CODPART' and tmp.valoare = p.codpart::varchar))
          AND (vAllMon = 1 or exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = 'CODMONEDA' and tmp.valoare = g.moneda::varchar))
          AND COALESCE(P.FARAPENALIZARI,0) = 0;

        insert into tmp_gen_penalitati
        SELECT
          O.CODOBLIGPIF,
          'COMP' PREFIXDOC,
          I.NRDOC,
          I.DATADOC,
          O.REST VALDOC,
          O.TERMEN,
          O.VALOARE - COALESCE(TMPS.RESTA,0) AS REST,
          O.MAJORARI AS MAJORARI,
          0 AS PRELUAT,
          A.OBS AS LOCATIE,
          P.DEN_PART,
          P.CODPART,
          A.CODAGENDA CODLOCATIE,
          S.DEN_SUBUNIT,
          G.MONEDA,
          COALESCE(CFA.COD_CODFISCAL,CFP.COD_CODFISCAL) CODFISCAL,
          COALESCE(TMPJ.RESTA,0) AS MAJANTERIOARE,
          TMPJ.DATADOC AS DATA_LAST_FACTMAJ,
          TMP.DATADOC DATA_LAST_PLATA,
          O.REST,
          O.VALOARE,
          0,
          0,
          P.SCADENTAV,
          0,
          0,
          0,
          O.VALOARE,
          i.codcompens,
          28,
          ''
        FROM
          OBLIGPIF O
          LEFT JOIN TMP_CMD_TMP TMP ON TMP.CODOBIECT = O.CODOBLIGPIF AND TMP.TIP = 'DATA_LAST_PLATA'
          LEFT JOIN TMP_CMD_TMP TMPS ON TMPS.CODOBIECT = O.CODOBLIGPIF AND TMPS.TIP = 'STINS'
          LEFT JOIN TMP_CMD_TMP TMPJ ON TMPJ.CODOBIECT = O.CODOBLIGPIF AND TMPJ.TIP = 'MAJ',
          GENERAL G,
          COMPENS I,
          NPART P
          LEFT JOIN NPARTCODFISC CFP ON P.CODPART = CFP.CODPART AND CFP.PRINCIPAL = 1,
          NAGENDA A
          LEFT JOIN NPARTCODFISC CFA ON A.COD_CODFISCAL = CFA.COD_CODFISCAL,
          NSUBUNIT S
        WHERE
          O.SEMNIFICATIE   = 1303
          AND I.CODCOMPENS = G.CODDOC
          AND P.CODPART = O.CODPART
          AND P.CODPART = A.CODPART AND A.SEDIUSOCIAL BETWEEN 4 AND 7
          AND G.CODGENERAL = O.CODGENERAL
          AND G.TIPDOC     = 28
          AND COALESCE(O.MAJORARI, 0) &lt;&gt; 0
          AND O.REST &gt; 0 AND I.AN*12+I.LUNA &gt;= vANLUNAINI
          AND ADD_DAYS(O.TERMEN, vZileGratie::INTEGER) &lt; to_date (vDataRef, 'dd.mm.yyyy')
          AND S.CODSUBUNIT = I.SUBUNITATEA
          AND (vAllPart = 1 or exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = 'CODPART' and tmp.valoare = p.codpart::varchar))
          AND (vAllMon = 1 or exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = 'CODMONEDA' and tmp.valoare = g.moneda::varchar))
          AND vLitigii = 1
          AND COALESCE(P.FARAPENALIZARI,0) = 0;

        insert into tmp_gen_penalitati
        SELECT
          O.CODOBLIGPIF,
          I.PREFIXDOC,
          I.NRDOC,
          I.DATADOC,
          I.VALDOC,
          ADD_DAYS(COALESCE ( (SELECT MIN (DATALIVR) FROM LIVR L WHERE L.CODIES = I.CODIES) , I.DATADOC)::DATE, (O.TERMEN - I.DATADOC::date)::INTEGER) AS TERMEN,
          O.VALOARE - COALESCE(TMP210.RESTA,0) - COALESCE(TMPS1.RESTA,0) AS REST,
          O.MAJORARI AS MAJORARI,
          0 AS PRELUAT,
          A.OBS AS LOCATIE,
          P.DEN_PART,
          P.CODPART,
          I.CODLOCATIE,
          S.DEN_SUBUNIT,
          G.MONEDA,
          COALESCE(CFA.COD_CODFISCAL,CFP.COD_CODFISCAL) CODFISCAL,
          COALESCE(TMPJ.RESTA,0) AS MAJANTERIOARE,
          TMPJ.DATADOC AS DATA_LAST_FACTMAJ,
          TMP.DATADOC DATA_LAST_PLATA,
          O.REST,
          O.VALOARE,
          COALESCE(I.GRATIE,0),
          0,
          P.SCADENTAV,
          0,
          0,
          0,
          O.VALOARE,
          i.codies,
          i.tipdoc,
          i.seriadoc
        FROM
          OBLIGPIF O
          LEFT JOIN TMP_CMD_TMP TMP ON TMP.CODOBIECT = O.CODOBLIGPIF AND TMP.TIP = 'DATA_LAST_PLATA'
          LEFT JOIN TMP_CMD_TMP TMPS1 ON TMPS1.CODOBIECT = O.CODOBLIGPIF AND TMPS1.TIP = 'STINS1'
          LEFT JOIN TMP_CMD_TMP TMPJ ON TMPJ.CODOBIECT = O.CODOBLIGPIF AND TMPJ.TIP = 'MAJ',
          GENERAL G,
          IESIRI I
          LEFT JOIN TMP_CMD_TMP TMP210 ON TMP210.CODOBIECT = I.CODIES AND TMP210.TIP = 'VAL210'
          LEFT JOIN NAGENDA A ON A.CODAGENDA = I.CODLOCATIE
          LEFT JOIN NPARTCODFISC CFA ON A.COD_CODFISCAL = CFA.COD_CODFISCAL,
          NPART P
          LEFT JOIN NPARTCODFISC CFP ON P.CODPART = CFP.CODPART AND CFP.PRINCIPAL = 1,
          NSUBUNIT S
        WHERE
          O.SEMNIFICATIE   = 200 AND P.CODPART = I.PARTENER
          AND G.CODGENERAL = O.CODGENERAL
          AND G.TIPDOC     = I.TIPDOC
          AND COALESCE(I.ANULAT, 0) = 0
          AND COALESCE(I.TIPFACTURA, 0) &lt;&gt; 15
          AND COALESCE(I.ANULAT, 0) = 0
          AND G.CODDOC     = I.CODIES
          AND COALESCE(O.MAJORARI, 0) &lt;&gt; 0
          AND O.REST = 0 and O.VALOARE &gt; 0 AND I.AN*12+I.LUNA &gt;= vANLUNAINI
          AND ADD_DAYS(COALESCE((SELECT MIN (DATALIVR) FROM LIVR L WHERE L.CODIES = I.CODIES) , I.DATADOC)::DATE, (O.TERMEN - I.DATADOC::date)::integer
                     + CASE WHEN COALESCE (i.gratie, 0) = 0 THEN vZileGratie::INTEGER ELSE i.gratie::INTEGER END
                    ) &lt; to_date (vDataRef, 'dd.mm.yyyy')AND S.CODSUBUNIT = I.SUBUNITATEA
          AND (vAllPart = 1 or exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = 'CODPART' and tmp.valoare = p.codpart::varchar))
          AND (vAllMon = 1 or exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = 'CODMONEDA' and tmp.valoare = g.moneda::varchar))
          AND COALESCE(I.CODMONETAR,0) = 0
          AND COALESCE(P.FARAPENALIZARI,0) = 0;
          /*AND NOT EXISTS (SELECT SS.CODSTINGERE
                          FROM STINGERE SS
                               INNER JOIN OBLIGPIF OST ON OST.CODOBLIGPIF = SS.CODSTINGATORPIF
                               INNER JOIN GENERAL GST ON OST.CODGENERAL = GST.CODGENERAL
                          WHERE SS.CODSTINSPIF = O.CODOBLIGPIF AND GST.TIPDOC = 16)*/

        insert into tmp_gen_penalitati
        SELECT
          O.CODOBLIGPIF,
          'COMP' PREFIXDOC,
          I.NRDOC,
          I.DATADOC,
          O.REST VALDOC,
          O.TERMEN,
          O.VALOARE - COALESCE(TMPS1.RESTA,0) AS REST,
          O.MAJORARI AS MAJORARI,
          0 AS PRELUAT,
          A.OBS AS LOCATIE,
          P.DEN_PART,
          P.CODPART,
          A.CODAGENDA CODLOCATIE,
          S.DEN_SUBUNIT,
          G.MONEDA,
          COALESCE(CFA.COD_CODFISCAL,CFP.COD_CODFISCAL) CODFISCAL,
          COALESCE(TMPJ.RESTA,0) AS MAJANTERIOARE,
          TMPJ.DATADOC AS DATA_LAST_FACTMAJ,
          TMP.DATADOC DATA_LAST_PLATA,
          O.REST,
          O.VALOARE,
          0,
          0,
          P.SCADENTAV,
          0,
          0,
          0,
          O.VALOARE,
          i.codcompens,
          28,
          ''
        FROM
          OBLIGPIF O
          LEFT JOIN TMP_CMD_TMP TMP ON TMP.CODOBIECT = O.CODOBLIGPIF AND TMP.TIP = 'DATA_LAST_PLATA'
          LEFT JOIN TMP_CMD_TMP TMPS1 ON TMPS1.CODOBIECT = O.CODOBLIGPIF AND TMPS1.TIP = 'STINS1'
          LEFT JOIN TMP_CMD_TMP TMPJ ON TMPJ.CODOBIECT = O.CODOBLIGPIF AND TMPJ.TIP = 'MAJ',
          GENERAL G,
          COMPENS I,
          NPART P
          LEFT JOIN NPARTCODFISC CFP ON P.CODPART = CFP.CODPART AND CFP.PRINCIPAL = 1,
          NAGENDA A
          LEFT JOIN NPARTCODFISC CFA ON A.COD_CODFISCAL = CFA.COD_CODFISCAL,
          NSUBUNIT S
        WHERE
          O.SEMNIFICATIE   = 1301
          AND I.CODCOMPENS = G.CODDOC
          AND P.CODPART = O.CODPART
          AND P.CODPART = A.CODPART AND A.SEDIUSOCIAL BETWEEN 4 AND 7
          AND G.CODGENERAL = O.CODGENERAL
          AND G.TIPDOC     = 28
          AND COALESCE(O.MAJORARI, 0) &lt;&gt; 0
          AND O.REST = 0 and O.VALOARE &gt; 0 AND I.AN*12+I.LUNA &gt;= vANLUNAINI
          AND ADD_DAYS(O.TERMEN, vZileGratie::INTEGER) &lt; to_date (vDataRef, 'dd.mm.yyyy')
          AND S.CODSUBUNIT = I.SUBUNITATEA
          AND (vAllPart = 1 or exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = 'CODPART' and tmp.valoare = p.codpart::varchar))
          AND (vAllMon = 1 or exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = 'CODMONEDA' and tmp.valoare = g.moneda::varchar))
          AND COALESCE(P.FARAPENALIZARI,0) = 0;

        insert into tmp_gen_penalitati
        SELECT
          O.CODOBLIGPIF,
          'COMP' PREFIXDOC,
          I.NRDOC,
          I.DATADOC,
          O.REST VALDOC,
          O.TERMEN,
          O.VALOARE - COALESCE(TMPS1.RESTA,0) AS REST,
          O.MAJORARI AS MAJORARI,
          0 AS PRELUAT,
          A.OBS AS LOCATIE,
          P.DEN_PART,
          P.CODPART,
          A.CODAGENDA CODLOCATIE,
          S.DEN_SUBUNIT,
          G.MONEDA,
          COALESCE(CFA.COD_CODFISCAL,CFP.COD_CODFISCAL) CODFISCAL,
          COALESCE(TMPJ.RESTA,0) AS MAJANTERIOARE,
          TMPJ.DATADOC AS DATA_LAST_FACTMAJ,
          TMP.DATADOC DATA_LAST_PLATA,
          O.REST,
          O.VALOARE,
          0,
          0,
          P.SCADENTAV,
          0,
          0,
          0,
          O.VALOARE,
          i.codcompens,
          28,
          ''
        FROM
          OBLIGPIF O
          LEFT JOIN TMP_CMD_TMP TMP ON TMP.CODOBIECT = O.CODOBLIGPIF AND TMP.TIP = 'DATA_LAST_PLATA'
          LEFT JOIN TMP_CMD_TMP TMPS1 ON TMPS1.CODOBIECT = O.CODOBLIGPIF AND TMPS1.TIP = 'STINS1'
          LEFT JOIN TMP_CMD_TMP TMPJ ON TMPJ.CODOBIECT = O.CODOBLIGPIF AND TMPJ.TIP = 'MAJ',
          GENERAL G,
          COMPENS I,
          NPART P
          LEFT JOIN NPARTCODFISC CFP ON P.CODPART = CFP.CODPART AND CFP.PRINCIPAL = 1,
          NAGENDA A
          LEFT JOIN NPARTCODFISC CFA ON A.COD_CODFISCAL = CFA.COD_CODFISCAL,
          NSUBUNIT S
        WHERE
          O.SEMNIFICATIE   = 1303
          AND I.CODCOMPENS = G.CODDOC
          AND P.CODPART = O.CODPART
          AND P.CODPART = A.CODPART AND A.SEDIUSOCIAL BETWEEN 4 AND 7
          AND G.CODGENERAL = O.CODGENERAL
          AND G.TIPDOC     = 28
          AND COALESCE(O.MAJORARI, 0) &lt;&gt; 0
          AND O.REST = 0 and O.VALOARE &gt; 0 AND I.AN*12+I.LUNA &gt;= vANLUNAINI
          AND ADD_DAYS(O.TERMEN, vZileGratie::INTEGER) &lt; to_date (vDataRef, 'dd.mm.yyyy')
          AND S.CODSUBUNIT = I.SUBUNITATEA
          AND (vAllPart = 1 or exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = 'CODPART' and tmp.valoare = p.codpart::varchar))
          AND (vAllMon = 1 or exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = 'CODMONEDA' and tmp.valoare = g.moneda::varchar))
          AND vLitigii = 1
          AND COALESCE(P.FARAPENALIZARI,0) = 0;
    end if;
  else
    if vIni &lt;&gt; 1 then
      insert into tmp_gen_penalitati
      SELECT
          O.CODOBLIGPIF,
          I.PREFIXDOC,
          I.NRDOC,
          I.DATADOC,
          I.VALDOC,
          O.TERMEN,
          O.VALOARE - COALESCE(TMP210.RESTA,0) - COALESCE(TMPS.RESTA,0) AS REST,
          O.MAJORARI AS MAJORARI,
          0 AS PRELUAT,
          A.OBS AS LOCATIE,
          P.DEN_PART,
          P.CODPART,
          I.CODLOCATIE,
          S.DEN_SUBUNIT,
          G.MONEDA,
          COALESCE(CFA.COD_CODFISCAL,CFP.COD_CODFISCAL) CODFISCAL,
          COALESCE(TMPJ.RESTA,0) AS MAJANTERIOARE,
          TMPJ.DATADOC AS DATA_LAST_FACTMAJ,
          TMP.DATADOC DATA_LAST_PLATA,
          O.REST,
          O.VALOARE,
          COALESCE(I.GRATIE,0),
          0,
          P.SCADENTAV,
          0,
          0,
          0,
          O.VALOARE,
          i.codies,
          i.tipdoc,
          i.seriadoc
        FROM
          OBLIGPIF O
          LEFT JOIN TMP_CMD_TMP TMP ON TMP.CODOBIECT = O.CODOBLIGPIF AND TMP.TIP = 'DATA_LAST_PLATA'
          LEFT JOIN TMP_CMD_TMP TMPS ON TMPS.CODOBIECT = O.CODOBLIGPIF AND TMPS.TIP = 'STINS'
          LEFT JOIN TMP_CMD_TMP TMPJ ON TMPJ.CODOBIECT = O.CODOBLIGPIF AND TMPJ.TIP = 'MAJ',
          GENERAL G,
          IESIRI I
          LEFT JOIN TMP_CMD_TMP TMP210 ON TMP210.CODOBIECT = I.CODIES AND TMP210.TIP = 'VAL210'
          LEFT JOIN NAGENDA A ON A.CODAGENDA = I.CODLOCATIE
          LEFT JOIN NPARTCODFISC CFA ON A.COD_CODFISCAL = CFA.COD_CODFISCAL,
          NPART P
          LEFT JOIN NPARTCODFISC CFP ON P.CODPART = CFP.CODPART AND CFP.PRINCIPAL = 1,
          NSUBUNIT S
        WHERE
          O.SEMNIFICATIE   = 200 AND P.CODPART = I.PARTENER
          AND G.CODGENERAL = O.CODGENERAL
          AND G.TIPDOC     = I.TIPDOC
          AND COALESCE(I.TIPFACTURA, 0) &lt;&gt; 15
          AND G.CODDOC     = I.CODIES
          AND COALESCE(O.MAJORARI, 0) &lt;&gt; 0
          AND O.REST &gt; 0 AND I.AN*12+I.LUNA &gt;= vANLUNAINI
          AND ADD_DAYS(O.TERMEN,
          CASE WHEN COALESCE (i.gratie, 0) = 0 THEN vZileGratie::INTEGER ELSE i.gratie::INTEGER END) &lt; to_date (vDataRef, 'dd.mm.yyyy')
          AND S.CODSUBUNIT = I.SUBUNITATEA
          AND (vAllPart = 1 or exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = 'CODPART' and tmp.valoare = p.codpart::varchar))
          AND (vAllMon = 1 or exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = 'CODMONEDA' and tmp.valoare = g.moneda::varchar))
          AND COALESCE(I.CODMONETAR,0) = 0
          AND COALESCE(P.FARAPENALIZARI,0) = 0;
          /*AND NOT EXISTS (SELECT SS.CODSTINGERE
                          FROM STINGERE SS
                               INNER JOIN OBLIGPIF OST ON OST.CODOBLIGPIF = SS.CODSTINGATORPIF
                               INNER JOIN GENERAL GST ON OST.CODGENERAL = GST.CODGENERAL
                          WHERE SS.CODSTINSPIF = O.CODOBLIGPIF AND GST.TIPDOC = 16)*/
        insert into tmp_gen_penalitati
        SELECT
          O.CODOBLIGPIF,
          'COMP' PREFIXDOC,
          I.NRDOC,
          I.DATADOC,
          O.REST VALDOC,
          O.TERMEN,
          O.VALOARE - COALESCE(TMPS.RESTA,0) AS REST,
          O.MAJORARI AS MAJORARI,
          0 AS PRELUAT,
          A.OBS AS LOCATIE,
          P.DEN_PART,
          P.CODPART,
          A.CODAGENDA CODLOCATIE,
          S.DEN_SUBUNIT,
          G.MONEDA,
          COALESCE(CFA.COD_CODFISCAL,CFP.COD_CODFISCAL) CODFISCAL,
          COALESCE(TMPJ.RESTA,0) AS MAJANTERIOARE,
          TMPJ.DATADOC AS DATA_LAST_FACTMAJ,
          TMP.DATADOC DATA_LAST_PLATA,
          O.REST,
          O.VALOARE,
          0,
          0,
          P.SCADENTAV,
          0,
          0,
          0,
          O.VALOARE,
          i.codcompens,
          28,
          ''
        FROM
          OBLIGPIF O
          LEFT JOIN TMP_CMD_TMP TMP ON TMP.CODOBIECT = O.CODOBLIGPIF AND TMP.TIP = 'DATA_LAST_PLATA'
          LEFT JOIN TMP_CMD_TMP TMPS ON TMPS.CODOBIECT = O.CODOBLIGPIF AND TMPS.TIP = 'STINS'
          LEFT JOIN TMP_CMD_TMP TMPJ ON TMPJ.CODOBIECT = O.CODOBLIGPIF AND TMPJ.TIP = 'MAJ',
          GENERAL G,
          COMPENS I,
          NPART P
          LEFT JOIN NPARTCODFISC CFP ON P.CODPART = CFP.CODPART AND CFP.PRINCIPAL = 1,
          NAGENDA A
          LEFT JOIN NPARTCODFISC CFA ON A.COD_CODFISCAL = CFA.COD_CODFISCAL,
          NSUBUNIT S
        WHERE
          O.SEMNIFICATIE   = 1301
          AND I.CODCOMPENS = G.CODDOC
          AND P.CODPART = O.CODPART
          AND P.CODPART = A.CODPART AND A.SEDIUSOCIAL BETWEEN 4 AND 7
          AND G.CODGENERAL = O.CODGENERAL
          AND G.TIPDOC     = 28
          AND COALESCE(O.MAJORARI, 0) &lt;&gt; 0
          AND O.REST &gt; 0 AND I.AN*12+I.LUNA &gt;= vANLUNAINI
          AND ADD_DAYS(O.TERMEN, vZileGratie::INTEGER) &lt; to_date (vDataRef, 'dd.mm.yyyy')
          AND S.CODSUBUNIT = I.SUBUNITATEA
          AND (vAllPart = 1 or exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = 'CODPART' and tmp.valoare = p.codpart::varchar))
          AND (vAllMon = 1 or exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = 'CODMONEDA' and tmp.valoare = g.moneda::varchar))
          AND COALESCE(P.FARAPENALIZARI,0) = 0;

        insert into tmp_gen_penalitati
        SELECT
          O.CODOBLIGPIF,
          'COMP' PREFIXDOC,
          I.NRDOC,
          I.DATADOC,
          O.REST VALDOC,
          O.TERMEN,
          O.VALOARE - COALESCE(TMPS.RESTA,0) AS REST,
          O.MAJORARI AS MAJORARI,
          0 AS PRELUAT,
          A.OBS AS LOCATIE,
          P.DEN_PART,
          P.CODPART,
          A.CODAGENDA CODLOCATIE,
          S.DEN_SUBUNIT,
          G.MONEDA,
          COALESCE(CFA.COD_CODFISCAL,CFP.COD_CODFISCAL) CODFISCAL,
          COALESCE(TMPJ.RESTA,0) AS MAJANTERIOARE,
          TMPJ.DATADOC AS DATA_LAST_FACTMAJ,
          TMP.DATADOC DATA_LAST_PLATA,
          O.REST,
          O.VALOARE,
          0,
          0,
          P.SCADENTAV,
          0,
          0,
          0,
          O.VALOARE,
          i.codcompens,
          28,
          ''
        FROM
          OBLIGPIF O
          LEFT JOIN TMP_CMD_TMP TMP ON TMP.CODOBIECT = O.CODOBLIGPIF AND TMP.TIP = 'DATA_LAST_PLATA'
          LEFT JOIN TMP_CMD_TMP TMPS ON TMPS.CODOBIECT = O.CODOBLIGPIF AND TMPS.TIP = 'STINS'
          LEFT JOIN TMP_CMD_TMP TMPJ ON TMPJ.CODOBIECT = O.CODOBLIGPIF AND TMPJ.TIP = 'MAJ',
          GENERAL G,
          COMPENS I,
          NPART P
          LEFT JOIN NPARTCODFISC CFP ON P.CODPART = CFP.CODPART AND CFP.PRINCIPAL = 1,
          NAGENDA A
          LEFT JOIN NPARTCODFISC CFA ON A.COD_CODFISCAL = CFA.COD_CODFISCAL,
          NSUBUNIT S
        WHERE
          O.SEMNIFICATIE   = 1303
          AND I.CODCOMPENS = G.CODDOC
          AND P.CODPART = O.CODPART
          AND P.CODPART = A.CODPART AND A.SEDIUSOCIAL BETWEEN 4 AND 7
          AND G.CODGENERAL = O.CODGENERAL
          AND G.TIPDOC     = 28
          AND COALESCE(O.MAJORARI, 0) &lt;&gt; 0
          AND O.REST &gt; 0 AND I.AN*12+I.LUNA &gt;= vANLUNAINI
          AND ADD_DAYS(O.TERMEN, vZileGratie::INTEGER) &lt; to_date (vDataRef, 'dd.mm.yyyy')
          AND S.CODSUBUNIT = I.SUBUNITATEA
          AND (vAllPart = 1 or exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = 'CODPART' and tmp.valoare = p.codpart::varchar))
          AND (vAllMon = 1 or exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = 'CODMONEDA' and tmp.valoare = g.moneda::varchar))
          AND vLitigii = 1
          AND COALESCE(P.FARAPENALIZARI,0) = 0;

        insert into tmp_gen_penalitati
        SELECT
          O.CODOBLIGPIF,
          I.PREFIXDOC,
          I.NRDOC,
          I.DATADOC,
          I.VALDOC,
          O.TERMEN,
          O.VALOARE - COALESCE(TMP210.RESTA,0) - COALESCE(TMPS1.RESTA,0) AS REST,
          O.MAJORARI AS MAJORARI,
          0 AS PRELUAT,
          A.OBS AS LOCATIE,
          P.DEN_PART,
          P.CODPART,
          I.CODLOCATIE,
          S.DEN_SUBUNIT,
          G.MONEDA,
          COALESCE(CFA.COD_CODFISCAL,CFP.COD_CODFISCAL) CODFISCAL,
          COALESCE(TMPJ.RESTA,0) AS MAJANTERIOARE,
          TMPJ.DATADOC AS DATA_LAST_FACTMAJ,
          TMP.DATADOC DATA_LAST_PLATA,
          O.REST,
          O.VALOARE,
          COALESCE(I.GRATIE,0),
          0,
          P.SCADENTAV,
          0,
          0,
          0,
          O.VALOARE,
          i.codies,
          i.tipdoc,
          i.seriadoc
        FROM
          OBLIGPIF O
          LEFT JOIN TMP_CMD_TMP TMP ON TMP.CODOBIECT = O.CODOBLIGPIF AND TMP.TIP = 'DATA_LAST_PLATA'
          LEFT JOIN TMP_CMD_TMP TMPS1 ON TMPS1.CODOBIECT = O.CODOBLIGPIF AND TMPS1.TIP = 'STINS1'
          LEFT JOIN TMP_CMD_TMP TMPJ ON TMPJ.CODOBIECT = O.CODOBLIGPIF AND TMPJ.TIP = 'MAJ',
          GENERAL G,
          IESIRI I
          LEFT JOIN TMP_CMD_TMP TMP210 ON TMP210.CODOBIECT = I.CODIES AND TMP210.TIP = 'VAL210'
          LEFT JOIN NAGENDA A ON A.CODAGENDA = I.CODLOCATIE
          LEFT JOIN NPARTCODFISC CFA ON A.COD_CODFISCAL = CFA.COD_CODFISCAL,
          NPART P
          LEFT JOIN NPARTCODFISC CFP ON P.CODPART = CFP.CODPART AND CFP.PRINCIPAL = 1,
          NSUBUNIT S
        WHERE
          O.SEMNIFICATIE   = 200 AND P.CODPART = I.PARTENER
          AND G.CODGENERAL = O.CODGENERAL
          AND G.TIPDOC     = I.TIPDOC
          AND COALESCE(I.TIPFACTURA, 0) &lt;&gt; 15
          AND G.CODDOC     = I.CODIES
          AND COALESCE(O.MAJORARI, 0) &lt;&gt; 0
          AND O.REST = 0 and O.VALOARE &gt; 0 AND I.AN*12+I.LUNA &gt;= vANLUNAINI
          AND ADD_DAYS(O.TERMEN,
          CASE WHEN COALESCE (i.gratie, 0) = 0 THEN vZileGratie::INTEGER ELSE i.gratie::INTEGER END) &lt; to_date (vDataRef, 'dd.mm.yyyy')
          AND S.CODSUBUNIT = I.SUBUNITATEA
          AND (vAllPart = 1 or exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = 'CODPART' and tmp.valoare = p.codpart::varchar))
          AND (vAllMon = 1 or exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = 'CODMONEDA' and tmp.valoare = g.moneda::varchar))
          AND COALESCE(I.CODMONETAR,0) = 0
          AND COALESCE(P.FARAPENALIZARI,0) = 0;
          /*AND NOT EXISTS (SELECT SS.CODSTINGERE
                          FROM STINGERE SS
                               INNER JOIN OBLIGPIF OST ON OST.CODOBLIGPIF = SS.CODSTINGATORPIF
                               INNER JOIN GENERAL GST ON OST.CODGENERAL = GST.CODGENERAL
                          WHERE SS.CODSTINSPIF = O.CODOBLIGPIF AND GST.TIPDOC = 16)*/
        insert into tmp_gen_penalitati
        SELECT
          O.CODOBLIGPIF,
          'COMP' PREFIXDOC,
          I.NRDOC,
          I.DATADOC,
          O.REST VALDOC,
          O.TERMEN,
          O.VALOARE - COALESCE(TMPS1.RESTA,0) AS REST,
          O.MAJORARI AS MAJORARI,
          0 AS PRELUAT,
          A.OBS AS LOCATIE,
          P.DEN_PART,
          P.CODPART,
          A.CODAGENDA CODLOCATIE,
          S.DEN_SUBUNIT,
          G.MONEDA,
          COALESCE(CFA.COD_CODFISCAL,CFP.COD_CODFISCAL) CODFISCAL,
          COALESCE(TMPJ.RESTA,0) AS MAJANTERIOARE,
          TMPJ.DATADOC AS DATA_LAST_FACTMAJ,
          TMP.DATADOC DATA_LAST_PLATA,
          O.REST,
          O.VALOARE,
          0,
          0,
          P.SCADENTAV,
          0,
          0,
          0,
          O.VALOARE,
          i.codcompens,
          28,
          ''
        FROM
          OBLIGPIF O
          LEFT JOIN TMP_CMD_TMP TMP ON TMP.CODOBIECT = O.CODOBLIGPIF AND TMP.TIP = 'DATA_LAST_PLATA'
          LEFT JOIN TMP_CMD_TMP TMPS1 ON TMPS1.CODOBIECT = O.CODOBLIGPIF AND TMPS1.TIP = 'STINS1'
          LEFT JOIN TMP_CMD_TMP TMPJ ON TMPJ.CODOBIECT = O.CODOBLIGPIF AND TMPJ.TIP = 'MAJ',
          GENERAL G,
          COMPENS I,
          NPART P
          LEFT JOIN NPARTCODFISC CFP ON P.CODPART = CFP.CODPART AND CFP.PRINCIPAL = 1,
          NAGENDA A
          LEFT JOIN NPARTCODFISC CFA ON A.COD_CODFISCAL = CFA.COD_CODFISCAL,
          NSUBUNIT S
        WHERE
          O.SEMNIFICATIE   = 1301
          AND I.CODCOMPENS = G.CODDOC
          AND P.CODPART = O.CODPART
          AND P.CODPART = A.CODPART AND A.SEDIUSOCIAL BETWEEN 4 AND 7
          AND G.CODGENERAL = O.CODGENERAL
          AND G.TIPDOC     = 28
          AND COALESCE(O.MAJORARI, 0) &lt;&gt; 0
          AND O.REST = 0 and O.VALOARE &gt; 0 AND I.AN*12+I.LUNA &gt;= vANLUNAINI
          AND ADD_DAYS(O.TERMEN, vZileGratie::INTEGER) &lt; to_date (vDataRef, 'dd.mm.yyyy')
          AND S.CODSUBUNIT = I.SUBUNITATEA
          AND (vAllPart = 1 or exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = 'CODPART' and tmp.valoare = p.codpart::varchar))
          AND (vAllMon = 1 or exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = 'CODMONEDA' and tmp.valoare = g.moneda::varchar))
          AND COALESCE(P.FARAPENALIZARI,0) = 0;

        insert into tmp_gen_penalitati
        SELECT
          O.CODOBLIGPIF,
          'COMP' PREFIXDOC,
          I.NRDOC,
          I.DATADOC,
          O.REST VALDOC,
          O.TERMEN,
          O.VALOARE - COALESCE(TMPS1.RESTA,0) AS REST,
          O.MAJORARI AS MAJORARI,
          0 AS PRELUAT,
          A.OBS AS LOCATIE,
          P.DEN_PART,
          P.CODPART,
          A.CODAGENDA CODLOCATIE,
          S.DEN_SUBUNIT,
          G.MONEDA,
          COALESCE(CFA.COD_CODFISCAL,CFP.COD_CODFISCAL) CODFISCAL,
          COALESCE(TMPJ.RESTA,0) AS MAJANTERIOARE,
          TMPJ.DATADOC AS DATA_LAST_FACTMAJ,
          TMP.DATADOC DATA_LAST_PLATA,
          O.REST,
          O.VALOARE,
          0,
          0,
          P.SCADENTAV,
          0,
          0,
          0,
          O.VALOARE,
          i.codcompens,
          28,
          ''
        FROM
          OBLIGPIF O
          LEFT JOIN TMP_CMD_TMP TMP ON TMP.CODOBIECT = O.CODOBLIGPIF AND TMP.TIP = 'DATA_LAST_PLATA'
          LEFT JOIN TMP_CMD_TMP TMPS1 ON TMPS1.CODOBIECT = O.CODOBLIGPIF AND TMPS1.TIP = 'STINS1'
          LEFT JOIN TMP_CMD_TMP TMPJ ON TMPJ.CODOBIECT = O.CODOBLIGPIF AND TMPJ.TIP = 'MAJ',
          GENERAL G,
          COMPENS I,
          NPART P
          LEFT JOIN NPARTCODFISC CFP ON P.CODPART = CFP.CODPART AND CFP.PRINCIPAL = 1,
          NAGENDA A
          LEFT JOIN NPARTCODFISC CFA ON A.COD_CODFISCAL = CFA.COD_CODFISCAL,
          NSUBUNIT S
        WHERE
          O.SEMNIFICATIE   = 1303
          AND I.CODCOMPENS = G.CODDOC
          AND P.CODPART = O.CODPART
          AND P.CODPART = A.CODPART AND A.SEDIUSOCIAL BETWEEN 4 AND 7
          AND G.CODGENERAL = O.CODGENERAL
          AND G.TIPDOC     = 28
          AND COALESCE(O.MAJORARI, 0) &lt;&gt; 0
          AND O.REST = 0 and O.VALOARE &gt; 0 AND I.AN*12+I.LUNA &gt;= vANLUNAINI
          AND ADD_DAYS(O.TERMEN, vZileGratie::INTEGER) &lt; to_date (vDataRef, 'dd.mm.yyyy')
          AND S.CODSUBUNIT = I.SUBUNITATEA
          AND (vAllPart = 1 or exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = 'CODPART' and tmp.valoare = p.codpart::varchar))
          AND (vAllMon = 1 or exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = 'CODMONEDA' and tmp.valoare = g.moneda::varchar))
          AND vLitigii = 1
          AND COALESCE(P.FARAPENALIZARI,0) = 0;
    end if;
  end if;
  update tmp_gen_penalitati tmp
  set
    storno =
    (
      select sum(case when o.semnificatie = 200 then o.rest else - o.rest end)
      from obligpif o
      where o.codpart = tmp.codpart and o.rest &lt;&gt; 0
            and o.termen &lt; to_date(vDataRef,'dd.mm.yyyy') and ((o.valoare &lt; 0 and o.semnificatie = 200) or o.semnificatie in (210,410))
    );

  UPDATE tmp_gen_penalitati tmp
  SET SCADENTAV = (SELECT P1.SCADENTAV FROM NPART1 P1 WHERE P1.CODPART = TMP.CODPART AND getAnLunaLucru() BETWEEN P1.ALStart AND p1.ALStop)
  WHERE COALESCE(TMP.SCADENTAV,0) = 0;

  delete FROM tmp_gen_penalitati_man;
  insert into tmp_gen_penalitati_man select * from tmp_gen_penalitati;

  aIdx := 0;
  FOR V_REC IN (SELECT tmp.coddoc, tmp.tipdoc, tmp.CODOBLIGPIF,tmp.PREFIXDOC,tmp.NRDOC,tmp.DATADOC,tmp.VALDOC,tmp.TERMEN,tmp.REST,tmp.MAJORARI,tmp.PRELUAT,tmp.LOCATIE,
                tmp.DEN_PART,tmp.CODPART,tmp.CODLOCATIE,tmp.DEN_SUBUNIT,tmp.MONEDA,tmp.CODFISCAL,tmp.MAJANTERIOARE,tmp.DATA_LAST_FACTMAJ,
                tmp.DATA_LAST_PLATA,tmp.RESTOBLIG,tmp.VALOBLIG,tmp.GRATIEDOC,tmp.STORNO,tmp.SCADENTAV,tmp.VALMAJ, tmp.seriadoc
                FROM tmp_gen_penalitati_man tmp
                where tmp.restoblig &gt; 0) LOOP
    delete FROM tmp_gen_penalitati where codobligpif = v_rec.codobligpif;
    aVal := 0;
    aRest := v_rec.valoblig;
    dataref := v_rec.termen;
    FOR V_TMP IN (SELECT CODOBLIGPIF, DATADOC, VALOARE, DATAPEN, DATAGEN
                  FROM (
                  SELECT v_rec.CODOBLIGPIF CODOBLIGPIF, T1.DATADOC, s.valoare, NULL::date datapen, T1.DATADOC DATAGEN
                  FROM STINGERE S
                       INNER JOIN OBLIGPIF OS ON OS.CODOBLIGPIF = S.CODSTINGATORPIF
                       INNER JOIN GENERAL GS ON GS.CODGENERAL = OS.CODGENERAL
                       INNER JOIN TREZOR T ON GS.TIPDOC = T.TIPDOC AND GS.TIPDOC IN (29,30,31)
                       INNER JOIN TREZOR1 T1 ON T.CODTREZOR = T1.CODTREZOR AND T1.CODTREZOR1 = GS.CODDOC
                  WHERE s.codstinspif = v_rec.codobligpif AND T1.DATADOC &lt;= to_date(vDataRef,'dd.mm.yyyy')
                  UNION ALL
                  SELECT v_rec.CODOBLIGPIF CODOBLIGPIF, CO.DATADOC, s.valoare, NULL::date datapen, CO.DATADOC DATAGEN
                  FROM STINGERE S
                       INNER JOIN OBLIGPIF OS ON OS.CODOBLIGPIF = S.CODSTINGATORPIF
                       INNER JOIN GENERAL GS ON GS.CODGENERAL = OS.CODGENERAL
                       INNER JOIN COMPENS CO ON CO.CODCOMPENS = GS.CODDOC AND GS.TIPDOC = 28
                  WHERE s.codstinspif = v_rec.codobligpif AND CO.DATADOC &lt;= to_date(vDataRef,'dd.mm.yyyy')
                  UNION ALL
                  SELECT v_rec.CODOBLIGPIF CODOBLIGPIF, NULL DATADOC, i.valdoc-i.tvadoc valoare, coalesce(i1.termencontract,I.DATADOC) DATAPEN, coalesce(i1.termencontract,I.DATADOC) DATAGEN
                  FROM IESIRI1 I1
                       INNER JOIN IESIRI I ON I.CODIES = I1.CODIES AND COALESCE(I.ANULAT, 0) = 0
                  WHERE I1.CODOBLIGMAJORAT = v_rec.CODOBLIGPIF AND COALESCE(I.CODMONETAR,0) = 0
                  UNION ALL
                  SELECT V_REC.CODOBLIGPIF CODOBLIGPIF, I.DATADOC, SS.valoare, null datapen, I.DATADOC DATAGEN
                  FROM STINGERE SS
                       INNER JOIN OBLIGPIF OST ON OST.CODOBLIGPIF = SS.CODSTINGATORPIF
                       INNER JOIN GENERAL GST ON OST.CODGENERAL = GST.CODGENERAL
                       INNER JOIN IESIRI I ON I.CODIES = GST.CODDOC AND I.TIPDOC = GST.TIPDOC
                  WHERE SS.CODSTINSPIF = V_REC.CODOBLIGPIF AND GST.TIPDOC = 16 AND I.DATADOC &lt;= to_date(vDataRef,'dd.mm.yyyy')
                  ) a_pg
                  ORDER BY DATAGEN
                 ) LOOP
      if not v_tmp.datapen is null then dataref := v_tmp.datapen; end if;
      if v_tmp.datapen is null then
        if v_tmp.datadoc &gt; v_rec.termen then
          aIdx := aIdx + 1;
          insert into tmp_gen_penalitati (
          CODOBLIGPIF,PREFIXDOC,NRDOC,DATADOC,VALDOC,TERMEN,REST,MAJORARI,PRELUAT,LOCATIE,
          DEN_PART,CODPART,CODLOCATIE,DEN_SUBUNIT,MONEDA,CODFISCAL,MAJANTERIOARE,DATA_LAST_FACTMAJ,
          DATA_LAST_PLATA,RESTOBLIG,VALOBLIG,GRATIEDOC,STORNO,SCADENTAV,VALMAJ,ZILE, CODUNIC, CODDOC, TIPDOC, Seriadoc
          )
          values (
          v_rec.CODOBLIGPIF,v_rec.PREFIXDOC,v_rec.NRDOC,v_rec.DATADOC,v_rec.VALDOC,v_rec.TERMEN,aRest,v_rec.MAJORARI,v_rec.PRELUAT,v_rec.LOCATIE,
          v_rec.DEN_PART,v_rec.CODPART,v_rec.CODLOCATIE,v_rec.DEN_SUBUNIT,v_rec.MONEDA,v_rec.CODFISCAL,v_rec.MAJANTERIOARE,v_rec.DATA_LAST_FACTMAJ,
          v_tmp.DATAGEN,v_rec.RESTOBLIG,v_rec.VALOBLIG,v_rec.GRATIEDOC,v_rec.STORNO,v_rec.SCADENTAV,ROUND(((v_rec.MAJORARI / 100) * (v_tmp.datadoc::date - dataref) * aREST)::numeric, 2), v_tmp.datadoc::date - dataref,
          AIDX, v_rec.coddoc, v_rec.tipdoc, v_rec.seriadoc
          );
          --aVal := aVal + ROUND((v_rec.MAJORARI / 100) * (v_tmp.datadoc - dataref) * aREST, 2);
          dataref := v_tmp.datadoc;
        end if;
        aRest := aRest - v_tmp.valoare;
      else
        --corectez precedentele
        aVal := v_tmp.valoare;
        for v_xxx in (select * from tmp_gen_penalitati where codobligpif = v_rec.codobligpif AND DATADOC &lt;= V_TMP.DATAPEN order by datadoc) loop
          if aVal &gt; v_xxx.valmaj then
            update tmp_gen_penalitati SET VALMAJ = 0 WHERE CODUNIC = V_XXX.CODUNIC;
            AVAL := AVAL - V_XXX.VALMAJ;
          else
            update tmp_gen_penalitati SET VALMAJ = VALMAJ - AVAL WHERE CODUNIC = V_XXX.CODUNIC;
            AVAL := 0;
          end if;
          IF AVAL &lt;= 0 THEN EXIT; END IF;
        end loop;
      end if;

      --ROUND((MAJORARI / 100) * (' + SDATAREF + ' - COALESCE(DATA_LAST_FACTMAJ, TERMEN)) * REST, 2)
    END LOOP;
    --aVal := aVal + ROUND((v_rec.MAJORARI / 100) * (to_date(sDataRef,'dd.mm.yyyy') - dataref) * aREST, 2);
    --update TMP_GEN_PENALITATI set valmaj = aVal where codobligpif = v_rec.codobligpif;
    if aRest &lt; 0.01 then aRest := 0; end if;
    if to_date(sDataRef,'dd.mm.yyyy') - dataref &gt; 0 then
      aIdx := aIdx + 1;
      insert into tmp_gen_penalitati (
      CODOBLIGPIF,PREFIXDOC,NRDOC,DATADOC,VALDOC,TERMEN,REST,MAJORARI,PRELUAT,LOCATIE,
      DEN_PART,CODPART,CODLOCATIE,DEN_SUBUNIT,MONEDA,CODFISCAL,MAJANTERIOARE,DATA_LAST_FACTMAJ,
      DATA_LAST_PLATA,RESTOBLIG,VALOBLIG,GRATIEDOC,STORNO,SCADENTAV,VALMAJ,ZILE,CODUNIC,CODDOC,TIPDOC, Seriadoc
      )
      values (
      v_rec.CODOBLIGPIF,v_rec.PREFIXDOC,v_rec.NRDOC,v_rec.DATADOC,v_rec.VALDOC,v_rec.TERMEN,aRest,v_rec.MAJORARI,v_rec.PRELUAT,v_rec.LOCATIE,
      v_rec.DEN_PART,v_rec.CODPART,v_rec.CODLOCATIE,v_rec.DEN_SUBUNIT,v_rec.MONEDA,v_rec.CODFISCAL,v_rec.MAJANTERIOARE,v_rec.DATA_LAST_FACTMAJ,
      to_date(sDataRef,'dd.mm.yyyy'),v_rec.RESTOBLIG,v_rec.VALOBLIG,v_rec.GRATIEDOC,v_rec.STORNO,v_rec.SCADENTAV,ROUND(((v_rec.MAJORARI / 100) * (sDataRef::date - dataref) * aREST)::NUMERIC,2), sDataRef::date - dataref,
      AIDX,v_rec.CODDOC,v_rec.TIPDOC, v_rec.seriadoc
      );
    end if;
  END LOOP;
  delete FROM tmp_gen_penalitati_man where trunc(data_last_plata) &lt;= trunc(termen) and restoblig = 0;

  if vRestZero = 1 then
    FOR V_REC IN (SELECT row_number() OVER() nr, tmp.coddoc,tmp.tipdoc,tmp.CODOBLIGPIF,tmp.PREFIXDOC,tmp.NRDOC,tmp.DATADOC,tmp.VALDOC,tmp.TERMEN,tmp.REST,tmp.MAJORARI,tmp.PRELUAT,tmp.LOCATIE,
                  tmp.DEN_PART,tmp.CODPART,tmp.CODLOCATIE,tmp.DEN_SUBUNIT,tmp.MONEDA,tmp.CODFISCAL,tmp.MAJANTERIOARE,tmp.DATA_LAST_FACTMAJ,
                  tmp.DATA_LAST_PLATA,tmp.RESTOBLIG,tmp.VALOBLIG,tmp.GRATIEDOC,tmp.STORNO,tmp.SCADENTAV,tmp.VALMAJ, tmp.seriadoc
                  FROM tmp_gen_penalitati_man tmp where tmp.restoblig = 0) LOOP
      delete FROM tmp_gen_penalitati where codobligpif = v_rec.codobligpif;
      aVal := 0;
      aRest := v_rec.valoblig;

      dataref := v_rec.termen;
      FOR V_TMP IN (SELECT CODOBLIGPIF, DATADOC, VALOARE, DATAPEN, DATAGEN
                    FROM (
                    SELECT v_rec.CODOBLIGPIF CODOBLIGPIF, T1.DATADOC, s.valoare, NULL::date DATAPEN, T1.DATADOC DATAGEN
                    FROM STINGERE S
                         INNER JOIN OBLIGPIF OS ON OS.CODOBLIGPIF = S.CODSTINGATORPIF
                         INNER JOIN GENERAL GS ON GS.CODGENERAL = OS.CODGENERAL
                         INNER JOIN TREZOR T ON GS.TIPDOC = T.TIPDOC AND GS.TIPDOC IN (29,30,31)
                         INNER JOIN TREZOR1 T1 ON T.CODTREZOR = T1.CODTREZOR AND T1.CODTREZOR1 = GS.CODDOC
                    WHERE S.CODSTINSPIF = v_rec.CODOBLIGPIF
                    UNION ALL
                    SELECT v_rec.CODOBLIGPIF CODOBLIGPIF, CO.DATADOC, s.valoare, NULL::date DATAPEN, CO.DATADOC DATAGEN
                    FROM STINGERE S
                         INNER JOIN OBLIGPIF OS ON OS.CODOBLIGPIF = S.CODSTINGATORPIF
                         INNER JOIN GENERAL GS ON GS.CODGENERAL = OS.CODGENERAL
                         INNER JOIN COMPENS CO ON CO.CODCOMPENS = GS.CODDOC AND GS.TIPDOC = 28
                    WHERE S.CODSTINSPIF = v_rec.CODOBLIGPIF
                    UNION ALL
                    SELECT v_rec.CODOBLIGPIF CODOBLIGPIF, NULL DATADOC, i.valdoc-i.tvadoc valoare, coalesce(i1.termencontract,I.DATADOC) DATAPEN, coalesce(i1.termencontract,I.DATADOC) DATAGEN
                    FROM IESIRI1 I1
                         INNER JOIN IESIRI I ON I.CODIES = I1.CODIES AND COALESCE(I.ANULAT, 0) = 0
                    WHERE I1.CODOBLIGMAJORAT = v_rec.CODOBLIGPIF AND COALESCE(I.CODMONETAR,0) = 0
                    UNION ALL
                    SELECT V_REC.CODOBLIGPIF CODOBLIGPIF, I.DATADOC, SS.valoare, null datapen, I.DATADOC DATAGEN
                    FROM STINGERE SS
                         INNER JOIN OBLIGPIF OST ON OST.CODOBLIGPIF = SS.CODSTINGATORPIF
                         INNER JOIN GENERAL GST ON OST.CODGENERAL = GST.CODGENERAL
                         INNER JOIN IESIRI I ON I.CODIES = GST.CODDOC AND I.TIPDOC = GST.TIPDOC
                    WHERE SS.CODSTINSPIF = V_REC.CODOBLIGPIF AND GST.TIPDOC = 16
                         ) a_pg
                     ORDER BY DATAGEN
                   ) LOOP
        if not v_tmp.datapen is null then dataref := v_tmp.datapen; end if;
        if v_tmp.datapen is null then
          if v_tmp.datadoc &gt; v_rec.termen then
            if v_tmp.datadoc &gt; to_date(vDataRef,'dd.mm.yyyy') then
              aIdx := aIdx + 1;
              insert into tmp_gen_penalitati (
              CODOBLIGPIF,PREFIXDOC,NRDOC,DATADOC,VALDOC,TERMEN,REST,MAJORARI,PRELUAT,LOCATIE,
              DEN_PART,CODPART,CODLOCATIE,DEN_SUBUNIT,MONEDA,CODFISCAL,MAJANTERIOARE,DATA_LAST_FACTMAJ,
              DATA_LAST_PLATA,RESTOBLIG,VALOBLIG,GRATIEDOC,STORNO,SCADENTAV,VALMAJ,ZILE,CODUNIC,CODDOC,TIPDOC, seriadoc
              )
              values (
              v_rec.CODOBLIGPIF,v_rec.PREFIXDOC,v_rec.NRDOC,v_rec.DATADOC,v_rec.VALDOC,v_rec.TERMEN,aRest,v_rec.MAJORARI,v_rec.PRELUAT,v_rec.LOCATIE,
              v_rec.DEN_PART,v_rec.CODPART,v_rec.CODLOCATIE,v_rec.DEN_SUBUNIT,v_rec.MONEDA,v_rec.CODFISCAL,v_rec.MAJANTERIOARE,v_rec.DATA_LAST_FACTMAJ,
              v_tmp.DATAGEN,v_rec.RESTOBLIG,v_rec.VALOBLIG,v_rec.GRATIEDOC,v_rec.STORNO,v_rec.SCADENTAV,ROUND(((v_rec.MAJORARI / 100) * (vDataRef::date - dataref) * aREST)::NUMERIC, 2), (vDataRef::date - dataref),AIDX,
              v_rec.coddoc,v_rec.tipdoc, v_rec.seriadoc
              );
              aVal := aVal + ROUND((v_rec.MAJORARI / 100) * (to_date(vDataRef,'dd.mm.yyyy') - dataref) * aREST, 2);
              dataref := to_date(vDataRef,'dd.mm.yyyy');
            else
              aIdx := aIdx + 1;
              insert into tmp_gen_penalitati (
              CODOBLIGPIF,PREFIXDOC,NRDOC,DATADOC,VALDOC,TERMEN,REST,MAJORARI,PRELUAT,LOCATIE,
              DEN_PART,CODPART,CODLOCATIE,DEN_SUBUNIT,MONEDA,CODFISCAL,MAJANTERIOARE,DATA_LAST_FACTMAJ,
              DATA_LAST_PLATA,RESTOBLIG,VALOBLIG,GRATIEDOC,STORNO,SCADENTAV,VALMAJ,ZILE,CODUNIC,CODDOC,TIPDOC, seriadoc
              )
              values (
              v_rec.CODOBLIGPIF,v_rec.PREFIXDOC,v_rec.NRDOC,v_rec.DATADOC,v_rec.VALDOC,v_rec.TERMEN,aRest,v_rec.MAJORARI,v_rec.PRELUAT,v_rec.LOCATIE,
              v_rec.DEN_PART,v_rec.CODPART,v_rec.CODLOCATIE,v_rec.DEN_SUBUNIT,v_rec.MONEDA,v_rec.CODFISCAL,v_rec.MAJANTERIOARE,v_rec.DATA_LAST_FACTMAJ,
              v_tmp.DATAGEN,v_rec.RESTOBLIG,v_rec.VALOBLIG,v_rec.GRATIEDOC,v_rec.STORNO,v_rec.SCADENTAV,ROUND(((v_rec.MAJORARI / 100) * (v_tmp.datadoc::date - dataref) * aREST)::NUMERIC,2), (v_tmp.datadoc::date - dataref),AIDX,
              V_REC.CODDOC,V_REC.TIPDOC, v_rec.seriadoc
              );
              --aVal := aVal + ROUND((v_rec.MAJORARI / 100) * (v_tmp.datadoc - dataref) * aREST, 2);
              dataref := v_tmp.datadoc;
            end if;
            aRest := aRest - v_tmp.valoare;
          else
            aRest := aRest - v_tmp.valoare;
          end if;
        else
          --corectez precedentele
          aVal := v_tmp.valoare;
          for v_xxx in (select * from tmp_gen_penalitati where codobligpif = v_rec.codobligpif AND DATADOC &lt;= V_TMP.DATAPEN order by datadoc) loop
            if aVal &gt; v_xxx.valmaj then
              update tmp_gen_penalitati SET VALMAJ = 0 WHERE CODUNIC = V_XXX.CODUNIC;
              AVAL := AVAL - V_XXX.VALMAJ;
            else
              update tmp_gen_penalitati SET VALMAJ = VALMAJ - AVAL WHERE CODUNIC = V_XXX.CODUNIC;
              AVAL := 0;
            end if;
            IF AVAL &lt;= 0 THEN EXIT; END IF;
          end loop;
        end if;
        --ROUND((MAJORARI / 100) * (' + SDATAREF + ' - COALESCE(DATA_LAST_FACTMAJ, TERMEN)) * REST, 2)
      END LOOP;
      --aVal := aVal + ROUND((v_rec.MAJORARI / 100) * (to_date(sDataRef,'dd.mm.yyyy') - dataref) * aREST, 2);
      --update TMP_GEN_PENALITATI set valmaj = aVal where codobligpif = v_rec.codobligpif;
      if aRest &lt; 0.01 then aRest := 0; end if;
      if to_date(sDataRef,'dd.mm.yyyy') - dataref &gt; 0 then
        aIdx := aIdx + 1;
        insert into tmp_gen_penalitati (
        CODOBLIGPIF,PREFIXDOC,NRDOC,DATADOC,VALDOC,TERMEN,REST,MAJORARI,PRELUAT,LOCATIE,
        DEN_PART,CODPART,CODLOCATIE,DEN_SUBUNIT,MONEDA,CODFISCAL,MAJANTERIOARE,DATA_LAST_FACTMAJ,
        DATA_LAST_PLATA,RESTOBLIG,VALOBLIG,GRATIEDOC,STORNO,SCADENTAV,VALMAJ,ZILE,CODDOC,TIPDOC, seriadoc
        )
        values (
        v_rec.CODOBLIGPIF,v_rec.PREFIXDOC,v_rec.NRDOC,v_rec.DATADOC,v_rec.VALDOC,v_rec.TERMEN,aRest,v_rec.MAJORARI,v_rec.PRELUAT,v_rec.LOCATIE,
        v_rec.DEN_PART,v_rec.CODPART,v_rec.CODLOCATIE,v_rec.DEN_SUBUNIT,v_rec.MONEDA,v_rec.CODFISCAL,v_rec.MAJANTERIOARE,v_rec.DATA_LAST_FACTMAJ,
        to_date(sDataRef,'dd.mm.yyyy'),v_rec.RESTOBLIG,v_rec.VALOBLIG,v_rec.GRATIEDOC,v_rec.STORNO,v_rec.SCADENTAV,ROUND(((v_rec.MAJORARI / 100) * (to_date(sDataRef,'dd.mm.yyyy') - dataref) * aREST)::NUMERIC,2), (sDataRef::date - dataref),
        V_REC.CODDOC,V_REC.TIPDOC, v_rec.seriadoc
        );
      end if;
    END LOOP;
  end if;

  DELETE FROM tmp_gen_penalitati WHERE VALMAJ = 0;
  UPDATE TMP_GEN_PENALITATI TMP
  SET
    RESTLADATA =
    (SELECT O.VALOARE -
            COALESCE
            (
              (SELECT
                 COALESCE(SUM(S.VALOARE), 0)
               FROM STINGERE S
                    INNER JOIN OBLIGPIF OS ON OS.CODOBLIGPIF = S.CODSTINGATORPIF
                    INNER JOIN GENERAL GS ON GS.CODGENERAL = OS.CODGENERAL
                    INNER JOIN TREZOR T ON GS.TIPDOC = T.TIPDOC AND GS.TIPDOC IN (29,30,31)
                    INNER JOIN TREZOR1 T1 ON T.CODTREZOR = T1.CODTREZOR AND T1.CODTREZOR1 = GS.CODDOC
               WHERE S.CODSTINSPIF = TMP.CODOBLIGPIF AND T1.DATADOC &lt;= DATAREF
            ), 0)-
            COALESCE
            (
              (SELECT
                 COALESCE(SUM(S.VALOARE), 0)
               FROM STINGERE S
                    INNER JOIN OBLIGPIF OS ON OS.CODOBLIGPIF = S.CODSTINGATORPIF
                    INNER JOIN GENERAL GS ON GS.CODGENERAL = OS.CODGENERAL
                    INNER JOIN COMPENS CO ON CO.CODCOMPENS = GS.CODDOC AND GS.TIPDOC = 28
               WHERE S.CODSTINSPIF = TMP.CODOBLIGPIF AND CO.DATADOC &lt;= DATAREF
            ), 0)
     FROM OBLIGPIF O
     WHERE O.CODOBLIGPIF = TMP.CODOBLIGPIF
    );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getdisccumulat</obj_name>
  <obj_hashval>86c660eb5e4adc8c8a6cf5b9ea7eebfa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getdisccumulat(INOUT wme_result numeric, INOUT vcoddoc1 numeric, INOUT vcodcontract1 numeric, INOUT vtip numeric, INOUT vvalorig numeric DEFAULT 0)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC          RECORD;
  vTotalPlata    numeric;
  vTotalDoc      numeric;
  vTotalLinie    numeric;
  vPartial       numeric;
  vCodObiect     numeric;
  vDisc          numeric;
  vTipDiscountT  numeric;
  vTipDiscountT1 numeric;
  vDiscT         numeric;
  vCant          numeric;
  vDataDoc       date;
begin
  vDisc := 0;
  IF  vValOrig &gt; 9 THEN
    IF  vTip = 1 THEN
      SELECT i1.codobiect, i.valdoc, i.datadoc, CASE WHEN  i.tipdoc = 21 THEN i1.PretOrig * i1.cant ELSE i1.PretOrig * i1.cant + i1.tva END , i1.cant
      INTO vCodObiect, vTotalDoc, vDataDoc, vTotalLinie, vCant
      FROM iesiri1 i1 INNER JOIN iesiri i ON  i.codies = i1.codies
      WHERE codies1 = vCodDoc1;

      BEGIN
        SELECT sum(s.valoare)
        INTO vTotalPlata
        FROM iesiri1 i1
            INNER JOIN iesiri i ON  i.codies = i1.codies
            INNER JOIN general g ON  g.coddoc = i.codies and  g.tipdoc = i.tipdoc
            INNER JOIN obligpif ostins ON  ostins.codgeneral = g.codgeneral
            INNER JOIN stingere s ON  s.codstinspif = ostins.codobligpif
        WHERE
           i1.codies1 = vCodDoc1;
      EXCEPTION WHEN others THEN
        vTotalPlata := 0;
      END;

      IF  vTotalDoc &lt;&gt; vTotalPlata THEN
        WME_Result :=  0;
        RETURN;
      END IF;

      BEGIN
        SELECT COALESCE(c1.TipDiscountT, 0) INTO vTipDiscountT FROM contract1 c1 WHERE c1.codcontract1 = vCodContract1;
      EXCEPTION WHEN others THEN
        vTipDiscountT := -1;
      END;

      IF  vTipDiscountT = 0 THEN
        FOR v_rec IN (SELECT * FROM contractt_manevra WHERE codcontract1 = vCodContract1 ORDER BY zile) LOOP
          BEGIN
            SELECT sum(stingere.valoare)
            INTO vPartial
            FROM iesiri1 i1
                INNER JOIN iesiri i ON  i1.codies = i.codies
                INNER JOIN general g ON  g.coddoc = i.codies and  g.tipdoc = i.tipdoc
                INNER JOIN obligpif ostins ON  ostins.codgeneral = g.codgeneral
                INNER JOIN stingere ON  stingere.codstinspif = ostins.codobligpif
                INNER JOIN obligpif ostingator ON  stingere.codstingatorpif = ostingator.codobligpif
                INNER JOIN general gs ON  gs.codgeneral = ostingator.codgeneral
                LEFT JOIN trezor1 t1 ON  gs.coddoc = t1.codtrezor1
                LEFT JOIN trezor t ON  t1.codtrezor = t.codtrezor and  gs.tipdoc = t.tipdoc
                LEFT JOIN (SELECT c.datadoc, c.codcompens, 28 TIPDOC FROM compens c) comp ON  comp.codcompens = gs.coddoc and  comp.tipdoc = gs.tipdoc
            WHERE
              COALESCE(t1.datadoc, comp.datadoc) - vDataDoc BETWEEN v_rec.ziledela AND v_rec.zile and  i1.codies1 = vCodDoc1 AND (  (  gs.TipDoc IN (29, 30, 31) AND  t1.TipTranz = 1)  OR (   t1.TipTranz = 1 AND  t1.ObiectTranz = 1)  or (   t1.tiptranz = 1 and  t1.obiecttranz = 0 and  gs.tipdoc = 33) )  AND  T1.Anulat &lt;&gt; 1 AND  T.operat = 1;
          EXCEPTION WHEN others THEN
            vPartial := 0;
          END;

          IF  vPartial / vTotalDoc * 100 &lt; v_rec.procvaldoc THEN
            IF  vTotalPlata - vPartial &lt;= 0 THEN
              vTotalPlata := vTotalPlata - vPartial;
              EXIT ;
            END IF;
            vDisc := -1;
            EXIT ;
          ELSE
            vTotalPlata := vTotalPlata - vPartial;
            IF  vTotalPlata &lt;= 0 THEN
              EXIT ;
            END IF;
          END IF;
        END LOOP;

        IF  vDisc = -1 THEN
          WME_Result :=  0;
          RETURN;
        END IF;

        IF  vTotalPlata &lt;= 0 THEN
          BEGIN
            SELECT COALESCE(c1.TipDiscountT1, 0), COALESCE(c1.disct, 0) INTO vTipDiscountT1, vDiscT FROM contract1 c1 WHERE c1.codcontract1 = vCodContract1;
          EXCEPTION WHEN others THEN
            vTipDiscountT1 := -1;
          END;

          IF  vTipDiscountT1 = 0 THEN
            vDisc := vTotalLinie * vDiscT / 100;
          ELSE
            IF  vTipDiscountT1 = 1 THEN
              vDisc := vDiscT * vCant;
            END IF;
          END IF;
        END IF;
      ELSE
        IF  vTipDiscountT = 1 THEN
          FOR v_rec IN (SELECT * FROM contractt_manevra WHERE codcontract1 = vCodContract1 ORDER BY termenfix) LOOP
            BEGIN
              SELECT sum(stingere.valoare)
              INTO vPartial
              FROM iesiri1 i1
                  INNER JOIN iesiri i ON  i1.codies = i.codies
                  INNER JOIN general g ON  g.coddoc = i.codies and  g.tipdoc = i.tipdoc
                  INNER JOIN obligpif ostins ON  ostins.codgeneral = g.codgeneral
                  INNER JOIN stingere ON  stingere.codstinspif = ostins.codobligpif
                  INNER JOIN obligpif ostingator ON  stingere.codstingatorpif = ostingator.codobligpif
                  INNER JOIN general gs ON  gs.codgeneral = ostingator.codgeneral
                  LEFT JOIN trezor1 t1 ON  gs.coddoc = t1.codtrezor1
                  LEFT JOIN trezor t ON  t1.codtrezor = t.codtrezor and  gs.tipdoc = t.tipdoc
                  LEFT JOIN (SELECT c.datadoc, c.codcompens, 28 TIPDOC FROM compens c) comp ON  comp.codcompens = gs.coddoc and  comp.tipdoc = gs.tipdoc
              WHERE
                COALESCE(t1.datadoc, comp.datadoc) BETWEEN v_rec.termenfixdela AND v_rec.termenfix and  i1.codies1 = vCodDoc1 AND (  (  gs.TipDoc IN (29, 30, 31) AND  t1.TipTranz = 1)  OR (   t1.TipTranz = 1 AND  t1.ObiectTranz = 1)  or (   t1.tiptranz = 1 and  t1.obiecttranz = 0 and  gs.tipdoc = 33) )  AND  T1.Anulat &lt;&gt; 1 AND  T.operat = 1;
            EXCEPTION WHEN others THEN
              vPartial := 0;
            END;

            IF  vPartial / vTotalDoc * 100 &lt; v_rec.procvaldoc THEN
              IF  vTotalPlata - vPartial &lt;= 0 THEN
                vTotalPlata := vTotalPlata - vPartial;
                EXIT ;
              END IF;
              vDisc := -1;
              EXIT ;
            ELSE
              vTotalPlata := vTotalPlata - vPartial;
              IF  vTotalPlata &lt;= 0 THEN
                EXIT ;
              END IF;
            END IF;
          END LOOP;

          IF  vDisc = -1 THEN
            WME_Result :=  0;
            RETURN;
          END IF;

          IF  vTotalPlata &lt;= 0 THEN
            BEGIN
              SELECT COALESCE(c1.TipDiscountT1, 0), COALESCE(c1.disct, 0) INTO vTipDiscountT1, vDiscT FROM contract1 c1 WHERE c1.codcontract1 = vCodContract1;
            EXCEPTION WHEN others THEN
              vTipDiscountT1 := -1;
            END;

            IF  vTipDiscountT1 = 0 THEN
              vDisc := vTotalLinie * vDiscT / 100;
            ELSE
              IF  vTipDiscountT1 = 1 THEN
                vDisc := vDiscT * vCant;
              END IF;
            END IF;
          END IF;
        END IF;
      END IF;
    ELSE
      SELECT i1.codobiect, i.valdoc, i.datadoc, i1.pu * i1.cant + i1.tva, i1.cant
      INTO vCodObiect, vTotalDoc, vDataDoc, vTotalLinie, vCant
      FROM intrari1 i1 INNER JOIN intrari i ON  i.codintr = i1.codintr
      WHERE codintr1 = vCodDoc1;

      BEGIN
        SELECT sum(s.valoare)
        INTO vTotalPlata
        FROM intrari1 i1
            INNER JOIN intrari i ON  i.codintr = i1.codintr
            INNER JOIN general g ON  g.coddoc = i.codintr and  g.tipdoc = i.tipdoc
            INNER JOIN obligpif ostins ON  ostins.codgeneral = g.codgeneral
            INNER JOIN stingere s ON  s.codstinspif = ostins.codobligpif
        WHERE i1.codintr1 = vCodDoc1;
      EXCEPTION WHEN others THEN
        vTotalPlata := 0;
      END;

      IF  vTotalDoc &lt;&gt; vTotalPlata THEN
        WME_Result :=  0;
        RETURN;
      END IF;

      BEGIN
        SELECT COALESCE(c1.TipDiscountT, 0) INTO vTipDiscountT FROM contract1 c1 WHERE c1.codcontract1 = vCodContract1;
      EXCEPTION WHEN others THEN
        vTipDiscountT := -1;
      END;

      IF  vTipDiscountT = 0 THEN
        FOR v_rec IN (SELECT * FROM contractt_manevra WHERE codcontract1 = vCodContract1 ORDER BY zile) LOOP
          BEGIN
            SELECT sum(stingere.valoare)
            INTO vPartial
            FROM intrari1 i1
                INNER JOIN intrari i ON  i1.codintr = i.codintr
                INNER JOIN general g ON  g.coddoc = i.codintr and  g.tipdoc = i.tipdoc
                INNER JOIN obligpif ostins ON  ostins.codgeneral = g.codgeneral
                INNER JOIN stingere ON  stingere.codstinspif = ostins.codobligpif
                INNER JOIN obligpif ostingator ON  stingere.codstingatorpif = ostingator.codobligpif
                INNER JOIN general gs ON  gs.codgeneral = ostingator.codgeneral
                LEFT  JOIN trezor1 t1 ON  gs.coddoc = t1.codtrezor1
                LEFT  JOIN trezor t ON  t1.codtrezor = t.codtrezor and  gs.tipdoc = t.tipdoc
                LEFT  JOIN (SELECT c.datadoc, c.codcompens, 28 TIPDOC FROM compens c) comp ON  comp.codcompens = gs.coddoc and  comp.tipdoc = gs.tipdoc
            WHERE
              COALESCE(t1.datadoc, comp.datadoc) - vDataDoc BETWEEN v_rec.ziledela AND v_rec.zile and  i1.codintr1 = vCodDoc1 AND (  (  G.TipDoc IN (29, 30, 31) AND  t1.TipTranz = 0)  OR (   t1.TipTranz = 0 AND  t1.ObiectTranz = 1) )  AND  T1.Anulat &lt;&gt; 1 AND  T.operat = 1;
          EXCEPTION WHEN others THEN
            vPartial := 0;
          END;

          IF  vPartial / vTotalDoc * 100 &lt; v_rec.procvaldoc THEN
            IF  vTotalPlata - vPartial &lt;= 0 THEN
              vTotalPlata := vTotalPlata - vPartial;
              EXIT ;
            END IF;
            vDisc := -1;
            EXIT ;
          ELSE
            vTotalPlata := vTotalPlata - vPartial;
            IF  vTotalPlata &lt;= 0 THEN
              EXIT ;
            END IF;
          END IF;
        END LOOP;

        IF  vDisc = -1 THEN
          WME_Result :=  0;
          RETURN;
        END IF;

        IF  vTotalPlata &lt;= 0 THEN
          BEGIN
            SELECT COALESCE(c1.TipDiscountT1, 0), COALESCE(c1.disct, 0) INTO vTipDiscountT1, vDiscT FROM contract1 c1 WHERE c1.codcontract1 = vCodContract1;
          EXCEPTION WHEN others THEN
            vTipDiscountT1 := -1;
          END;

          IF  vTipDiscountT1 = 0 THEN
            vDisc := vTotalLinie * vDiscT / 100;
          ELSE
            IF  vTipDiscountT1 = 1 THEN
              vDisc := vDiscT * vCant;
            END IF;
          END IF;
        END IF;
      ELSE
        IF  vTipDiscountT = 1 THEN
          FOR v_rec IN (SELECT * FROM contractt_manevra WHERE codcontract1 = vCodContract1 ORDER BY termenfix) LOOP
            BEGIN
              SELECT sum(stingere.valoare)
              INTO vPartial
              FROM iesiri1 i1
              INNER JOIN iesiri i ON  i1.codies = i.codies
              INNER JOIN general g ON  g.coddoc = i.codies and  g.tipdoc = i.tipdoc
              INNER JOIN obligpif ostins ON  ostins.codgeneral = g.codgeneral
              INNER JOIN stingere ON  stingere.codstinspif = ostins.codobligpif
              INNER JOIN obligpif ostingator ON  stingere.codstingatorpif = ostingator.codobligpif
              INNER JOIN general gs ON  gs.codgeneral = ostingator.codgeneral
              LEFT  JOIN trezor1 t1 ON  gs.coddoc = t1.codtrezor1
              LEFT  JOIN trezor t ON  t1.codtrezor = t.codtrezor and  gs.tipdoc = t.tipdoc
              LEFT  JOIN (SELECT c.datadoc, c.codcompens, 28 TIPDOC FROM compens c) comp ON  comp.codcompens = gs.coddoc and  comp.tipdoc = gs.tipdoc
              WHERE
                COALESCE(t1.datadoc, comp.datadoc) BETWEEN v_rec.termenfixdela AND v_rec.termenfix and  i1.codies1 = vCodDoc1 AND (  (  G.TipDoc IN (29, 30, 31) AND  t1.TipTranz = 0)  OR (   t1.TipTranz = 0 AND  t1.ObiectTranz = 1) )  AND  T1.Anulat &lt;&gt; 1 AND  T.operat = 1;
            EXCEPTION WHEN others THEN
              vPartial := 0;
            END;

            IF  vPartial / vTotalDoc * 100 &lt; v_rec.procvaldoc THEN
              IF  vTotalPlata - vPartial &lt;= 0 THEN
                vTotalPlata := vTotalPlata - vPartial;
                EXIT ;
              END IF;
              vDisc := -1;
              EXIT ;
            ELSE
              vTotalPlata := vTotalPlata - vPartial;
              IF  vTotalPlata &lt;= 0 THEN
                EXIT ;
              END IF;
            END IF;
          END LOOP;

          IF  vDisc = -1 THEN
            WME_Result :=  0;
            RETURN;
          END IF;

          IF  vTotalPlata &lt;= 0 THEN
            BEGIN
              SELECT COALESCE(c1.TipDiscountT1, 0), COALESCE(c1.disct, 0) INTO vTipDiscountT1, vDiscT FROM contract1 c1 WHERE c1.codcontract1 = vCodContract1;
            EXCEPTION WHEN others THEN
              vTipDiscountT1 := -1;
            END;

            IF  vTipDiscountT1 = 0 THEN
              vDisc := vTotalLinie * vDiscT / 100;
            ELSE
              IF  vTipDiscountT1 = 1 THEN
                vDisc := vDiscT * vCant;
              END IF;
            END IF;
          END IF;
        END IF;
      END IF;
    END IF;
  ELSE
    IF  vTip = 1 THEN
      SELECT i1.codobiect, i.valdoc, i.datadoc,
             CASE WHEN  i.tipdoc = 21 THEN i1.PretOrig * i1.cant * COALESCE(i1.coefdiscmaj, 1)
                  ELSE (  i1.PretOrig * i1.cant + i1.tva)  * COALESCE(i1.coefdiscmaj, 1)
             END , i1.cant
      INTO vCodObiect, vTotalDoc, vDataDoc, vTotalLinie, vCant
      FROM iesiri1 i1 INNER JOIN iesiri i ON  i.codies = i1.codies
      WHERE codies1 = vCodDoc1;

      BEGIN
        SELECT sum(s.valoare)
        INTO vTotalPlata
        FROM iesiri1 i1
          INNER JOIN iesiri i ON  i.codies = i1.codies
          INNER JOIN general g ON  g.coddoc = i.codies and  g.tipdoc = i.tipdoc
          INNER JOIN obligpif ostins ON  ostins.codgeneral = g.codgeneral
          INNER JOIN stingere s ON  s.codstinspif = ostins.codobligpif
        WHERE i1.codies1 = vCodDoc1;
      EXCEPTION WHEN others THEN
        vTotalPlata := 0;
      END;

      IF  vTotalDoc &lt;&gt; vTotalPlata THEN
        WME_Result :=  0;
        RETURN;
      END IF;

      BEGIN
        SELECT COALESCE(c1.TipDiscountT, 0) INTO vTipDiscountT FROM contract1 c1 WHERE c1.codcontract1 = vCodContract1;
      EXCEPTION WHEN others THEN
        vTipDiscountT := -1;
      END;

      IF  vTipDiscountT = 0 THEN
        FOR v_rec IN (SELECT * FROM contractt_manevra WHERE codcontract1 = vCodContract1 ORDER BY zile) LOOP
          BEGIN
            SELECT sum(stingere.valoare)
            INTO vPartial
            FROM iesiri1 i1
              INNER JOIN iesiri i ON  i1.codies = i.codies
              INNER JOIN general g ON  g.coddoc = i.codies and  g.tipdoc = i.tipdoc
              INNER JOIN obligpif ostins ON  ostins.codgeneral = g.codgeneral
              INNER JOIN stingere ON  stingere.codstinspif = ostins.codobligpif
              INNER JOIN obligpif ostingator ON  stingere.codstingatorpif = ostingator.codobligpif
              INNER JOIN general gs ON  gs.codgeneral = ostingator.codgeneral
              LEFT JOIN trezor1 t1 ON  gs.coddoc = t1.codtrezor1
              LEFT JOIN trezor t ON  t1.codtrezor = t.codtrezor and  gs.tipdoc = t.tipdoc
              LEFT JOIN (SELECT c.datadoc, c.codcompens, 28 TIPDOC FROM compens c) comp ON  comp.codcompens = gs.coddoc and  comp.tipdoc = gs.tipdoc
            WHERE
              COALESCE(t1.datadoc, comp.datadoc) - vDataDoc BETWEEN v_rec.ziledela AND v_rec.zile and  i1.codies1 = vCodDoc1 AND (  (  gs.TipDoc IN (29, 30, 31) AND  t1.TipTranz = 1)  OR (   t1.TipTranz = 1 AND  t1.ObiectTranz = 1)  or (   t1.tiptranz = 1 and  t1.obiecttranz = 0 and  gs.tipdoc = 33) )  AND  T1.Anulat &lt;&gt; 1 AND  T.operat = 1;
          EXCEPTION WHEN others THEN
            vPartial := 0;
          END;

          IF  vPartial / vTotalDoc * 100 &lt; v_rec.procvaldoc THEN
            IF  vTotalPlata - vPartial &lt;= 0 THEN
              vTotalPlata := vTotalPlata - vPartial;
              EXIT ;
            END IF;
            vDisc := -1;
            EXIT ;
          ELSE
            vTotalPlata := vTotalPlata - vPartial;
            IF  vTotalPlata &lt;= 0 THEN
              EXIT ;
            END IF;
          END IF;
        END LOOP;

        IF  vDisc = -1 THEN
          WME_Result :=  0;
          RETURN;
        END IF;

        IF  vTotalPlata &lt;= 0 THEN
          BEGIN
            SELECT COALESCE(c1.TipDiscountT1, 0), COALESCE(c1.disct, 0) INTO vTipDiscountT1, vDiscT FROM contract1 c1 WHERE c1.codcontract1 = vCodContract1;
          EXCEPTION WHEN others THEN
            vTipDiscountT1 := -1;
          END;

          IF  vTipDiscountT1 = 0 THEN
            vDisc := vTotalLinie * vDiscT / 100;
          ELSE
            IF  vTipDiscountT1 = 1 THEN
              vDisc := vDiscT * vCant;
            END IF;
          END IF;
        END IF;
      ELSE
        IF  vTipDiscountT = 1 THEN
          FOR v_rec IN (SELECT * FROM contractt_manevra WHERE codcontract1 = vCodContract1 ORDER BY termenfix) LOOP
            BEGIN
              SELECT sum(stingere.valoare)
              INTO vPartial
              FROM iesiri1 i1
                  INNER JOIN iesiri i ON  i1.codies = i.codies
                  INNER JOIN general g ON  g.coddoc = i.codies and  g.tipdoc = i.tipdoc
                  INNER JOIN obligpif ostins ON  ostins.codgeneral = g.codgeneral
                  INNER JOIN stingere ON  stingere.codstinspif = ostins.codobligpif
                  INNER JOIN obligpif ostingator ON  stingere.codstingatorpif = ostingator.codobligpif
                  INNER JOIN general gs ON  gs.codgeneral = ostingator.codgeneral
                  LEFT  JOIN trezor1 t1 ON  gs.coddoc = t1.codtrezor1
                  LEFT  JOIN trezor t ON  t1.codtrezor = t.codtrezor and  gs.tipdoc = t.tipdoc
                  LEFT  JOIN (SELECT c.datadoc, c.codcompens, 28 TIPDOC FROM compens c) comp ON  comp.codcompens = gs.coddoc and  comp.tipdoc = gs.tipdoc
              WHERE
                COALESCE(t1.datadoc, comp.datadoc) BETWEEN v_rec.termenfixdela AND v_rec.termenfix and  i1.codies1 = vCodDoc1 AND (  (  gs.TipDoc IN (29, 30, 31) AND  t1.TipTranz = 1)  OR (   t1.TipTranz = 1 AND  t1.ObiectTranz = 1)  or (   t1.tiptranz = 1 and  t1.obiecttranz = 0 and  gs.tipdoc = 33) )  AND  T1.Anulat &lt;&gt; 1 AND  T.operat = 1;
            EXCEPTION WHEN others THEN
              vPartial := 0;
            END;

            IF  vPartial / vTotalDoc * 100 &lt; v_rec.procvaldoc THEN
              IF  vTotalPlata - vPartial &lt;= 0 THEN
                vTotalPlata := vTotalPlata - vPartial;
                EXIT ;
              END IF;
              vDisc := -1;
              EXIT ;
            ELSE
              vTotalPlata := vTotalPlata - vPartial;
              IF  vTotalPlata &lt;= 0 THEN
                EXIT ;
              END IF;
            END IF;
          END LOOP;

          IF  vDisc = -1 THEN
            WME_Result :=  0;
            RETURN;
          END IF;

          IF  vTotalPlata &lt;= 0 THEN
            BEGIN
              SELECT COALESCE(c1.TipDiscountT1, 0), COALESCE(c1.disct, 0) INTO vTipDiscountT1, vDiscT FROM contract1 c1 WHERE c1.codcontract1 = vCodContract1;
            EXCEPTION WHEN others THEN
              vTipDiscountT1 := -1;
            END;

            IF  vTipDiscountT1 = 0 THEN
              vDisc := vTotalLinie * vDiscT / 100;
            ELSE
              IF  vTipDiscountT1 = 1 THEN
                vDisc := vDiscT * vCant;
              END IF;
            END IF;
          END IF;
        END IF;
      END IF;
    ELSE
      SELECT i1.codobiect, i.valdoc, i.datadoc, i1.pu * i1.cant + i1.tva, i1.cant
      INTO vCodObiect, vTotalDoc, vDataDoc, vTotalLinie, vCant
      FROM intrari1 i1 INNER JOIN intrari i ON  i.codintr = i1.codintr
      WHERE codintr1 = vCodDoc1;

      BEGIN
        SELECT sum(s.valoare)
        INTO vTotalPlata
        FROM intrari1 i1
            INNER JOIN intrari i ON  i.codintr = i1.codintr
            INNER JOIN general g ON  g.coddoc = i.codintr and  g.tipdoc = i.tipdoc
            INNER JOIN obligpif ostins ON  ostins.codgeneral = g.codgeneral
            INNER JOIN stingere s ON  s.codstinspif = ostins.codobligpif
        WHERE
           i1.codintr1 = vCodDoc1;
      EXCEPTION WHEN others THEN
        vTotalPlata := 0;
      END;

      IF  vTotalDoc &lt;&gt; vTotalPlata THEN
        WME_Result :=  0;
        RETURN;
      END IF;

      BEGIN
        SELECT COALESCE(c1.TipDiscountT, 0) INTO vTipDiscountT FROM contract1 c1 WHERE c1.codcontract1 = vCodContract1;
      EXCEPTION WHEN others THEN
        vTipDiscountT := -1;
      END;

      IF  vTipDiscountT = 0 THEN
        FOR v_rec IN (SELECT * FROM contractt_manevra WHERE codcontract1 = vCodContract1 ORDER BY zile) LOOP
          BEGIN
            SELECT sum(stingere.valoare)
            INTO vPartial
            FROM intrari1 i1
            INNER JOIN intrari i ON  i1.codintr = i.codintr
            INNER JOIN general g ON  g.coddoc = i.codintr and  g.tipdoc = i.tipdoc
            INNER JOIN obligpif ostins ON  ostins.codgeneral = g.codgeneral
            INNER JOIN stingere ON  stingere.codstinspif = ostins.codobligpif
            INNER JOIN obligpif ostingator ON  stingere.codstingatorpif = ostingator.codobligpif
            INNER JOIN general gs ON  gs.codgeneral = ostingator.codgeneral
            LEFT  JOIN trezor1 t1 ON  gs.coddoc = t1.codtrezor1
            LEFT  JOIN trezor t ON  t1.codtrezor = t.codtrezor and  gs.tipdoc = t.tipdoc
            LEFT  JOIN (SELECT c.datadoc, c.codcompens, 28 TIPDOC FROM compens c) comp ON  comp.codcompens = gs.coddoc and  comp.tipdoc = gs.tipdoc
            WHERE
              COALESCE(t1.datadoc, comp.datadoc) - vDataDoc BETWEEN v_rec.ziledela AND v_rec.zile and  i1.codintr1 = vCodDoc1 AND (  (  gs.TipDoc IN (29, 30, 31) AND  t1.TipTranz = 0)  OR (   t1.TipTranz = 0 AND  t1.ObiectTranz = 0) )  AND  T1.Anulat &lt;&gt; 1 AND  T.operat = 1;
          EXCEPTION WHEN others THEN
            vPartial := 0;
          END;

          IF  vPartial / vTotalDoc * 100 &lt; v_rec.procvaldoc THEN
            IF  vTotalPlata - vPartial &lt;= 0 THEN
              vTotalPlata := vTotalPlata - vPartial;
              EXIT ;
            END IF;
            vDisc := -1;
            EXIT ;
          ELSE
            vTotalPlata := vTotalPlata - vPartial;
            IF  vTotalPlata &lt;= 0 THEN
              EXIT ;
            END IF;
          END IF;
        END LOOP;

        IF  vDisc = -1 THEN
          WME_Result :=  0;
          RETURN;
        END IF;

        IF  vTotalPlata &lt;= 0 THEN
          BEGIN
            SELECT COALESCE(c1.TipDiscountT1, 0), COALESCE(c1.disct, 0) INTO vTipDiscountT1, vDiscT FROM contract1 c1 WHERE c1.codcontract1 = vCodContract1;
          EXCEPTION WHEN others THEN
            vTipDiscountT1 := -1;
          END;

          IF  vTipDiscountT1 = 0 THEN
            vDisc := vTotalLinie * vDiscT / 100;
          ELSE
            IF  vTipDiscountT1 = 1 THEN
              vDisc := vDiscT * vCant;
            END IF;
          END IF;
        END IF;
      ELSE
        IF  vTipDiscountT = 1 THEN
          FOR v_rec IN (SELECT * FROM contractt_manevra WHERE codcontract1 = vCodContract1 ORDER BY termenfix) LOOP
            BEGIN
              SELECT sum(stingere.valoare)
              INTO vPartial
              FROM intrari1 i1
                INNER JOIN intrari i ON  i1.codintr = i.codintr
                INNER JOIN general g ON  g.coddoc = i.codintr and  g.tipdoc = i.tipdoc
                INNER JOIN obligpif ostins ON  ostins.codgeneral = g.codgeneral
                INNER JOIN stingere ON  stingere.codstinspif = ostins.codobligpif
                INNER JOIN obligpif ostingator ON  stingere.codstingatorpif = ostingator.codobligpif
                INNER JOIN general gs ON  gs.codgeneral = ostingator.codgeneral
                LEFT  JOIN trezor1 t1 ON  gs.coddoc = t1.codtrezor1
                LEFT  JOIN trezor t ON  t1.codtrezor = t.codtrezor and  gs.tipdoc = t.tipdoc
                LEFT  JOIN (SELECT c.datadoc, c.codcompens, 28 TIPDOC FROM compens c) comp ON  comp.codcompens = gs.coddoc and  comp.tipdoc = gs.tipdoc
              WHERE
                COALESCE(t1.datadoc, comp.datadoc) BETWEEN v_rec.termenfixdela AND v_rec.termenfix and  i1.codintr1 = vCodDoc1 AND (  (  gs.TipDoc IN (29, 30, 31) AND  t1.TipTranz = 0)  OR (   t1.TipTranz = 0 AND  t1.ObiectTranz = 0) )  AND  T1.Anulat &lt;&gt; 1 AND  T.operat = 1;
            EXCEPTION WHEN others THEN
              vPartial := 0;
            END;

            IF  vPartial / vTotalDoc * 100 &lt; v_rec.procvaldoc THEN
              IF  vTotalPlata - vPartial &lt;= 0 THEN
                vTotalPlata := vTotalPlata - vPartial;
                EXIT ;
              END IF;
              vDisc := -1;
              EXIT ;
            ELSE
              vTotalPlata := vTotalPlata - vPartial;
              IF  vTotalPlata &lt;= 0 THEN
                EXIT ;
              END IF;
            END IF;
          END LOOP;

          IF  vDisc = -1 THEN
            WME_Result :=  0;
            RETURN;
          END IF;

          IF  vTotalPlata &lt;= 0 THEN
            BEGIN
              SELECT COALESCE(c1.TipDiscountT1, 0), COALESCE(c1.disct, 0) INTO vTipDiscountT1, vDiscT FROM contract1 c1 WHERE c1.codcontract1 = vCodContract1;
            EXCEPTION WHEN others THEN
              vTipDiscountT1 := -1;
            END;

            IF  vTipDiscountT1 = 0 THEN
              vDisc := vTotalLinie * vDiscT / 100;
            ELSE
              IF  vTipDiscountT1 = 1 THEN
                vDisc := vDiscT * vCant;
              END IF;
            END IF;
          END IF;
        END IF;
      END IF;
    END IF;
  END IF;

  WME_Result :=  vDisc;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getdisccumulat</obj_name>
  <obj_hashval>2e7ae5466b38ace46abd5437e3d42b9b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getdisccumulat(INOUT wme_result numeric, INOUT vcoddoc1 numeric, INOUT vcodcontract1 numeric, INOUT vtip numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC           RECORD;
  vTotalPlata     double precision;
  vTotalDoc       double precision;
  vTotalLinie     double precision;
  vPartial         double precision;
  vCodObiect       numeric;
  vDisc           double precision;
  vTipDiscountT   numeric;
  vTipDiscountT1   numeric;
  vDiscT           double precision;
  vCant           double precision;
  vDataDoc         date;
begin
  vDisc := 0;
  IF  vTip = 1 THEN
    SELECT i1.codobiect, i.valdoc, i.datadoc,
           CASE WHEN  i.tipdoc = 21 THEN i1.PretOrig * i1.cant * COALESCE( i1.coefdiscmaj, 1)
                ELSE (  i1.PretOrig * i1.cant + i1.tva)  * COALESCE( i1.coefdiscmaj, 1)
           END ,
           i1.cant
    INTO vCodObiect, vTotalDoc, vDataDoc, vTotalLinie, vCant
    FROM iesiri1 i1 INNER JOIN iesiri i ON  i.codies = i1.codies
    WHERE codies1 = vCodDoc1;

    BEGIN
      SELECT sum( s.valoare)
      INTO vTotalPlata
      FROM iesiri1 i1
          INNER JOIN iesiri   i      ON  i.codies = i1.codies
          INNER JOIN general  g      ON  g.coddoc = i.codies and  g.tipdoc = i.tipdoc
          INNER JOIN obligpif ostins ON  ostins.codgeneral = g.codgeneral
          INNER JOIN stingere s      ON  s.codstinspif = ostins.codobligpif
      WHERE i1.codies1 = vCodDoc1;
    EXCEPTION WHEN others THEN
      vTotalPlata := 0;
    END;

    IF  vTotalDoc &lt;&gt; vTotalPlata THEN
      WME_Result :=  0;
      RETURN;
    END IF;

    BEGIN
      SELECT COALESCE( c1.TipDiscountT, 0) INTO vTipDiscountT FROM contract1 c1 WHERE c1.codcontract1 = vCodContract1;
    EXCEPTION WHEN others THEN
      vTipDiscountT := -1;
    END;

    IF  vTipDiscountT = 0 THEN
      FOR v_rec IN (SELECT * FROM contractt_manevra WHERE codcontract1 = vCodContract1 ORDER BY zile ) LOOP
        BEGIN
          SELECT sum( stingere.valoare)
          INTO vPartial
          FROM iesiri1 i1
              INNER JOIN iesiri   i          ON  i1.codies                = i.codies
              INNER JOIN general  g          ON  g.coddoc                 = i.codies    and  g.tipdoc = i.tipdoc
              INNER JOIN obligpif ostins     ON  ostins.codgeneral        = g.codgeneral
              INNER JOIN stingere            ON  stingere.codstinspif     = ostins.codobligpif
              INNER JOIN obligpif ostingator ON  stingere.codstingatorpif = ostingator.codobligpif
              INNER JOIN general  gs         ON  gs.codgeneral            = ostingator.codgeneral
              LEFT  JOIN trezor1  t1         ON  gs.coddoc                = t1.codtrezor1
              LEFT  JOIN trezor   t          ON  t1.codtrezor             = t.codtrezor and  gs.tipdoc = t.tipdoc
              LEFT  JOIN (SELECT c.datadoc, c.codcompens, 28 TIPDOC FROM compens c) comp ON  comp.codcompens = gs.coddoc and  comp.tipdoc = gs.tipdoc
          WHERE
            COALESCE( t1.datadoc, comp.datadoc) - vDataDoc BETWEEN v_rec.ziledela AND v_rec.zile and  i1.codies1 = vCodDoc1 AND (  (  gs.TipDoc IN (29, 30, 31) AND  t1.TipTranz = 1)  OR (   t1.TipTranz = 1 AND  t1.ObiectTranz = 1)  or (   t1.tiptranz = 1 and  t1.obiecttranz = 0 and  gs.tipdoc = 33) )  AND  T1.Anulat &lt;&gt; 1 AND  T.operat = 1;
        EXCEPTION WHEN others THEN
          vPartial := 0;
        END;

        IF  vPartial / vTotalDoc * 100 &lt; v_rec.procvaldoc THEN
          IF  vTotalPlata - vPartial &lt;= 0 THEN
            vTotalPlata := vTotalPlata - vPartial;
            EXIT ;
          END IF;
          vDisc := -1;
          EXIT ;
        ELSE
          vTotalPlata := vTotalPlata - vPartial;
          IF  vTotalPlata &lt;= 0 THEN
            EXIT ;
          END IF;
        END IF;
      END LOOP;

      IF  vDisc = -1 THEN
        WME_Result :=  0;
        RETURN;
      END IF;

      IF  vTotalPlata &lt;= 0 THEN
        BEGIN
          SELECT COALESCE( c1.TipDiscountT1, 0), COALESCE( c1.disct, 0) INTO vTipDiscountT1, vDiscT FROM contract1 c1 WHERE c1.codcontract1 = vCodContract1;
        EXCEPTION WHEN others THEN
          vTipDiscountT1 := -1;
        END;

        IF  vTipDiscountT1 = 0 THEN
          vDisc := vTotalLinie * vDiscT / 100;
        ELSE
          IF  vTipDiscountT1 = 1 THEN
            vDisc := vDiscT * vCant;
          END IF;
        END IF;
      END IF;
    ELSE
      IF  vTipDiscountT = 1 THEN
        FOR v_rec IN (SELECT * FROM contractt_manevra WHERE codcontract1 = vCodContract1 ORDER BY termenfix) LOOP
          BEGIN
            SELECT sum( stingere.valoare)
            INTO vPartial
            FROM iesiri1 i1
                INNER JOIN iesiri   i ON  i1.codies = i.codies
                INNER JOIN general  g ON  g.coddoc = i.codies and  g.tipdoc = i.tipdoc
                INNER JOIN obligpif ostins ON  ostins.codgeneral = g.codgeneral
                INNER JOIN stingere ON  stingere.codstinspif = ostins.codobligpif
                INNER JOIN obligpif ostingator ON  stingere.codstingatorpif = ostingator.codobligpif
                INNER JOIN general  gs ON  gs.codgeneral = ostingator.codgeneral
                LEFT  JOIN trezor1  t1 ON  gs.coddoc = t1.codtrezor1
                LEFT  JOIN trezor   t ON  t1.codtrezor = t.codtrezor and  gs.tipdoc = t.tipdoc
                LEFT  JOIN (SELECT c.datadoc, c.codcompens, 28 TIPDOC FROM compens c) comp ON  comp.codcompens = gs.coddoc and  comp.tipdoc = gs.tipdoc
            WHERE
              COALESCE( t1.datadoc, comp.datadoc) BETWEEN v_rec.termenfixdela AND v_rec.termenfix and  i1.codies1 = vCodDoc1 AND (  (  gs.TipDoc IN (29, 30, 31) AND  t1.TipTranz = 1)  OR (   t1.TipTranz = 1 AND  t1.ObiectTranz = 1)  or (   t1.tiptranz = 1 and  t1.obiecttranz = 0 and  gs.tipdoc = 33) )  AND  T1.Anulat &lt;&gt; 1 AND  T.operat = 1;
          EXCEPTION WHEN others THEN
            vPartial := 0;
          END;

          IF  vPartial / vTotalDoc * 100 &lt; v_rec.procvaldoc THEN
            IF  vTotalPlata - vPartial &lt;= 0 THEN
              vTotalPlata := vTotalPlata - vPartial;
              EXIT ;
            END IF;
            vDisc := -1;
            EXIT ;
          ELSE
            vTotalPlata := vTotalPlata - vPartial;
            IF  vTotalPlata &lt;= 0 THEN
              EXIT ;
            END IF;
          END IF;
        END LOOP;

        IF  vDisc = -1 THEN
          WME_Result :=  0;
          RETURN;
        END IF;

        IF  vTotalPlata &lt;= 0 THEN
          BEGIN
            SELECT COALESCE( c1.TipDiscountT1, 0), COALESCE( c1.disct, 0) INTO vTipDiscountT1, vDiscT FROM contract1 c1 WHERE c1.codcontract1 = vCodContract1;
          EXCEPTION WHEN others THEN
            vTipDiscountT1 := -1;
          END;

          IF  vTipDiscountT1 = 0 THEN
            vDisc := vTotalLinie * vDiscT / 100;
          ELSE
            IF  vTipDiscountT1 = 1 THEN
              vDisc := vDiscT * vCant;
            END IF;
          END IF;
        END IF;
      END IF;
    END IF;
  ELSE
    SELECT i1.codobiect, i.valdoc, i.datadoc, i1.pu * i1.cant + i1.tva, i1.cant
    INTO vCodObiect, vTotalDoc, vDataDoc, vTotalLinie, vCant
    FROM intrari1 i1 INNER JOIN intrari i ON  i.codintr = i1.codintr
    WHERE codintr1 = vCodDoc1;

    BEGIN
      SELECT sum( s.valoare)
      INTO vTotalPlata
      FROM intrari1 i1
          INNER JOIN intrari i ON  i.codintr = i1.codintr
          INNER JOIN general g ON  g.coddoc = i.codintr and  g.tipdoc = i.tipdoc
          INNER JOIN obligpif ostins ON  ostins.codgeneral = g.codgeneral
          INNER JOIN stingere s ON  s.codstinspif = ostins.codobligpif
      WHERE
         i1.codintr1 = vCodDoc1;
    EXCEPTION WHEN others THEN
      vTotalPlata := 0;
    END;

    IF  vTotalDoc &lt;&gt; vTotalPlata THEN
      WME_Result :=  0;
      RETURN;
    END IF;

    BEGIN
      SELECT COALESCE( c1.TipDiscountT, 0) INTO vTipDiscountT FROM contract1 c1 WHERE c1.codcontract1 = vCodContract1;
    EXCEPTION WHEN others THEN
      vTipDiscountT := -1;
    END;

    IF  vTipDiscountT = 0 THEN
      FOR v_rec IN (SELECT * FROM contractt_manevra WHERE codcontract1 = vCodContract1 ORDER BY zile) LOOP
        BEGIN
          SELECT sum( stingere.valoare)
          INTO vPartial
          FROM intrari1 i1
              INNER JOIN intrari i ON  i1.codintr = i.codintr
              INNER JOIN general g ON  g.coddoc = i.codintr and  g.tipdoc = i.tipdoc
              INNER JOIN obligpif ostins ON  ostins.codgeneral = g.codgeneral
              INNER JOIN stingere ON  stingere.codstinspif = ostins.codobligpif
              INNER JOIN obligpif ostingator ON  stingere.codstingatorpif = ostingator.codobligpif
              INNER JOIN general gs ON  gs.codgeneral = ostingator.codgeneral
              LEFT  JOIN trezor1 t1 ON  gs.coddoc = t1.codtrezor1
              LEFT  JOIN trezor t ON  t1.codtrezor = t.codtrezor and  gs.tipdoc = t.tipdoc
              LEFT  JOIN (SELECT c.datadoc, c.codcompens, 28 TIPDOC FROM compens c) comp ON  comp.codcompens = gs.coddoc and  comp.tipdoc = gs.tipdoc
          WHERE
            COALESCE( t1.datadoc, comp.datadoc) - vDataDoc BETWEEN v_rec.ziledela AND v_rec.zile and  i1.codintr1 = vCodDoc1 AND (  (  G.TipDoc IN (29, 30, 31) AND  t1.TipTranz = 0)  OR (   t1.TipTranz = 0 AND  t1.ObiectTranz = 1) )  AND  T1.Anulat &lt;&gt; 1 AND  T.operat = 1;
        EXCEPTION WHEN others THEN
          vPartial := 0;
        END;

        IF  vPartial / vTotalDoc * 100 &lt; v_rec.procvaldoc THEN
          IF  vTotalPlata - vPartial &lt;= 0 THEN
            vTotalPlata := vTotalPlata - vPartial;
            EXIT ;
          END IF;
          vDisc := -1;
          EXIT ;
        ELSE
          vTotalPlata := vTotalPlata - vPartial;
          IF  vTotalPlata &lt;= 0 THEN
            EXIT ;
          END IF;
        END IF;
      END LOOP;

      IF  vDisc = -1 THEN
        WME_Result :=  0;
        RETURN;
      END IF;

      IF  vTotalPlata &lt;= 0 THEN
        BEGIN
          SELECT COALESCE( c1.TipDiscountT1, 0), COALESCE( c1.disct, 0) INTO vTipDiscountT1, vDiscT FROM contract1 c1 WHERE c1.codcontract1 = vCodContract1;
        EXCEPTION WHEN others THEN
          vTipDiscountT1 := -1;
        END;

        IF  vTipDiscountT1 = 0 THEN
          vDisc := vTotalLinie * vDiscT / 100;
        ELSE
          IF  vTipDiscountT1 = 1 THEN
            vDisc := vDiscT * vCant;
          END IF;
        END IF;
      END IF;
    ELSE
      IF  vTipDiscountT = 1 THEN
        FOR v_rec IN (SELECT * FROM contractt_manevra WHERE codcontract1 = vCodContract1 ORDER BY termenfix) LOOP
          BEGIN
            SELECT sum( stingere.valoare)
            INTO vPartial
            FROM iesiri1 i1
                INNER JOIN iesiri i ON  i1.codies = i.codies
                INNER JOIN general g ON  g.coddoc = i.codies and  g.tipdoc = i.tipdoc
                INNER JOIN obligpif ostins ON  ostins.codgeneral = g.codgeneral
                INNER JOIN stingere ON  stingere.codstinspif = ostins.codobligpif
                INNER JOIN obligpif ostingator ON  stingere.codstingatorpif = ostingator.codobligpif
                INNER JOIN general gs ON  gs.codgeneral = ostingator.codgeneral
                LEFT  JOIN trezor1 t1 ON  gs.coddoc = t1.codtrezor1
                LEFT  JOIN trezor t ON  t1.codtrezor = t.codtrezor and  gs.tipdoc = t.tipdoc
                LEFT  JOIN (SELECT c.datadoc, c.codcompens, 28 TIPDOC FROM compens c) comp ON  comp.codcompens = gs.coddoc and  comp.tipdoc = gs.tipdoc
            WHERE
              COALESCE( t1.datadoc, comp.datadoc) BETWEEN v_rec.termenfixdela AND v_rec.termenfix and  i1.codies1 = vCodDoc1 AND (  (  G.TipDoc IN (29, 30, 31) AND  t1.TipTranz = 0)  OR (   t1.TipTranz = 0 AND  t1.ObiectTranz = 1) )  AND  T1.Anulat &lt;&gt; 1 AND  T.operat = 1;
          EXCEPTION WHEN others THEN
            vPartial := 0;
          END;

          IF  vPartial / vTotalDoc * 100 &lt; v_rec.procvaldoc THEN
            IF  vTotalPlata - vPartial &lt;= 0 THEN
              vTotalPlata := vTotalPlata - vPartial;
              EXIT ;
            END IF;
            vDisc := -1;
            EXIT ;
          ELSE
            vTotalPlata := vTotalPlata - vPartial;
            IF  vTotalPlata &lt;= 0 THEN
              EXIT ;
            END IF;
          END IF;
        END LOOP;

        IF  vDisc = -1 THEN
          WME_Result :=  0;
          RETURN;
        END IF;

        IF  vTotalPlata &lt;= 0 THEN
          BEGIN
            SELECT COALESCE( c1.TipDiscountT1, 0), COALESCE( c1.disct, 0) INTO vTipDiscountT1, vDiscT FROM contract1 c1 WHERE c1.codcontract1 = vCodContract1;
          EXCEPTION WHEN others THEN
            vTipDiscountT1 := -1;
          END;

          IF  vTipDiscountT1 = 0 THEN
            vDisc := vTotalLinie * vDiscT / 100;
          ELSE
            IF  vTipDiscountT1 = 1 THEN
              vDisc := vDiscT * vCant;
            END IF;
          END IF;
        END IF;
      END IF;
    END IF;
  END IF;

  WME_Result :=  vDisc;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getdiscvolum</obj_name>
  <obj_hashval>cf6dcbace26beccfd2bbde3b3f8c7906</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getdiscvolum(INOUT wme_result numeric, INOUT acoddoc numeric, INOUT acodcontract numeric, INOUT atip numeric, INOUT acodncredit numeric, INOUT pretbrut numeric DEFAULT 0, INOUT acurs numeric DEFAULT 1)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  vDisc     double precision;
  vProcDisc double precision;
  vValDisc  double precision;
  vTipDisc  numeric;
  vValDoc   double precision;
  vTotal    double precision;
  vCurs     NUMERIC(10,7);
BEGIN
  --Florin 20.04.2023 - fixat 57990
  --Florin 28.06.2022 - fixat 54705
  if aCurs = 0 then vCurs := 1; else vCurs := aCurs; end if;
  IF aCodContract = 0 THEN
    WME_Result := 0;
    RETURN;
  END IF;

  vDisc := 0;
  BEGIN
    SELECT COALESCE (TipTargetV, 0) INTO STRICT vTipDisc FROM contract WHERE codcontract = aCodContract;
  EXCEPTION
  WHEN others THEN
    vTipDisc := 0;
  END;
  IF aTip = 1 THEN
    IF vTipDisc = 0 THEN
      BEGIN
        SELECT valoare INTO vTotal
        FROM manevra_notecredit
        WHERE
          codobiect = 0
          and UserID = (SELECT pkg_globals_GETUSERID.WME_RESULT FROM pkg_globals_GETUSERID (NULL,NULL))
          and CodNCredit = aCodNCredit
         limit 1;
      EXCEPTION
      WHEN others THEN
        vTotal := 0;
      END;

      IF vTotal = 0 THEN
        WME_Result := 0;
        RETURN;
      END IF;

      SELECT sum (COALESCE (a.valm, 0))
      INTO vValDoc
      FROM (SELECT SUM (
                        CASE
                          WHEN COALESCE (PretBrut, 0) &lt;&gt; 1 THEN
                            CASE
                              WHEN i.tipdoc = 21 THEN (I1.Cant * i1.pretorig - I1.TVA) * COALESCE (I1.CoefDiscMaj, 1)
                              ELSE i1.cant * i1.pretorig * COALESCE (I1.CoefDiscMaj, 1)
                            END
                          ELSE
                            CASE
                              WHEN i.tipdoc = 21 THEN I1.Cant * i1.pretorig - I1.TVA
                              ELSE i1.cant                * i1.pretorig
                            END
                        END) VALM
            FROM IESIRI I INNER JOIN iesiri1 I1 ON i.codies = i1.codies
            WHERE
              i1.codobiect &gt; 0
              AND I1.CodObiect::varchar NOT IN (COALESCE ( (fnc_GetValConstantalucru ('ArtDiscAcTer')), '0') ,
                                       COALESCE ( (fnc_GetValConstantalucru ('ArtDiscAcVol')), '0') ,
                                       COALESCE ( (fnc_GetValConstantalucru ('ArtDiscAcCant')), '0') ,
                                       COALESCE ( (fnc_GetValConstantalucru ('ArtPenAcTer')), '0')
                                      )
              and i.codies = aCodDoc) a;

      BEGIN
        SELECT COALESCE (cv.Discount, 0) INTO vProcDisc
        FROM contractv cv
        WHERE
          cv.codcontract = aCodContract
          and COALESCE (cv.codcontract1, 0) = 0
          and cv.suma = (SELECT max (suma) FROM contractv CCv WHERE CCv.Codcontract = aCodContract and suma &lt;= vTotal and COALESCE (ccv.codcontract1, 0) = 0);
      EXCEPTION
      WHEN others THEN
        vProcDisc := 0;
      END;

      IF vProcDisc = 0 THEN
        BEGIN
          SELECT COALESCE (cv.ValDiscount, 0) INTO vValDisc
          FROM contractv cv
          WHERE
            cv.codcontract = aCodContract
            and COALESCE (cv.codcontract1, 0) = 0
            and cv.suma = (SELECT max (suma) FROM contractv CCv WHERE CCv.Codcontract = aCodContract and suma &lt;= vTotal and COALESCE (ccv.codcontract1, 0) = 0);
        EXCEPTION
        WHEN others THEN
          vValDisc := 0;
        END;
      END IF;

      IF vProcDisc &lt;&gt; 0 THEN
        vDisc := vValDoc * vProcDisc / 100;
      ELSE
        vDisc := vValDoc / vTotal * vValDisc * vCurs;
      END IF;
    ELSE
      IF vTipDisc = 1 THEN
        BEGIN
          SELECT valoare INTO vTotal
          FROM manevra_notecredit
          WHERE
            codobiect = 0
            and UserID = (SELECT pkg_globals_GETUSERID.WME_RESULT FROM pkg_globals_GETUSERID (NULL,NULL))
            and CodNCredit = aCodNcredit
           limit 1;
        EXCEPTION
        WHEN others THEN
          vTotal := 0;
        END;

        IF vTotal = 0 THEN
          WME_Result := 0;
          RETURN;
        END IF;

        SELECT sum (COALESCE (a.valm, 0)) INTO vValDoc
        FROM (SELECT SUM (
                          CASE
                            WHEN COALESCE (PretBrut, 0) &lt;&gt; 1 THEN
                              CASE
                                WHEN i.tipdoc = 21 THEN (I1.Cant * i1.pretorig - I1.TVA) * COALESCE (I1.CoefDiscMaj, 1)
                                ELSE i1.cant * i1.pretorig * COALESCE (I1.CoefDiscMaj, 1)
                              END
                            ELSE
                              CASE
                                WHEN i.tipdoc = 21 THEN I1.Cant * i1.pretorig - I1.TVA
                                ELSE i1.cant                * i1.pretorig
                              END
                          END) VALM
              FROM IESIRI              I
                  INNER JOIN iesiri1   I1 ON i.codies = i1.codies
                  INNER JOIN contract1 c1 ON c1.codcontract1 = (SELECT pkg_notecredit_GetCodContract1.WME_RESULT
                                                                FROM pkg_notecredit_GetCodContract1 (NULL, i1.codobiect, i.datadoc, aCodContract))
              WHERE
                i1.codobiect &gt; 0
                AND I1.CodObiect::varchar NOT IN (COALESCE ( (fnc_GetValConstantalucru ('ArtDiscAcTer' )), '0') ,
                                         COALESCE ( (fnc_GetValConstantalucru ('ArtDiscAcVol' )), '0') ,
                                         COALESCE ( (fnc_GetValConstantalucru ('ArtDiscAcCant')), '0') ,
                                         COALESCE ( (fnc_GetValConstantalucru ('ArtPenAcTer'  )), '0')
                                         )
                and i.codies = aCodDoc
                and c1.codcontract = aCodContract) a;

        BEGIN
          SELECT COALESCE (cv.Discount, 0) INTO vProcDisc
          FROM contractv cv
          WHERE
            cv.codcontract = aCodContract
            and COALESCE (cv.codcontract1, 0) = 0
            and cv.suma = (SELECT max (suma) FROM contractv CCv WHERE CCv.Codcontract = aCodContract and suma &lt;= vTotal and COALESCE (ccv.codcontract1, 0) = 0);
        EXCEPTION
        WHEN others THEN
          vProcDisc := 0;
        END;

        IF vProcDisc = 0 THEN
          BEGIN
            SELECT COALESCE (cv.ValDiscount, 0) INTO vValDisc
            FROM contractv cv
            WHERE
              cv.codcontract = aCodContract
              and COALESCE (cv.codcontract1, 0) = 0
              and cv.suma = (SELECT max (suma) FROM contractv CCv WHERE CCv.Codcontract = aCodContract and suma &lt;= vTotal and COALESCE (ccv.codcontract1, 0) = 0);
          EXCEPTION
          WHEN others THEN
            vValDisc := 0;
          END;
        END IF;

        IF vProcDisc &lt;&gt; 0 THEN
          vDisc := vValDoc * vProcDisc / 100;
        ELSE
          vDisc := vValDoc / vTotal * vValDisc * vCurs;
        END IF;
      else
        FOR v_rec IN (SELECT a.codobiect, a.codcontract1, sum (a.valm) VALM, tmp.valoare VALTOT
                      FROM (SELECT I1.CodObiect, c1.codcontract1,
                                   SUM (
                                        CASE
                                          WHEN COALESCE (PretBrut, 0) &lt;&gt; 1 THEN
                                            CASE
                                              WHEN i.tipdoc = 21 THEN (I1.Cant * i1.pretorig - I1.TVA) * COALESCE (I1.CoefDiscMaj, 1)
                                                ELSE i1.cant * i1.pretorig * COALESCE (I1.CoefDiscMaj, 1)
                                            END
                                          ELSE
                                            CASE
                                              WHEN i.tipdoc = 21 THEN I1.Cant * i1.pretorig - I1.TVA
                                              ELSE i1.cant                * i1.pretorig
                                            END
                                        END) VALM
                            FROM IESIRI I
                                INNER JOIN iesiri1   I1 ON i.codies = i1.codies
                                INNER JOIN contract1 c1 ON c1.codcontract1 = (SELECT pkg_notecredit_GetCodContract1.WME_RESULT
                                                                              FROM pkg_notecredit_GetCodContract1 (NULL, i1.codobiect, i.datadoc, aCodContract))
                            WHERE i1.codobiect &gt; 0
                              AND I1.CodObiect::varchar NOT IN (COALESCE ( (fnc_GetValConstantalucru ('ArtDiscAcTer' )), '0') ,
                                                       COALESCE ( (fnc_GetValConstantalucru ('ArtDiscAcVol' )), '0') ,
                                                       COALESCE ( (fnc_GetValConstantalucru ('ArtDiscAcCant')), '0') ,
                                                       COALESCE ( (fnc_GetValConstantalucru ('ArtPenAc'     )), '0'))
                              and i1.codies1 = aCodDoc
                              and c1.codcontract = aCodContract
                            GROUP BY I1.CodObiect, c1.codcontract1
                           ) a
                        INNER JOIN manevra_notecredit tmp ON a.codobiect = tmp.codobiect and a.codcontract1 = tmp.codcontract1
                                                             and tmp.UserID = (SELECT pkg_globals_GETUSERID.WME_RESULT FROM pkg_globals_GETUSERID (NULL,NULL)) and tmp.codncredit = aCodNCredit
                      WHERE tmp.valoare &lt;&gt; 0
                      GROUP BY a.codobiect, a.codcontract1, tmp.valoare)
        loop
          BEGIN
            SELECT COALESCE (cv.Discount, 0) into STRICT vProcDisc
            FROM contractv cv INNER JOIN contract1 c1 ON cv.codcontract1 = c1.codcontract1
            WHERE
              cv.codcontract = aCodContract
              and c1.codcontract1 = v_rec.codcontract1
              and cv.suma = (SELECT max (suma) FROM contractv CCv WHERE CCv.Codcontract = aCodContract and suma &lt;= v_rec.valtot and ccv.codcontract1 = c1.codcontract1);
          EXCEPTION
          WHEN others THEN
            vProcDisc := 0;
          END;

          IF vProcDisc = 0 then
            BEGIN
              SELECT COALESCE (cv.ValDiscount, 0) into STRICT vValDisc
              FROM contractv cv INNER JOIN contract1 c1 ON cv.codcontract1 = c1.codcontract1
              WHERE
                cv.codcontract = aCodContract
                and c1.codcontract1 = v_rec.codcontract1
                and cv.suma = (SELECT max (suma) FROM contractv CCv WHERE CCv.Codcontract = aCodContract and suma &lt;= v_rec.valtot and ccv.codcontract1 = c1.codcontract1);
            EXCEPTION
            WHEN others THEN
              vValDisc := 0;
            END;
          END IF;

          IF vProcDisc &lt;&gt; 0 THEN
            vDisc := vDisc + v_Rec.ValM * vProcDisc / 100;
          ELSE
            vDisc := vDisc + v_Rec.ValM / v_Rec.valtot * vValDisc * vCurs;
          END IF;
        END LOOP;
      END IF;
    END IF;
  ELSE
    IF vTipDisc = 0 THEN
      BEGIN
        SELECT valoare
        INTO
          vTotal
        FROM manevra_notecredit
        WHERE
          codobiect = 0
          and UserID = (SELECT pkg_globals_GETUSERID.WME_RESULT FROM pkg_globals_GETUSERID (NULL,NULL))
          and codncredit = aCodNCredit
         limit 1;
      EXCEPTION
      WHEN others THEN
        vTotal := 0;
      END;

      IF vTotal = 0 THEN
        WME_Result := 0;
        RETURN;
      END IF;

      SELECT sum (COALESCE (a.valm, 0))
      INTO
        vValDoc
      FROM (SELECT SUM (
                            CASE
                              WHEN COALESCE (PretBrut, 0) &lt;&gt; 1 THEN I1.Cant * I1.PretOrig * COALESCE (I1.CoefDiscMaj, 1)
                              ELSE I1.Cant                              * I1.PretOrig
                            END) VALM
            FROM Intrari I INNER JOIN intrari1 I1 ON i.codintr = i1.codintr
            WHERE
              i1.codobiect &gt; 0
              AND I1.CodObiect::varchar not IN (COALESCE ( (fnc_GetValConstantalucru ('ArtDiscPrimVol' )), '0') ,
                                       COALESCE ( (fnc_GetValConstantalucru ('ArtDiscPrimCant' )), '0') ,
                                       fnc_GetValConstantalucru ('ArtPenPrimTer'))
              AND INSTR(fnc_GetValConstantalucru ('ArtPenPrimTer'), (I1.CODOBIECT)::varchar) = 0
              and i.codintr = aCodDoc) a;
      BEGIN
        SELECT COALESCE (cv.Discount, 0)
        INTO
          vProcDisc
        FROM contractv cv
        WHERE
          cv.codcontract = aCodContract
          and COALESCE (cv.codcontract1, 0) = 0
          and cv.suma = (SELECT max (suma) FROM contractv CCv WHERE CCv.Codcontract = aCodContract and suma &lt;= vTotal and COALESCE (ccv.codcontract1, 0) = 0);
      EXCEPTION
      WHEN others THEN
        vProcDisc := 0;
      END;

      IF vProcDisc = 0 THEN
        BEGIN
          SELECT COALESCE (cv.ValDiscount, 0)
          INTO
            vValDisc
          FROM contractv cv
          WHERE
            cv.codcontract = aCodContract
            and COALESCE (cv.codcontract1, 0) = 0
            and cv.suma = (SELECT max (suma) FROM contractv CCv WHERE CCv.Codcontract = aCodContract and suma &lt;= vTotal and COALESCE (ccv.codcontract1, 0) = 0);
        EXCEPTION
        WHEN others THEN
          vValDisc := 0;
        END;
      END IF;

      IF vProcDisc &lt;&gt; 0 THEN
        vDisc := vValDoc * vProcDisc / 100;
      ELSE
        vDisc := vValDoc / vTotal * vValDisc * vCurs;
      END IF;
    ELSE
      IF vTipDisc = 1 THEN
        BEGIN
          SELECT valoare
          INTO
            vTotal
          FROM manevra_notecredit
          WHERE
            codobiect = 0
            and UserID = (SELECT pkg_globals_GETUSERID.WME_RESULT FROM pkg_globals_GETUSERID (NULL,NULL))
            and CodNCredit = aCodNCredit
           limit 1;
        EXCEPTION
        WHEN others THEN
          vTotal := 0;
        END;

        IF vTotal = 0 THEN
          WME_Result := 0;
          RETURN;
        END IF;
        SELECT sum (COALESCE (a.valm, 0))
        INTO
          vValDoc
        FROM (SELECT SUM (
                          CASE
                            WHEN COALESCE (PretBrut, 0) &lt;&gt; 1 THEN I1.Cant * I1.PretOrig * COALESCE (I1.CoefDiscMaj, 1)
                            ELSE I1.Cant                              * I1.PretOrig
                          END) VALM
              FROM Intrari         I
                  INNER JOIN intrari1  I1 ON i.codintr = i1.codintr
                  INNER JOIN contract1 c1 ON c1.codcontract1 = (SELECT pkg_notecredit_GetCodContract1.WME_RESULT
                                                                FROM pkg_notecredit_GetCodContract1 (NULL, i1.codobiect, i.datadoc, aCodContract))
              WHERE
                i1.codobiect &gt; 0
                AND I1.CodObiect::varchar NOT IN (COALESCE ( (fnc_GetValConstantalucru ('ArtDiscPrimVol' )), '0') ,
                                         COALESCE ( (fnc_GetValConstantalucru ('ArtDiscPrimCant' )), '0') ,
                                         fnc_GetValConstantalucru ('ArtPenPrimTer'))
                AND INSTR(fnc_GetValConstantalucru ('ArtPenPrimTer'  ), (I1.CODOBIECT)::varchar) = 0
                and i.codintr = aCodDoc
                and c1.codcontract = aCodContract) a;

        BEGIN
          SELECT COALESCE (cv.Discount, 0)
          INTO
            vProcDisc
          FROM contractv cv
          WHERE
            cv.codcontract = aCodContract
            and COALESCE (cv.codcontract1, 0) = 0
            and cv.suma = (SELECT max (suma) FROM contractv CCv WHERE CCv.Codcontract = aCodContract and suma &lt;= vTotal and COALESCE (ccv.codcontract1, 0) = 0);
        EXCEPTION
        WHEN others THEN
          vProcDisc := 0;
        END;

        IF vProcDisc = 0 THEN
          BEGIN
            SELECT COALESCE (cv.ValDiscount, 0)
            INTO
              vValDisc
            FROM contractv cv
            WHERE
              cv.codcontract = aCodContract
              and COALESCE (cv.codcontract1, 0) = 0
              and cv.suma = (SELECT max (suma) FROM contractv CCv WHERE CCv.Codcontract = aCodContract and suma &lt;= vTotal and COALESCE (ccv.codcontract1, 0) = 0);
          EXCEPTION
          WHEN others THEN
            vValDisc := 0;
          END;
        END IF;

        IF vProcDisc &lt;&gt; 0 THEN
          vDisc := vValDoc * vProcDisc / 100;
        ELSE
          vDisc := vValDoc / vTotal * vValDisc * vCurs;
        END IF;
      ELSE
        FOR v_rec IN (SELECT a.codobiect, a.codcontract1, sum (a.valm) VALM, tmp.valoare VALTOT
                      FROM (SELECT I1.CodObiect, c1.codcontract1,
                                   SUM (
                                        CASE
                                          WHEN COALESCE (PretBrut, 0) &lt;&gt; 1 THEN I1.Cant * I1.PretOrig * COALESCE (I1.CoefDiscMaj, 1)
                                          ELSE I1.Cant * I1.PretOrig
                                        END) VALM
                            FROM Intrari             I
                                INNER JOIN intrari1  I1 ON i.codintr = i1.codintr
                                INNER JOIN contract1 c1 ON c1.codcontract1 = (SELECT pkg_notecredit_GetCodContract1.WME_RESULT
                                                                              FROM pkg_notecredit_GetCodContract1 (NULL, i1.codobiect, i.datadoc, aCodContract))
                            WHERE i1.codobiect &gt; 0
                              AND I1.CodObiect::varchar not IN (COALESCE ( (fnc_GetValConstantalucru ('ArtDiscPrimVol' )), '0') ,
                                                       COALESCE ( (fnc_GetValConstantalucru ('ArtDiscPrimCant' )), '0') ,
                                                       fnc_GetValConstantalucru ('ArtPenPrimTer'))
                              AND INSTR(fnc_GetValConstantalucru('ArtPenPrimTer'  ), (I1.CODOBIECT)::varchar) = 0
                              and i1.codintr1 = aCodDoc
                              and c1.codcontract = aCodContract
                            GROUP BY I1.CodObiect, c1.codcontract1
                           ) a
                        LEFT JOIN manevra_notecredit tmp ON a.codobiect = tmp.codobiect and a.codcontract1 = tmp.codcontract1
                                                            and UserID = (SELECT pkg_globals_GETUSERID.WME_RESULT FROM pkg_globals_GETUSERID (NULL,NULL))
                                                            and tmp.codncredit = aCodNCredit
                      GROUP BY a.codobiect, a.codcontract1, tmp.valoare)
        LOOP
          BEGIN
            SELECT COALESCE (cv.Discount, 0)
            INTO
              vProcDisc
            FROM contractv           cv
              INNER JOIN contract1 c1 ON cv.codcontract1 = c1.codcontract1
            WHERE
              cv.codcontract = aCodContract
              and c1.codcontract1 = v_rec.codcontract1
              and cv.suma = (SELECT max (suma) FROM contractv CCv WHERE CCv.Codcontract = aCodContract and suma &lt;= v_rec.valtot and ccv.codcontract1 = c1.codcontract1);
          EXCEPTION
          WHEN others THEN
            vProcDisc := 0;
          END;

          IF vProcDisc = 0 THEN
            BEGIN
              SELECT COALESCE (cv.ValDiscount, 0)
              INTO
                vValDisc
              FROM contractv cv INNER JOIN contract1 c1 ON cv.codcontract1 = c1.codcontract1
              WHERE
                cv.codcontract = aCodContract
                and c1.codcontract1 = v_rec.codcontract1
                and cv.suma = (SELECT max (suma) FROM contractv CCv WHERE CCv.Codcontract = aCodContract and suma &lt;= v_rec.valtot and ccv.codcontract1 = c1.codcontract1);
            EXCEPTION
            WHEN others THEN
              vValDisc := 0;
            END;
          END IF;

          IF vProcDisc &lt;&gt; 0 THEN
            vDisc := vDisc + v_Rec.ValM * vProcDisc / 100;
          ELSE
            vDisc := vDisc + v_Rec.ValM / v_Rec.valtot * vValDisc * vCurs;
          END IF;
        END LOOP;
      END IF;
    END IF;
  END IF;

  WME_Result := vDisc;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_gettnccadouri</obj_name>
  <obj_hashval>facd2c9f4da07363a7cd39039701f6c3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_gettnccadouri(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.tncCadouri', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 4;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_sp_gotorecord</obj_name>
  <obj_hashval>a9a699f65efd1e5884c81a76068a38f2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  V_REC RECORD;
  vDataStart       date;
  vDataStop        date;
  vTipDoc          numeric;
  vCodContract     numeric := 0;
  vCount           numeric;
  vCount1          numeric;
  vCodPart         numeric;
  vTipDiscV        numeric;
  vVolumPeArticole numeric;
  vPretBrutC       numeric;
  vPretBrutV       numeric;
  vTrimestriala    numeric;
  vLuna            numeric;
  vTrimestru       numeric;
  vAreCorectii     numeric;
  vPrevizionare    numeric;
  vIesiriPeVolum   numeric;
  vValOrig         numeric;
  vTotCant         numeric(20,7);
  vCurs            NUMERIC(20,7);
BEGIN
  --Florin 12.02.2025 - sinc. Oracle
  --Florin 10.12.2024 - fixat 64239
  --Florin 21.11.2024 - sinc. Oracle
  --Stef 30.01.2024
  perform pkg_notecredit_setct_monitor('MON_47');
  perform PKG_STOC_GENERARE_FACTURI_MAKE_CONFIG_LUNA();
  perform set_config ('PKG_NOTECREDIT.KArtDiscAcTer'      , coalesce ( (fnc_GetValConstantalucru ('ArtDiscAcTer'      )) , '0') ::varchar, false);
  perform set_config ('PKG_NOTECREDIT.KArtDiscAcVol'      , coalesce ( (fnc_GetValConstantalucru ('ArtDiscAcVol'      )) , '0') ::varchar, false);
  perform set_config ('PKG_NOTECREDIT.KArtDiscAcCant'     , coalesce ( (fnc_GetValConstantalucru ('ArtDiscAcCant'     )) , '0') ::varchar, false);
  perform set_config ('PKG_NOTECREDIT.KArtPenAcTer'       , coalesce ( (fnc_GetValConstantalucru ('ArtPenAc'          )) , '0') ::varchar, false);
  perform set_config ('PKG_NOTECREDIT.KArtDiscOffInvoiceC', coalesce ( (fnc_GetValConstantalucru ('ArtDiscOffInvoiceC')) , '0') ::varchar, false);
  perform set_config ('PKG_NOTECREDIT.KArtDiscPrimTer'    , fnc_GetValConstantalucru ('ArtDiscPrimTer'    ), false);
  perform set_config ('PKG_NOTECREDIT.KArtDiscPrimVol'    , coalesce ( (fnc_GetValConstantalucru ('ArtDiscPrimVol'    )) , '0') ::varchar, false);
  perform set_config ('PKG_NOTECREDIT.KArtDiscPrimCant'   , coalesce ( (fnc_GetValConstantalucru ('ArtDiscPrimCant'   )) , '0') ::varchar, false);
  perform set_config ('PKG_NOTECREDIT.KArtPenPrimTer'     , coalesce ( (fnc_GetValConstantalucru ('ArtPenPrim'        )) , '0') ::varchar, false);
  perform set_config ('PKG_NOTECREDIT.KArtDiscOffInvoiceF', coalesce ( (fnc_GetValConstantalucru ('ArtDiscOffInvoiceF')) , '0') ::varchar, false);

  perform set_config ('PKG_NOTECREDIT.tncTermen'     , '1', false);
  perform set_config ('PKG_NOTECREDIT.tncVolum'      , '2', false);
  perform set_config ('PKG_NOTECREDIT.tncCantitate'  , '3', false);
  perform set_config ('PKG_NOTECREDIT.tncCadouri'    , '4', false);
  perform set_config ('PKG_NOTECREDIT.tncProvizioane', '5', false);
  perform set_config ('PKG_NOTECREDIT.tncPenalizari' , '6', false);

  if RecId &gt; 0 then
    insert into TMP_NOTECREDIT (
        CodNCredit,
        CodContract2,
        CodPart,
        TipDoc,
        Subunitatea,
        DataStart,
        DataStop,
        CODCONTV,
        CODCONTT,
        CODCONTC,
        CODCONTP,
        DataStartD,
        DataStopD,
        DataFact,
        Contract,
        An,
        Luna,
        TipARticol,
        Obs,
        CodContract,
        CodMoneda,
        VolumPeArticole,
        CODCONTZ,
        PretBrutC,
        PretBrutV,
        CodCarnet,
        TipDiscV,
        Trimestriala,
        Corectie,
        COdNCCorectie,
        PrefixDoc,
        CarnetDoc,
        NrDoc,
        SeriaDoc,
        AreCarnetDoc,
        AreCorectii,
        Previzionare,
        IesiriPeVolum,
        Curs,
        Inchisa,
        ValOrigTer, CODANALIZA)
    select NC.CodNCredit,
      NC.CodContract2,
      NC.CodPart,
      NC.TipDoc,
      NC.Subunitatea,
      NC.Datastart,
      NC.DataStop,
      nc.CODCONTV,
      nc.CODCONTT,
      nc.CODCONTC,
      nc.CODCONTP,
      NC.DataStart,
      NC.DataStop,
      current_timestamp,
      case
        when coalesce (NC.CodContract2, coalesce (NC.CodContract, 0)) = 0 then '...fara...'
        else
          case
            when coalesce (NC.CodContract, 0) = 0
              then coalesce (C.Nrdoc::varchar, '') || '/'|| coalesce (to_char (C.DataStart  , 'DD.MM.YYYY') , '') || '-' || coalesce (to_char (C.DataStop  , 'DD.MM.YYYY') , '')
            else coalesce (CNC.Nrdoc::varchar, '') || '/'|| coalesce (to_char (CNC.DataStart, 'DD.MM.YYYY') , '') || '-' || coalesce (to_char (CNC.DataStop, 'DD.MM.YYYY') , '')
          end
      end ,
      NC.An,
      NC.Luna,
      NC.TipArticol,
      NC.Obs,
      CASE when coalesce (nc.codcontract2, 0) = 0 then NC.CodContract else C.Codcontract end ,
      coalesce (NC.CodMoneda, C.Moneda) ,
      coalesce (NC.VOLUMPEARTICOLE, 0) ,
      nc.CODCONTZ,
      coalesce (nc.pretbrutc, 0) ,
      coalesce (nc.pretbrutv, 0) ,
      nc.codcarnet,
      CASE WHEN CASE when coalesce (NC.CodContract2, 0) = 0 then coalesce (NC.CodContract, 0) else NC.CodContract2 end = 0
             THEN CASE when coalesce (NC.Volumpearticole, 0) = 0 then 3 else 4 end
           ELSE CASE when coalesce (NC.CodContract, 0) = 0 then coalesce (C.TIPTARGETV, 0) else coalesce (CNC.TIPTARGETV, 0) end
      END ,
      coalesce (NC.Trimestriala, 0) ,
      NC.Corectie,
      NC.CodNCCorectie,
      NC.PrefixDoc,
      NC.CarnetDoc,
      NC.NrDoc,
      NC.SeriaDoc,
      CASE when coalesce (NC.CARNETDOC, 0) = 0 then 0 else 1 end ,
      (select count(*) from notecredit WHERE codnccorectie = recid) ,
      NC.Previzionare,
      NC.IesiriPeVolum,
      NC.Curs,
      NC.Inchisa,
      coalesce(NC.ValOrigTer, 0), NC.CODANALIZA
    from NOTECREDIT       NC
      left join CONTRACT2 C2  on NC.CODCONTRACT2 = C2.CODCONTRACT2
      left join CONTRACT  C   on C2.CODCONTRACT  = C.CODCONTRACT
      left join CONTRACT  CNC on CNC.Codcontract = nc.codcontract
    where
      CodNCredit = RecId;

    select coalesce (VolumPeArticole, 0) INTO vVolumPeArticole from tmp_notecredit;
    select coalesce (AreCorectii, 0)     INTO vAreCorectii     from tmp_notecredit;
    select coalesce (Trimestriala, 0)    INTO vTrimestriala    from tmp_notecredit;
    select coalesce (IesiriPeVolum, 0)   INTO vIesiriPeVolum   from tmp_notecredit;
    select coalesce(ValOrigTer, CODANALIZA,0) into vValOrig    from tmp_notecredit;
    select coalesce(curs,1) into vCurs from tmp_notecredit;
    if vCurs = 0 then vCurs := 1; end if;

    if vTrimestriala = 1 then
      select extract (month from datastop) INTO vLuna from tmp_notecredit;

      vTrimestru := 0;
      if vLuna in (1, 2, 3) then
        vTrimestru := 1;
      end if;
      if vLuna in (4, 5, 6) then
        vTrimestru := 2;
      end if;
      if vLuna in (7, 8, 9) then
        vTrimestru := 3;
      end if;
      if vLuna in (10, 11, 12) then
        vTrimestru := 4;
      end if;
    end if;

    select datastart INTO vDataStart from tmp_notecredit;
    select datastop  INTO vDataStop  from tmp_notecredit;
    select TipDoc    INTO vTipDoc    from tmp_notecredit;

    select coalesce (c.codcontract, 0) , coalesce (nc.codpart, 0) , coalesce (c.tiptargetv, 0)
    INTO vCodContract, vCodPart, vTipDiscV
    from notecredit  nc left join contract c on nc.codcontract = c.codcontract
    WHERE nc.codncredit = RecId;

    insert  into TMP_NOTECREDIT1 (
        CodNCredit1,
        CodNCredit,
        TipOper,
        Valoare,
        CodObligStins,
        CodDoc,
        TipDoc,
        CodObligStingator,
        Obs,
        ValDif,
        Valoareold,
        CODCLASEDISC,
        CODNCREDIT1ORIG,
        PREVIZIONAT,
        CODDISCOUNT,
        VALDOC,
        VALLEI,
        TIP,
        PROCTVA,
        OBSNAV,
        CODANALIZANOD,
        CODCENTRU)
    select CodNCredit1,
      CodNCredit,
      TipOper,
      Valoare,
      CodObligStins,
      CodDoc,
      TipDoc,
      CodObligStingator,
      Obs,
      ValDif,
      Valoareold,
      CODCLASEDISC,
      CODNCREDIT1ORIG,
      PREVIZIONAT,
      CODDISCOUNT,
      VALDOC,
      VALLEI,
      TIP,
      coalesce (PROCTVA, 24) ,
      OBSNAV,
      CODANALIZANOD,
      CODCENTRU
    from NOTECREDIT1 WHERE CodNCredit = RecId;

    select count(*) INTO vCount from notecredit1 WHERE codncredit = recid and tip = current_setting ('PKG_NOTECREDIT.tncProvizioane', true) ::numeric;

    if vCount &gt; 0 then
      insert  into TMP_NOTECREDITZ (
          CodNCredit1,
          CodNCredit,
          Valoare,
          CodObligStins,
          CodDoc,
          TipDoc,
          CodObligStingator,
          Obs,
          ValDif,
          Valoareold,
          CODNCREDIT1ORIG,
          CODDISCOUNT,
          DOC,
          NRDOC,
          DATADOC,
          MONEDA,
          SEDIU,
          CURS,
          VALDOC,
          VALLEI,
          DISCOUNT,
          DENCRITERIU,
          CREDITAT,
          DEN_CLASEDISC,
          CODCLASEDISC,
          PROCTVA,
          CODANALIZANOD,
          CODCENTRU)
      select NC1.CodNCredit1,
        NC1.CodNCredit,
        NC1.Valoare,
        I.CodIes,
        NC1.CodDoc,
        NC1.TipDoc,
        NC1.CodObligStingator,
        NC1.Obs,
        NC1.ValDif,
        NC1.Valoareold,
        NC1.CODNCREDIT1ORIG,
        NC1.CODDISCOUNT,
        I.PREFIXDOC   DOC,
        I.NRDOC       NRDOC,
        I.DATADOC     DATADOC,
        (select PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT from PKG_MONEDE_GET_SIMBOL_MONEDA (null, coalesce (G.MONEDA, NC.CODMONEDA))) MONEDA,
        A.OBS  SEDIU,
        CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end CURS,
        CASE when i.codies is null then nc1.valdoc else I.ValDoc - I.TVADOC end ,
        CASE when i.codies is null then nc1.valdoc
             else round ( ( (I.ValDoc - I.TVADOC) * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end) ::numeric, 4)
        end * CASE when NC.Corectie = 2 and coalesce (nc1.coddoc, 0) = 0 then NC.Curs else 1 end VALLEI,
        0,
        CD.DENCRITERIU,
        coalesce (ALTE.CREDITAT, 0) + coalesce (ALTELIBERE.CREDITAT, 0) ,
        CLSDISC.DEN_CLASEDISC,
        CLSDISC.CODCLASEDISC,
        coalesce (nc1.proctva, 24),
        CODANALIZANOD,
        CODCENTRU
      from NOTECREDIT1                        NC1
        inner join NOTECREDIT                 NC      on NC.CODNCREDIT = NC1.CODNCREDIT
        left join IESDISC                     ID      on NC1.CODDOC    = ID.CODIESDISC
        left join DISCOUNT                    D       on coalesce (ID.CODDISCOUNT, NC1.CODDISCOUNT) = D.CODDISCOUNT
        left join CRITERIIDISC                CD      on CD.CODCRITERIU       = D.CODCRITERIU
        left join IESIRI                      I       on I.CODIES             = ID.CodIes and NC1.TipDoc = I.TipDoc
        left join NCLASEDISC                  CLSDISC on CLSDISC.CODCLASEDISC = CD.CLASA
        left join general                     G       on I.CODIES             = G.CODDOC and I.TipDoc = G.TipDoc
        left join TMP_CURS_REGULARIZAT_LUNA   GREG    on GREG.CODGENERAL      = G.CODGENERAL
        left join NAGENDA                     A       on A.CODAGENDA          = I.CODLOCATIE
        left join (select sum (N1.VALOARE) CREDITAT, N1.CODDOC, coalesce (n1.proctva, 24) PROCTVA
                   from NOTECREDIT1 N1 inner join NOTECREDIT NC on NC.CODNCREDIT = N1.CODNCREDIT
                   where
                      N1.Valoare &lt;&gt; 0
                      and NC.TIPDOC = vTipDoc
                      and n1.TIP = current_setting ('PKG_NOTECREDIT.tncProvizioane', true) ::numeric
                      and N1.CODNCREDIT &lt;&gt; RecId
                      and coalesce (NC.CORECTIE, 0) = 0
                      and n1.coddoc &gt; 0
                   group BY n1.coddoc, coalesce (n1.proctva, 24)
                  )  ALTE on alte.coddoc = nc1.coddoc and alte.proctva = coalesce (nc1.proctva, 24)
        left join ( select sum (NCC1.VALOARE) CREDITAT, nc1.codncredit1, coalesce (nc1.proctva, 24) PROCTVA
                    from NOTECREDIT1             NC1
                      inner join NOTECREDIT      NC   on NC.CODNCREDIT = NC1.CODNCREDIT
                      inner join NOTECREDIT1     NCC1 on NCC1.CODNCREDIT1ORIG = NC1.CODNCREDIT1
                      inner join NOTECREDIT      NCC  on NCC.CODNCREDIT = NCC1.CODNCREDIT
                    where
                      coalesce (nc1.coddoc, 0) = 0
                      and NC1.Valoare &lt;&gt; 0
                      and NC.TIPDOC = vTipDoc
                      and NC1.TIP = 5
                      and NCC1.CODNCREDIT &lt;&gt; RecId
                      and coalesce (NCC.corectie, 0) = 0
                      and NC.corectie = 2
                    group BY nc1.codncredit1, coalesce (nc1.proctva, 24)
                  ) AlteLibere on altelibere.codncredit1 = nc1.CodNCredit1Orig and coalesce (nc1.proctva, 24) = altelibere.proctva
      where
        NC1.CodNCredit = RecId
        and NC1.Tip = current_setting ('PKG_NOTECREDIT.tncProvizioane', true) ::numeric
        and not coalesce (g.semnificatie, 0) in (240, 500, 211, 210);

      if vTipDoc = 58 then
        for v_rec in (with
                  IProc AS (
                    SELECT DISTINCT I1.CodIes,i1.codobiect, PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT, 1) ProcTVA
                    FROM tmp_notecreditz ncz
                      inner join iesdisc id on id.codiesdisc = NCZ.CODDOC
                      inner join iesiri i on id.codies = i.codies
                      inner join iesiri1 I1 on i.codies = i1.codies
                      INNER JOIN nartobj obj ON i1.codobiect = obj.codobiect
                      INNER JOIN nart1 art1 ON art1.codarticol = obj.codarticol AND I.AN*12+I.LUNA BETWEEN art1.ALStart AND art1.ALStop
                      INNER JOIN ntva1 tva1 ON tva1.codtva = art1.codtva        AND I.AN*12+I.LUNA BETWEEN tva1.ALStart AND tva1.ALStop                    ),
                    IProcVal as
                    (select ProcTva, CodIes, CodObiect, sum (BazaTVA)  BAZATVA, cumulat
                     from (select distinct IProc.ProcTVA, I.CodIes, ii.codobiect, i1.indexlocal,
                              i1.PretOrig * i1.cant *
                              case when ii.cumulat = 1 then 1 else nvl(i1.coefdiscmaj,1) END
                              -
                              CASE when not i.tipdoc in (16,21) then 0
                              else i1.PretOrig*i1.cant*
                              case when ii.cumulat = 1 then 1 else nvl(i1.coefdiscmaj,1) end
                              * (select pkg_list_base_utils_get_cota_tva_art.WME_RESULT from pkg_list_base_utils_get_cota_tva_art (null, i1.codobiect, i.an, i.luna)) / 100 end  BAZATVA, 0 cumulat
                           from ( select distinct id.codies, 0 CODOBIECT, coalesce(cd.cumulat,0) cumulat
                                  from tmp_notecreditz  ncz
                                    inner join iesdisc  id on id.codiesdisc = NCZ.CODDOC
                                    inner join discount d  on d.coddiscount = id.coddiscount
                                    inner join criteriidisc cd on cd.codcriteriu = d.codcriteriu
                                  where
                                    coalesce (id.codobiect, 0) = 0
                                )  ii
                            inner join iesiri  i  on ii.codies = i.codies
                            inner join iesiri1 I1 on i.codies  = i1.codies
                            inner join IProc      on i1.codies = IProc.codies and IProc.codobiect = i1.codobiect
                          ) A_PG
                      group BY ProcTVA, CodIes, CodObiect, cumulat
                      union all
                      select  distinct IProc.ProcTVA, I.CodIes, ii.codobiect,
                        sum (i1.PretOrig * i1.cant *
                        case when ii.cumulat = 1 then 1 else nvl(i1.coefdiscmaj,1) END
                        -
                        CASE when not i.tipdoc in (16, 21) then 0
                        else i1.PretOrig * i1.cant *
                        case when ii.cumulat = 1 then 1 else nvl(i1.coefdiscmaj,1) END *
                        (select pkg_list_base_utils_get_cota_tva_art.WME_RESULT
                        from pkg_list_base_utils_get_cota_tva_art (null, i1.codobiect, i.an, i.luna)) / 100
                        END)  BAZATVA, ii.cumulat
                      from (select distinct id.codies, id.codobiect, coalesce(cd.cumulat,0) cumulat
                            from tmp_notecreditz  ncz
                              inner join iesdisc  id on id.codiesdisc = NCZ.CODDOC
                              inner join discount d  on d.coddiscount = id.coddiscount
                              inner join criteriidisc cd on cd.codcriteriu = d.codcriteriu
                            WHERE coalesce (id.codobiect, 0) &gt; 0
                            ) ii
                        inner join iesiri  i  on ii.codies = i.codies
                        inner join iesiri1 I1 on i.codies  = i1.codies and i1.codobiect = ii.codobiect
                        inner join IProc      on i1.codies = IProc.codies and IProc.codobiect = i1.codobiect
                      group BY IProc.ProcTVA, I.CodIes, ii.codobiect, II.CUMULAT
                    )
                  select ncz.codncredit1, id.procent * IProcVal.BazaTVA / 100 VALDISC
                  from tmp_notecreditz ncz
                    inner join iesdisc id on id.codiesdisc   = NCZ.CODDOC
                    inner JOIN DISCOUNT D ON NVL(ID.CODDISCOUNT,NCz.CODDISCOUNT) = D.CODDISCOUNT
                    inner JOIN CRITERIIDISC CD ON CD.CODCRITERIU = D.CODCRITERIU
                    inner join IProcVal on IProcVal.CodIes = id.COdIes and ncz.proctva = IProcVal.ProcTVA and nvl(id.codobiect,0) = IProcVal.CodObiect and iprocval.cumulat = coalesce(cd.cumulat,0)
                  where
                    id.offinvoice = 2 and ncz.coddoc &gt; 0)
        loop
          UPDATE tmp_notecreditz set discount = v_Rec.valdisc WHERE codncredit1 = v_rec.codncredit1 and coddoc &gt; 0;
        end loop;

        for v_rec in (select ncz.codncredit1, n1.valoare VALDISC, n1.proctva
                      from tmp_notecreditz  ncz inner join notecredit1 n1 on n1.codncredit1 = ncz.codncredit1orig
                      where coalesce (ncz.coddoc, 0) = 0)
        loop
          UPDATE tmp_notecreditz set discount = v_Rec.valdisc WHERE codncredit1 = v_rec.codncredit1 and coalesce (coddoc, 0) = 0 and proctva = v_rec.proctva;
        end loop;
      else
        for v_rec in (with IProc as (
                    SELECT DISTINCT I1.CodIes1, PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT, 1) ProcTVA
                    FROM tmp_notecreditz ncz
                      inner join iesdisc id on id.codiesdisc = NCZ.CODDOC
                      inner join iesiri i on id.codies = i.codies
                      inner join iesiri1 I1 on i.codies = i1.codies
                      INNER JOIN nartobj obj ON i1.codobiect = obj.codobiect
                      INNER JOIN nart1 art1 ON art1.codarticol = obj.codarticol AND I.AN*12+I.LUNA BETWEEN art1.ALStart AND art1.ALStop
                      INNER JOIN ntva1 tva1 ON tva1.codtva = art1.codtva        AND I.AN*12+I.LUNA BETWEEN tva1.ALStart AND tva1.ALStop
                    ),
                    IProcVal as
                    (select IProc.ProcTVA,
                        I.CodIes,
                        sum (i1.PretOrig * i1.cant * coalesce (i1.coefdiscmaj, 1) -
                        case
                          when not i.tipdoc in (16, 21) then 0
                          else i1.PretOrig * i1.cant * coalesce (i1.coefdiscmaj, 1) * (select pkg_list_base_utils_get_cota_tva_art.WME_RESULT
                                                                                       from pkg_list_base_utils_get_cota_tva_art (null, i1.codobiect, i.an, i.luna)
                                                                                      ) / 100
                        end) BAZATVA
                      from tmp_notecreditz   ncz
                        inner join iesdisc id on id.codiesdisc = NCZ.CODDOC
                        inner join iesiri  i  on id.codies     = i.codies
                        inner join iesiri1 I1 on i.codies      = i1.codies
                        inner join IProc      on i1.codies1    = IProc.codies1
                      group BY IProc.ProcTVA, I.CodIes
                    )
                  select ncz.codncredit1, id.procent * IProcVal.BazaTVA / 100 VALDISC
                  from tmp_notecreditz  ncz
                    inner join iesdisc  id on id.codiesdisc   = NCZ.CODDOC
                    inner join IProcVal    on IProcVal.CodIes = id.COdIes and ncz.proctva = IProcVal.ProcTVA
                  where
                    id.offinvoice = 3)
        loop
          UPDATE tmp_notecreditz set discount = v_Rec.valdisc WHERE codncredit1 = v_rec.codncredit1 and coddoc &gt; 0;
        end loop;

        for v_rec in (select ncz.codncredit1, n1.valoare VALDISC, n1.proctva
                      from tmp_notecreditz ncz inner join notecredit1 n1 on n1.codncredit1 = ncz.codncredit1orig
                      where coalesce (ncz.coddoc, 0) = 0)
        loop
          UPDATE tmp_notecreditz set discount = v_Rec.valdisc WHERE codncredit1 = v_rec.codncredit1 and coalesce (coddoc, 0) = 0 and proctva = v_rec.proctva;
        end loop;
      end if;

      UPDATE tmp_notecreditz set discount = valoare WHERE coalesce (coddoc, 0) = 0 and coalesce (codncredit1orig, 0) = 0;

      if vAreCorectii &gt; 0 then
        UPDATE tmp_notecreditz tmpz
        set valoare = valoare + coalesce ( (select sum (coalesce (valoare, 0) - coalesce (valoareold, 0)) from notecredit1 WHERE codncredit1orig = tmpz.codncredit1) , 0);
      end if;
    end if;

    insert  into tmp_notecreditzc (
        codncredit,
        valoare,
        discount,
        dencriteriu,
        creditat,
        den_clasedisc,
        valoareold,
        proctva)
    select RecId,
      sum (valoare) ,
      sum (discount) ,
      dencriteriu,
      sum (creditat) ,
      den_clasedisc,
      sum (valoareold) ,
      proctva
    from tmp_notecreditz
    group BY dencriteriu, den_clasedisc, proctva;

    select count(*) INTO vCount from notecredit1 WHERE codncredit = recid and tip = current_setting ('PKG_NOTECREDIT.tncVolum', true) ::numeric;

    if vCount &gt; 0 then
      perform PKG_NOTECREDIT_MAKE_MANEVRA_NC (RecId, null);
      if vTipDoc = 58 then
        if vCodContract  &gt; 0 then
          if vTipDiscV = 0 then
            insert into TMP_NOTECREDITV (
                CodNCredit1,
                CodNCredit,
                Valoare,
                CodObligStins,
                CodDoc,
                TipDoc,
                CodObligStingator,
                Obs,
                ValDif,
                Valoareold,
                DOC,
                NRDOC,
                DATADOC,
                MONEDA,
                SEDIU,
                CURS,
                VALDOC_N,
                VALLEI_N,
                DISCOUNT_N,
                VALDOC_B,
                VALLEI_B,
                DISCOUNT_B,
                CODOBIECT,
                DENUMIRE,
                CODDOCMASTER,
                CODCLASEDISC,
                CODNCREDIT1ORIG,
                PROCTVA,
                CODANALIZANOD,
                CODCENTRU)
            with ValAfis as
              ( select codies, sum (valm) VALM, sum (valm_b) VALM_B, ProcTVA
                from (select I.CodIes,
                            case
                              when i.tipdoc = 21 then (I1.Cant * i1.pretorig - I1.TVA) * coalesce (I1.CoefDiscMaj, 1)
                              else i1.cant * i1.pretorig * coalesce (I1.CoefDiscMaj, 1)
                            end VALM,
                            case
                              when i.tipdoc = 21 then I1.Cant * i1.pretorig - I1.TVA
                              else i1.cant                * i1.pretorig
                            end VALM_B,
                            PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT, 1) ProcTVA
                    from notecredit1     nc1
                      inner join IESIRI  I    on nc1.coddoc      = i.codies and nc1.tipdoc = i.tipdoc
                      inner join iesiri1 I1   on i.codies        = i1.codies
                      inner join nartobj obj  on i1.codobiect    = obj.codobiect
                      INNER JOIN nart1 art1 ON art1.codarticol = obj.codarticol AND I.AN*12+I.LUNA BETWEEN art1.ALStart AND art1.ALStop
                      INNER JOIN ntva1 tva1 ON tva1.codtva = art1.codtva        AND I.AN*12+I.LUNA BETWEEN tva1.ALStart AND tva1.ALStop
                    where
                      I.DataDoc between vDataStart and vDataStop
                      and i1.codobiect &gt; 0
                      and (I1.CodObiect not in (current_setting ('PKG_NOTECREDIT.KArtDiscAcVol', true) ::numeric,
                                                current_setting ('PKG_NOTECREDIT.KArtDiscAcCant', true) ::numeric,
                                                current_setting ('PKG_NOTECREDIT.KArtPenAcTer', true) ::numeric,
                                                current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceC', true) ::numeric)
                      and INSTR (current_setting ('PKG_NOTECREDIT.KArtDiscAcTer', true) , (I1.CODOBIECT) ::varchar) = 0)
                      and nc1.tip = current_setting ('PKG_NOTECREDIT.tncVolum', true) ::numeric
                      and nc1.codncredit = RecId
                      AND Coalesce(nc1.proctva,24) = PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT, 1)
                      ) B_PG
                group BY codies, ProcTVA
              )
            select NC1.CodNCredit1,
              NC1.CodNCredit,
              NC1.Valoare,
              NC1.CodObligStins,
              NC1.CodDoc,
              NC1.TipDoc,
              NC1.CodObligStingator,
              NC1.Obs,
              NC1.ValDif,
              NC1.Valoareold,
              I.PREFIXDOC  DOC,
              I.NRDOC      NRDOC,
              I.DATADOC    DATADOC,
              (select PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT from PKG_MONEDE_GET_SIMBOL_MONEDA (null, G.MONEDA)) MONEDA,
              A.OBS  SEDIU,
              CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end  CURS,
              round ( (V.ValM) ::numeric, 4) VALDOC,
              round ( (V.ValM * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end) ::numeric, 4) VALLEI,
              CASE
                when vTrimestriala = 1 then (select pkg_notecredit_GetDiscVolumTrim.WME_RESULT
                                             from   pkg_notecredit_GetDiscVolumTrim (null, I.CodIes, vCodContract, 1, RecID, vTrimestru, 0, vCurs))
                else (select pkg_notecredit_GetDiscVolum.WME_RESULT from pkg_notecredit_GetDiscVolum (null, I.CodIes, vCodContract, 1, RecID, 0, vCurs))
              end ,
              round ( (V.ValM_b) ::numeric, 4) VALDOC_B,
              round ( (V.ValM_b * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end) ::numeric, 4) VALLEI_B,
              case
                when vTrimestriala = 1 then (select pkg_notecredit_GetDiscVolumTrim.WME_RESULT
                                             from pkg_notecredit_GetDiscVolumTrim (null, I.CodIes, vCodContract, 1, RecID, vTrimestru, 1, vCurs))
                else (select pkg_notecredit_GetDiscVolum.WME_RESULT from pkg_notecredit_GetDiscVolum (null, I.CodIes, vCodContract, 1, RecID, 1, vCurs))
              end ,
              0,
              '',
              I.CODIES,
              NC1.CODCLASEDISC,
              NC1.CODNCREDIT1ORIG,
              coalesce (NC1.PROCTVA, v.proctva),
              NC1.CODANALIZANOD,
              NC1.CODCENTRU
            from NOTECREDIT1                      NC1
              inner join IESIRI                   I    on NC1.Coddoc      = I.CodIes and NC1.TipDoc = I.TipDoc
              inner join VALAFIS                  V    on I.CODIES        = V.CODIES and coalesce (nc1.proctva, 24) = v.proctva
              left join general                   G    on I.CODIES        = G.CODDOC and I.TipDoc = G.TipDoc
              left join TMP_CURS_REGULARIZAT_LUNA GREG on GREG.CODGENERAL = G.CODGENERAL
              left join NAGENDA                   A    on A.CODAGENDA     = I.CODLOCATIE
            where
              NC1.CodNCredit = RecId
              and NC1.Tip = current_setting ('PKG_NOTECREDIT.tncVolum', true) ::numeric
              and G.Semnificatie = 200;

          else
            if vTipDiscV = 1 then
              insert  into TMP_NOTECREDITV (
                  CodNCredit1,
                  CodNCredit,
                  Valoare,
                  CodObligStins,
                  CodDoc,
                  TipDoc,
                  CodObligStingator,
                  Obs,
                  ValDif,
                  Valoareold,
                  DOC,
                  NRDOC,
                  DATADOC,
                  MONEDA,
                  SEDIU,
                  CURS,
                  VALDOC_N,
                  VALLEI_N,
                  DISCOUNT_N,
                  VALDOC_B,
                  VALLEI_B,
                  DISCOUNT_B,
                  CODOBIECT,
                  DENUMIRE,
                  CODDOCMASTER,
                  CODCLASEDISC,
                  CODNCREDIT1ORIG,
                  PROCTVA,
                  CODANALIZANOD,
                  CODCENTRU)
              with ValAfis as
                ( select codies, sum (valm)   VALM, sum (valm_b) VALM_B, proctva
                  from (select I.CodIes,
                          case when i.tipdoc = 21 then (I1.Cant * i1.pretorig - I1.TVA) * coalesce (I1.CoefDiscMaj, 1) else i1.cant * i1.pretorig * coalesce (I1.CoefDiscMaj, 1) end VALM,
                          case when i.tipdoc = 21 then I1.Cant * i1.pretorig - I1.TVA else i1.cant * i1.pretorig end VALM_B,
                          PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT, 1) ProcTVA
                        from notecredit1       nc1
                          inner join IESIRI    I  on nc1.coddoc      = i.codies and nc1.tipdoc = i.tipdoc
                          inner join iesiri1   I1 on i.codies        = i1.codies
                          inner join contract1 c1 on c1.codcontract1 = (select PKG_NOTECREDIT_GetCodContract1.WME_RESULT
                                                                        from PKG_NOTECREDIT_GetCodContract1 (null, i1.codobiect, i.datadoc, vCodContract))
                          inner join nartobj obj  on i1.codobiect    = obj.codobiect
                          INNER JOIN nart1 art1 ON art1.codarticol = obj.codarticol AND I.AN*12+I.LUNA BETWEEN art1.ALStart AND art1.ALStop
                          INNER JOIN ntva1 tva1 ON tva1.codtva = art1.codtva        AND I.AN*12+I.LUNA BETWEEN tva1.ALStart AND tva1.ALStop
                        where
                          I.DataDoc between vDataStart and vDataStop
                          and i1.codobiect &gt; 0
                          and (I1.CodObiect not in (current_setting ('PKG_NOTECREDIT.KArtDiscAcVol', true) ::numeric,
                                                    current_setting ('PKG_NOTECREDIT.KArtDiscAcCant', true) ::numeric,
                                                    current_setting ('PKG_NOTECREDIT.KArtPenAcTer', true) ::numeric,
                                                    current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceC', true) ::numeric)
                          and INSTR (current_setting ('PKG_NOTECREDIT.KArtDiscAcTer', true) , (I1.CODOBIECT) ::varchar) = 0)
                          and nc1.tip = current_setting ('PKG_NOTECREDIT.tncVolum', true) ::numeric
                          and c1.codcontract = vCodContract
                          and nc1.codncredit = RecId
                          AND Coalesce(nc1.proctva,24) = PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT, 1)
                       ) C_PG
                  group BY codies, proctva
                )
              select NC1.CodNCredit1,
                NC1.CodNCredit,
                NC1.Valoare,
                NC1.CodObligStins,
                NC1.CodDoc,
                NC1.TipDoc,
                NC1.CodObligStingator,
                NC1.Obs,
                NC1.ValDif,
                NC1.Valoareold,
                I.PREFIXDOC     DOC,
                I.NRDOC         NRDOC,
                I.DATADOC       DATADOC,
                (select PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT from PKG_MONEDE_GET_SIMBOL_MONEDA (null, G.MONEDA)) MONEDA,
                A.OBS   SEDIU,
                CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end  CURS,
                round ( (V.ValM) ::numeric, 4) VALDOC,
                round ( (V.ValM * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end) ::numeric, 4) VALLEI,
                case
                  when vTrimestriala = 1 then (select pkg_notecredit_GetDiscVolumTrim.WME_RESULT
                                               from   pkg_notecredit_GetDiscVolumTrim (null, I.CodIes, vCodContract, 1, RecId, vTrimestru, 0, vCurs))
                  else (select pkg_notecredit_GetDiscVolum.WME_RESULT from pkg_notecredit_GetDiscVolum (null, I.CodIes, vCodContract, 1, RecId, 0, vCurs))
                end ,
                round ( (V.ValM_b) ::numeric, 4) VALDOC_B,
                round ( (V.ValM_b * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end) ::numeric, 4) VALLEI_B,
                case
                  when vTrimestriala = 1 then (select pkg_notecredit_GetDiscVolumTrim.WME_RESULT
                                               from   pkg_notecredit_GetDiscVolumTrim (null, I.CodIes, vCodContract, 1, RecId, vTrimestru, 1, vCurs))
                  else (select pkg_notecredit_GetDiscVolum.WME_RESULT from pkg_notecredit_GetDiscVolum (null, I.CodIes, vCodContract, 1, RecId, 1, vCurs))
                end ,
                0,
                '',
                I.CODIES,
                NC1.CODCLASEDISC,
                NC1.CODNCREDIT1ORIG,
                coalesce (NC1.PROCTVA, 24),
                NC1.CODANALIZANOD,
                NC1.CODCENTRU
              from NOTECREDIT1                      NC1
                inner join IESIRI                   I    on NC1.Coddoc      = I.CodIes and NC1.TipDoc = I.TipDoc
                inner join VALAFIS                  V    on I.CODIES        = V.CODIES and coalesce (nc1.proctva, 24) = v.proctva
                left join general                   G    on I.CODIES        = G.CODDOC and I.TipDoc = G.TipDoc
                left join TMP_CURS_REGULARIZAT_LUNA GREG on GREG.CODGENERAL = G.CODGENERAL
                left join NAGENDA                   A    on A.CODAGENDA     = I.CODLOCATIE
              where
                NC1.CodNCredit = RecId
                and NC1.Tip = current_setting ('PKG_NOTECREDIT.tncVolum', true) ::numeric
                and G.Semnificatie = 200;

            else
              insert  into TMP_NOTECREDITV (
                  CodNCredit1,
                  CodNCredit,
                  Valoare,
                  CodObligStins,
                  CodDoc,
                  TipDoc,
                  CodObligStingator,
                  Obs,
                  ValDif,
                  Valoareold,
                  DOC,
                  NRDOC,
                  DATADOC,
                  MONEDA,
                  SEDIU,
                  CURS,
                  VALDOC_N,
                  VALLEI_N,
                  DISCOUNT_N,
                  VALDOC_B,
                  VALLEI_B,
                  DISCOUNT_B,
                  CODOBIECT,
                  DENUMIRE,
                  CODDOCMASTER,
                  CODCLASEDISC,
                  CODINTERN,
                  CODNCREDIT1ORIG,
                  PROCTVA,
                  CODANALIZANOD,
                  CODCENTRU)
              with ValAfis as
                ( select codies1, valm, valm_b
                  from (select I1.CodIes1,
                              case
                                when coalesce (c1.tipdiscount, 0) = 0 then
                                  case
                                    when i.tipdoc = 21 then (I1.Cant * i1.pretorig - I1.TVA) * coalesce (I1.CoefDiscMaj, 1)
                                    else i1.cant * i1.pretorig * coalesce (I1.CoefDiscMaj, 1)
                                  end
                                else I1.Cant * C1.pret
                              end VALM,
                              case
                                when coalesce (c1.tipdiscount, 0) = 0 then
                                  case
                                    when i.tipdoc = 21 then I1.Cant * i1.pretorig - I1.TVA
                                    else i1.cant * i1.pretorig
                                  end
                                else I1.Cant * C1.pret
                              end                  VALM_B
                        from notecredit1       nc1
                          inner join IESIRI    I  on nc1.tipdoc      = i.tipdoc
                          inner join iesiri1   I1 on i.codies        = i1.codies and nc1.coddoc = i1.codies1
                          inner join contract1 c1 on c1.codcontract1 = (select PKG_NOTECREDIT_GetCodContract1.WME_RESULT
                                                                        from   PKG_NOTECREDIT_GetCodContract1 (null, i1.codobiect, i.datadoc, vCodContract))
                          inner join nartobj obj  on i1.codobiect    = obj.codobiect
                          INNER JOIN nart1 art1 ON art1.codarticol = obj.codarticol AND I.AN*12+I.LUNA BETWEEN art1.ALStart AND art1.ALStop
                          INNER JOIN ntva1 tva1 ON tva1.codtva = art1.codtva        AND I.AN*12+I.LUNA BETWEEN tva1.ALStart AND tva1.ALStop
                        where
                            I.DataDoc between vDataStart and vDataStop
                            and i1.codobiect &gt; 0
                            and (I1.CodObiect not in (current_setting ('PKG_NOTECREDIT.KArtDiscAcVol', true) ::numeric,
                                                      current_setting ('PKG_NOTECREDIT.KArtDiscAcCant', true) ::numeric,
                                                      current_setting ('PKG_NOTECREDIT.KArtPenAcTer', true) ::numeric,
                                                      current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceC', true) ::numeric)
                            and INSTR (current_setting ('PKG_NOTECREDIT.KArtDiscAcTer', true) , (I1.CODOBIECT) ::varchar) = 0)
                            and nc1.tip = current_setting ('PKG_NOTECREDIT.tncVolum', true) ::numeric
                            and c1.codcontract = vCodContract
                            and nc1.codncredit = RecId
                            AND Coalesce(nc1.proctva,24) = PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT, 1)
                           ) D_PG
                )
              select NC1.CodNCredit1,
                NC1.CodNCredit,
                NC1.Valoare,
                NC1.CodObligStins,
                NC1.CodDoc,
                NC1.TipDoc,
                NC1.CodObligStingator,
                NC1.Obs,
                NC1.ValDif,
                NC1.Valoareold,
                I.PREFIXDOC   DOC,
                I.NRDOC       NRDOC,
                I.DATADOC     DATADOC,
                (select PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT from PKG_MONEDE_GET_SIMBOL_MONEDA (null, G.MONEDA)) MONEDA,
                A.OBS   SEDIU,
                CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end  CURS,
                round ( (V.ValM) ::numeric, 4) VALDOC,
                round ( (V.ValM * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end) ::numeric, 4) VALLEI,
                (select pkg_notecredit_GetDiscVolum.WME_RESULT from pkg_notecredit_GetDiscVolum (null, I1.CodIes1, vCodContract, 1, RecId, 0, vCurs)) ,
                round ( (V.ValM_b) ::numeric, 4) VALDOC_B,
                round ( (V.ValM_b * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end) ::numeric, 4) VALLEI_B,
                (select pkg_notecredit_GetDiscVolum.WME_RESULT from pkg_notecredit_GetDiscVolum (null, I1.CodIes1, vCodContract, 1, RecId, 1, vCurs)) ,
                I1.CodObiect,
                OBJ.Denumire,
                I.CODIES,
                NC1.CODCLASEDISC,
                OBJ.CODINTERN,
                NC1.CODNCREDIT1ORIG,
                coalesce (NC1.PROCTVA, 24),
                NC1.CODANALIZANOD,
                NC1.CODCENTRU
              from NOTECREDIT1                      NC1
                inner join IESIRI                   I    on NC1.TipDoc      = I.TipDoc
                inner join IESIRI1                  I1   on NC1.Coddoc      = I1.CodIes1 and I.CodIes = I1.CodIes
                inner join VALAFIS                  V    on V.CODIES1       = I1.CODIES1
                inner join NARTOBJ                  OBJ  on I1.CodObiect    = OBJ.CodObiect
                left join general                   G    on I.CODIES        = G.CODDOC and I.TipDoc = G.TipDoc
                left join TMP_CURS_REGULARIZAT_LUNA GREG on GREG.CODGENERAL = G.CODGENERAL
                left join NAGENDA                   A    on A.CODAGENDA     = I.CODLOCATIE
              where
                NC1.CodNCredit = RecId
                and NC1.Tip = current_setting ('PKG_NOTECREDIT.tncVolum', true) ::numeric
                and G.Semnificatie = 200;
            end if;
          end if;
        else
          if vVolumPeArticole = 0 then
            insert  into TMP_NOTECREDITV (
                CodNCredit1,
                CodNCredit,
                Valoare,
                CodObligStins,
                CodDoc,
                TipDoc,
                CodObligStingator,
                Obs,
                ValDif,
                Valoareold,
                DOC,
                NRDOC,
                DATADOC,
                MONEDA,
                SEDIU,
                CURS,
                VALDOC_N,
                VALLEI_N,
                DISCOUNT_N,
                VALDOC_B,
                VALLEI_B,
                DISCOUNT_B,
                CODOBIECT,
                Denumire,
                CODDOCMASTER,
                CODCLASEDISC,
                CODNCREDIT1ORIG,
                PROCTVA,
                CODANALIZANOD,
                CODCENTRU)
            with ValAfis as
              ( select codies, sum (valm)   VALM, sum (valm_b) VALM_B, proctva
                from (select I.CodIes,
                            case
                              when i.tipdoc = 21 then (I1.Cant * i1.pretorig - I1.TVA) * coalesce (I1.CoefDiscMaj, 1)
                              else i1.cant * i1.pretorig * coalesce (I1.CoefDiscMaj, 1)
                            end VALM,
                            case
                              when i.tipdoc = 21 then I1.Cant * i1.pretorig - I1.TVA
                              else i1.cant                * i1.pretorig
                            end VALM_B,
                            PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT, 1) ProcTVA
                      from notecredit1     nc1
                        inner join IESIRI  I    on nc1.coddoc      = i.codies and nc1.tipdoc = i.tipdoc
                        inner join iesiri1 I1   on i.codies        = i1.codies
                        inner join nartobj obj  on i1.codobiect    = obj.codobiect
                        INNER JOIN nart1 art1 ON art1.codarticol = obj.codarticol AND I.AN*12+I.LUNA BETWEEN art1.ALStart AND art1.ALStop
                        INNER JOIN ntva1 tva1 ON tva1.codtva = art1.codtva        AND I.AN*12+I.LUNA BETWEEN tva1.ALStart AND tva1.ALStop
                      where
                        I.DataDoc between vDataStart and vDataStop
                        and i1.codobiect &gt; 0
                        and (I1.CodObiect not in (current_setting ('PKG_NOTECREDIT.KArtDiscAcVol', true) ::numeric,
                                                  current_setting ('PKG_NOTECREDIT.KArtDiscAcCant', true) ::numeric,
                                                  current_setting ('PKG_NOTECREDIT.KArtPenAcTer', true) ::numeric,
                                                  current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceC', true) ::numeric)
                        and INSTR (current_setting ('PKG_NOTECREDIT.KArtDiscAcTer', true) , (I1.CODOBIECT) ::varchar) = 0)
                        and nc1.tip = current_setting ('PKG_NOTECREDIT.tncVolum', true) ::numeric
                        and nc1.codncredit = RecId
                        AND Coalesce(nc1.proctva,24) = PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT, 1)
                        ) E_PG
                group BY codies, proctva
              )
            select NC1.CodNCredit1,
              NC1.CodNCredit,
              NC1.Valoare,
              NC1.CodObligStins,
              NC1.CodDoc,
              NC1.TipDoc,
              NC1.CodObligStingator,
              NC1.Obs,
              NC1.ValDif,
              NC1.Valoareold,
              I.PREFIXDOC  DOC,
              I.NRDOC      NRDOC,
              I.DATADOC    DATADOC,
              (select PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT from PKG_MONEDE_GET_SIMBOL_MONEDA (null, G.MONEDA)) MONEDA,
              A.OBS  SEDIU,
              CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end  CURS,
              round ( (V.ValM) ::numeric, 4) VALDOC,
              round ( (V.ValM * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end) ::numeric, 4) VALLEI,
              (select pkg_notecredit_GetDiscVolum.WME_RESULT from pkg_notecredit_GetDiscVolum (null, I.CodIes, vCodContract, 1, RecId, 0, vCurs)) ,
              round ( (V.ValM_b) ::numeric, 4) VALDOC_B,
              round ( (V.ValM_b * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end) ::numeric, 4) VALLEI_B,
              (select pkg_notecredit_GetDiscVolum.WME_RESULT from pkg_notecredit_GetDiscVolum (null, I.CodIes, vCodContract, 1, RecId, 1, vCurs)) ,
              0,
              '',
              I.CODIES,
              NC1.CODCLASEDISC,
              NC1.CODNCREDIT1ORIG,
              coalesce (NC1.PROCTVA, 24),
              NC1.CODANALIZANOD,
              NC1.CODCENTRU
            from NOTECREDIT1                      NC1
              inner join IESIRI                   I    on NC1.Coddoc      = I.CodIes and NC1.TipDoc = I.TipDoc
              inner join VALAFIS                  V    on V.CODIES        = I.CODIES and v.proctva = coalesce (nc1.proctva, 24)
              left join general                   G    on I.CODIES        = G.CODDOC and I.TipDoc = G.TipDoc
              left join TMP_CURS_REGULARIZAT_LUNA GREG on GREG.CODGENERAL = G.CODGENERAL
              left join NAGENDA                   A    on A.CODAGENDA     = I.CODLOCATIE
            where
              NC1.CodNCredit = RecId
              and NC1.Tip = current_setting ('PKG_NOTECREDIT.tncVolum', true) ::numeric
              and G.Semnificatie = 200;

          else
            insert  into TMP_NOTECREDITV (
                CodNCredit1,
                CodNCredit,
                Valoare,
                CodObligStins,
                CodDoc,
                TipDoc,
                CodObligStingator,
                Obs,
                ValDif,
                Valoareold,
                DOC,
                NRDOC,
                DATADOC,
                MONEDA,
                SEDIU,
                CURS,
                VALDOC_N,
                VALLEI_N,
                DISCOUNT_N,
                VALDOC_B,
                VALLEI_B,
                DISCOUNT_B,
                CODOBIECT,
                Denumire,
                CODDOCMASTER,
                CODCLASEDISC,
                CODINTERN,
                CODNCREDIT1ORIG,
                PROCTVA,
                CODANALIZANOD,
                CODCENTRU)
            with ValAfis as
              ( select codies1, sum (valm)   VALM, sum (valm_b) VALM_B
                from (select I1.CodIes1,
                            sum (CASE when i.tipdoc = 21 then (I1.Cant * i1.pretorig - I1.TVA) * coalesce (I1.CoefDiscMaj, 1)
                                      else i1.cant * i1.pretorig * coalesce (I1.CoefDiscMaj, 1)
                                 END) VALM,
                            sum (CASE when i.tipdoc = 21 then I1.Cant * i1.pretorig - I1.TVA else i1.cant * i1.pretorig end) VALM_B
                      from notecredit1     nc1
                        inner join IESIRI  I    on nc1.tipdoc      = i.tipdoc
                        inner join iesiri1 I1   on i.codies        = i1.codies and nc1.coddoc = i1.codies1
                        inner join nartobj obj  on i1.codobiect    = obj.codobiect
                        INNER JOIN nart1 art1 ON art1.codarticol = obj.codarticol AND I.AN*12+I.LUNA BETWEEN art1.ALStart AND art1.ALStop
                        INNER JOIN ntva1 tva1 ON tva1.codtva = art1.codtva        AND I.AN*12+I.LUNA BETWEEN tva1.ALStart AND tva1.ALStop
                      where
                        I.DataDoc between vDataStart and vDataStop
                        and i1.codobiect &gt; 0
                        and (I1.CodObiect not in (current_setting ('PKG_NOTECREDIT.KArtDiscAcVol', true) ::numeric,
                                                  current_setting ('PKG_NOTECREDIT.KArtDiscAcCant', true) ::numeric,
                                                  current_setting ('PKG_NOTECREDIT.KArtPenAcTer', true) ::numeric,
                                                  current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceC', true) ::numeric)
                        and INSTR (current_setting ('PKG_NOTECREDIT.KArtDiscAcTer', true) , (I1.CODOBIECT) ::varchar) = 0)
                        and nc1.tip = current_setting ('PKG_NOTECREDIT.tncVolum', true) ::numeric
                        and nc1.codncredit = RecId
                        AND Coalesce(nc1.proctva,24) = PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT, 1)
                      group BY I1.CodIes1
                    ) F_PG
                group BY codies1
              )
            select NC1.CodNCredit1,
              NC1.CodNCredit,
              NC1.Valoare,
              NC1.CodObligStins,
              NC1.CodDoc,
              NC1.TipDoc,
              NC1.CodObligStingator,
              NC1.Obs,
              NC1.ValDif,
              NC1.Valoareold,
              I.PREFIXDOC  DOC,
              I.NRDOC      NRDOC,
              I.DATADOC    DATADOC,
              (select PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT from PKG_MONEDE_GET_SIMBOL_MONEDA (null, G.MONEDA)) MONEDA,
              A.OBS  SEDIU,
              CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) END  CURS,
              round ( (V.ValM) ::numeric, 4) VALDOC,
              round ( (V.ValM * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end) ::numeric, 4) VALLEI,
              (select pkg_notecredit_GetDiscVolum.WME_RESULT from pkg_notecredit_GetDiscVolum (null, I1.CodIes1, vCodContract, 1, RecId, 0, vCurs)) ,
              round ( (V.ValM_b) ::numeric, 4) VALDOC_B,
              round ( (V.ValM_b * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end) ::numeric, 4) VALLEI_B,
              (select pkg_notecredit_GetDiscVolum.WME_RESULT from pkg_notecredit_GetDiscVolum (null, I1.CodIes1, vCodContract, 1, RecId, 1, vCurs)) ,
              i1.codobiect,
              obj.denumire,
              I.CODIES,
              NC1.CODCLASEDISC,
              OBJ.CODINTERN,
              NC1.CODNCREDIT1ORIG,
              coalesce (NC1.PROCTVA, 24),
              NC1.CODANALIZANOD,
              NC1.CODCENTRU
            from NOTECREDIT1                      NC1
              inner join IESIRI1                  I1   on NC1.Coddoc      = I1.CodIes1
              inner join IESIRI                   I    on I1.CODIES       = I.CODIES and NC1.TipDoc = I.TipDoc
              inner join VALAFIS                  V    on V.CODIES1       = I1.CODIES1
              inner join NARTOBJ                  OBJ  on OBJ.CODOBIECT   = I1.CODOBIECT
              left join general                   G    on I.CODIES        = G.CODDOC and I.TipDoc = G.TipDoc
              left join TMP_CURS_REGULARIZAT_LUNA GREG on GREG.CODGENERAL = G.CODGENERAL
              left join NAGENDA                   A    on A.CODAGENDA     = I.CODLOCATIE
            where
              NC1.CodNCredit = RecId
              and NC1.Tip = current_setting ('PKG_NOTECREDIT.tncVolum', true) ::numeric
              and G.Semnificatie = 200;
          end if;
        end if;
      else
        if vCodContract  &gt; 0 then
          if vTipDiscV = 0 then
            insert  into TMP_NOTECREDITV (
                CodNCredit1,
                CodNCredit,
                Valoare,
                CodObligStins,
                CodDoc,
                TipDoc,
                CodObligStingator,
                Obs,
                ValDif,
                Valoareold,
                DOC,
                NRDOC,
                DATADOC,
                MONEDA,
                SEDIU,
                CURS,
                VALDOC_N,
                VALLEI_N,
                DISCOUNT_N,
                VALDOC_B,
                VALLEI_B,
                DISCOUNT_B,
                CODOBIECT,
                DENUMIRE,
                CODDOCMASTER,
                CODCLASEDISC,
                CODNCREDIT1ORIG,
                PROCTVA,
                CODANALIZANOD,
                CODCENTRU)
            with ValAfis as
              ( select codintr, sum (valm)   VALM, sum (valm_b) VALM_B, ProcTVA
                from (select I.CodIntr, I1.Cant * I1.PretOrig * I1.Coefdiscmaj VALM, I1.Cant * I1.PretOrig  VALM_B,
                                   PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT, 1) ProcTVA
                      from notecredit1      nc1
                        inner join INTRARI  I    on nc1.coddoc      = i.codintr and nc1.tipdoc = i.tipdoc
                        inner join intrari1 I1   on i.codintr       = i1.codintr
                        inner join nartobj  obj  on i1.codobiect    = obj.codobiect
                        INNER JOIN nart1 art1 ON art1.codarticol = obj.codarticol AND I.AN*12+I.LUNA BETWEEN art1.ALStart AND art1.ALStop
                        INNER JOIN ntva1 tva1 ON tva1.codtva = art1.codtva        AND I.AN*12+I.LUNA BETWEEN tva1.ALStart AND tva1.ALStop
                      where
                        I.DataDoc between vDataStart and vDataStop
                        and i1.codobiect &gt; 0
                        and I1.CodObiect not in (current_setting('PKG_NOTECREDIT.KArtDiscPrimVol', true) ::numeric,
                                                 current_setting('PKG_NOTECREDIT.KArtDiscPrimCant', true) ::numeric,
                                                 current_setting('PKG_NOTECREDIT.KArtPenPrimTer', true) ::numeric,
                                                 current_setting('PKG_NOTECREDIT.KArtDiscOffInvoiceF', true) ::numeric)
                        AND INSTR(current_setting ('PKG_NOTECREDIT.KArtDiscPrimTer', true) , (I1.CODOBIECT)::varchar) = 0
                        and nc1.tip = current_setting ('PKG_NOTECREDIT.tncVolum', true) ::numeric
                        AND Coalesce(nc1.proctva,24) = PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT, 1)
                        and nc1.codncredit = RecId
                        ) G_PG
                group BY codintr, proctva
              )
            select NC1.CodNCredit1,
              NC1.CodNCredit,
              NC1.Valoare,
              NC1.CodObligStins,
              NC1.CodDoc,
              NC1.TipDoc,
              NC1.CodObligStingator,
              NC1.Obs,
              NC1.ValDif,
              NC1.Valoareold,
              I.PREFIXDOC   DOC,
              I.NRDOC       NRDOC,
              I.DATADOC     DATADOC,
              (select PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT from PKG_MONEDE_GET_SIMBOL_MONEDA (null, G.MONEDA)) MONEDA,
              A.OBS SEDIU,
              CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end  CURS,
              round ( (V.ValM) ::numeric, 4) VALDOC,
              round ( (V.ValM * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end) ::numeric, 4) VALLEI,
              (select pkg_notecredit_GetDiscVolum.WME_RESULT from pkg_notecredit_GetDiscVolum (null, I.CodIntr, vCodContract, 2, RecId, 0, vCurs)) ,
              round ( (V.ValM_b) ::numeric, 4) VALDOC_B,
              round ( (V.ValM_b * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end) ::numeric, 4) VALLEI_B,
              (select pkg_notecredit_GetDiscVolum.WME_RESULT from pkg_notecredit_GetDiscVolum (null, I.CodIntr, vCodContract, 2, RecId, 1, vCurs)) ,
              0,
              '',
              I.CODINTR,
              NC1.CODCLASEDISC,
              NC1.CODNCREDIT1ORIG,
              coalesce (NC1.PROCTVA, v.proctva),
              NC1.CODANALIZANOD,
              NC1.CODCENTRU
            from NOTECREDIT1                      NC1
              inner join INTRARI                  I    on NC1.Coddoc      = I.CodIntr and NC1.TipDoc = I.TipDoc
              inner join VALAFIS                  V    on I.CODINTR       = V.CODINTR and coalesce (nc1.proctva, 24) = v.proctva
              left join general                   G    on I.CODINTR       = G.CODDOC  and I.TipDoc = G.TipDoc
              left join TMP_CURS_REGULARIZAT_LUNA GREG on GREG.CODGENERAL = G.CODGENERAL
              left join NAGENDA                   A    on A.CODAGENDA     = I.CODLOCATIE
            WHERE NC1.CodNCredit = RecId
              AND NC1.Tip = current_setting ('PKG_NOTECREDIT.tncVolum', true)::numeric
              and g.semnificatie &lt;&gt; 500
              and g.semnificatie &lt;&gt; 111
              and g.semnificatie &lt;&gt; 200
              and g.semnificatie &lt;&gt; 140
              and g.semnificatie &lt;&gt; 110;
          else
            if vTipDiscV = 1 then
              insert  into TMP_NOTECREDITV (
                  CodNCredit1,
                  CodNCredit,
                  Valoare,
                  CodObligStins,
                  CodDoc,
                  TipDoc,
                  CodObligStingator,
                  Obs,
                  ValDif,
                  Valoareold,
                  DOC,
                  NRDOC,
                  DATADOC,
                  MONEDA,
                  SEDIU,
                  CURS,
                  VALDOC_N,
                  VALLEI_N,
                  DISCOUNT_N,
                  VALDOC_B,
                  VALLEI_B,
                  DISCOUNT_B,
                  CODOBIECT,
                  DENUMIRE,
                  CODDOCMASTER,
                  CODCLASEDISC,
                  CODNCREDIT1ORIG,
                  PROCTVA,
                  CODANALIZANOD,
                  CODCENTRU)
              with ValAfis as
                ( select codintr, sum (valm)   VALM, sum (valm_b) VALM_B, ProcTVA
                  from (select I.CodIntr, I1.Cant * I1.PretOrig * I1.Coefdiscmaj VALM, I1.Cant * I1.PretOrig  VALM_B,
                                   PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT, 1) ProcTVA
                        from notecredit1       nc1
                          inner join INTRARI   I  on nc1.coddoc      = i.codintr and nc1.tipdoc = i.tipdoc
                          inner join intrari1  I1 on i.codintr       = i1.codintr
                          inner join contract1 c1 on c1.codcontract1 = (select PKG_NOTECREDIT_GetCodContract1.WME_RESULT
                                                                        from PKG_NOTECREDIT_GetCodContract1 (null, i1.codobiect, i.datadoc, vCodContract))
                          inner join nartobj obj  on i1.codobiect = obj.codobiect
                          INNER JOIN nart1 art1 ON art1.codarticol = obj.codarticol AND I.AN*12+I.LUNA BETWEEN art1.ALStart AND art1.ALStop
                          INNER JOIN ntva1 tva1 ON tva1.codtva = art1.codtva        AND I.AN*12+I.LUNA BETWEEN tva1.ALStart AND tva1.ALStop
                        where
                          I.DataDoc between vDataStart and vDataStop
                          and i1.codobiect &gt; 0
                          and I1.CodObiect not in (current_setting ('PKG_NOTECREDIT.KArtDiscPrimVol', true) ::numeric,
                                                   current_setting ('PKG_NOTECREDIT.KArtDiscPrimCant', true) ::numeric,
                                                   current_setting ('PKG_NOTECREDIT.KArtPenPrimTer', true) ::numeric,
                                                   current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceF', true) ::numeric)
                          AND INSTR(current_setting ('PKG_NOTECREDIT.KArtDiscPrimTer', true) , (I1.CODOBIECT)::varchar) = 0
                          and nc1.tip = current_setting ('PKG_NOTECREDIT.tncVolum', true) ::numeric
                          and c1.codcontract = vCodContract
                          AND Coalesce(nc1.proctva,24) = PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT, 1)
                          and nc1.codncredit = RecId
                          ) H_PG
                  group BY codintr, ProcTVA
                )
              select NC1.CodNCredit1,
                NC1.CodNCredit,
                NC1.Valoare,
                NC1.CodObligStins,
                NC1.CodDoc,
                NC1.TipDoc,
                NC1.CodObligStingator,
                NC1.Obs,
                NC1.ValDif,
                NC1.Valoareold,
                I.PREFIXDOC   DOC,
                I.NRDOC       NRDOC,
                I.DATADOC     DATADOC,
                (select PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT from PKG_MONEDE_GET_SIMBOL_MONEDA (null, G.MONEDA)) MONEDA,
                A.OBS   SEDIU,
                CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end  CURS,
                round ( (V.ValM) ::numeric, 4) VALDOC,
                round ( (V.ValM * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end) ::numeric, 4) VALLEI,
                (select pkg_notecredit_GetDiscVolum.WME_RESULT from pkg_notecredit_GetDiscVolum (null, I.CodIntr, vCodContract, 2, RecID, 0, vCurs)) ,
                round ( (V.ValM_b) ::numeric, 4) VALDOC_B,
                round ( (V.ValM_b * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end) ::numeric, 4) VALLEI_B,
                (select pkg_notecredit_GetDiscVolum.WME_RESULT from pkg_notecredit_GetDiscVolum (null, I.CodIntr, vCodContract, 2, RecID, 1, vCurs)) ,
                0,
                '',
                I.CODINTR,
                NC1.CODCLASEDISC,
                NC1.CODNCREDIT1ORIG,
                coalesce (NC1.PROCTVA, V.PROCTVA),
                NC1.CODANALIZANOD,
                NC1.CODCENTRU
              from NOTECREDIT1                      NC1
                inner join INTRARI                  I    on NC1.Coddoc      = I.CodIntr and NC1.TipDoc = I.TipDoc
                inner join VALAFIS                  V    on I.CODINTR       = V.CODINTR and coalesce (NC1.PROCTVA, 24) = V.ProcTVA
                left join general                   G    on I.CODINTR       = G.CODDOC  and I.TipDoc = G.TipDoc
                left join TMP_CURS_REGULARIZAT_LUNA GREG on GREG.CODGENERAL = G.CODGENERAL
                left join NAGENDA                   A    on A.CODAGENDA     = I.CODLOCATIE
              where
                NC1.CodNCredit = RecId
                and NC1.Tip = current_setting ('PKG_NOTECREDIT.tncVolum', true) ::numeric
                and g.semnificatie &lt;&gt; 500
                and g.semnificatie &lt;&gt; 111
                and g.semnificatie &lt;&gt; 200
                and g.semnificatie &lt;&gt; 140
                and g.semnificatie &lt;&gt; 110;
            else
              insert  into TMP_NOTECREDITV (
                  CodNCredit1,
                  CodNCredit,
                  Valoare,
                  CodObligStins,
                  CodDoc,
                  TipDoc,
                  CodObligStingator,
                  Obs,
                  ValDif,
                  Valoareold,
                  DOC,
                  NRDOC,
                  DATADOC,
                  MONEDA,
                  SEDIU,
                  CURS,
                  VALDOC_N,
                  VALLEI_N,
                  DISCOUNT_N,
                  VALDOC_B,
                  VALLEI_B,
                  DISCOUNT_B,
                  CODOBIECT,
                  DENUMIRE,
                  CODDOCMASTER,
                  CODCLASEDISC,
                  CODINTERN,
                  CODNCREDIT1ORIG,
                  PROCTVA,
                  CODANALIZANOD,
                  CODCENTRU)
              with ValAfis as
                ( select codintr1, valm, valm_b
                  from (select I1.CodIntr1, I1.Cant * I1.PretOrig * I1.Coefdiscmaj VALM, I1.Cant * I1.PretOrig VALM_B
                        from notecredit1       nc1
                          inner join INTRARI   I  on nc1.tipdoc = i.tipdoc
                          inner join intrari1  I1 on i.codintr = i1.codintr and nc1.coddoc = i1.codintr1
                          inner join contract1 c1 on c1.codcontract1 = (select PKG_NOTECREDIT_GetCodContract1.WME_RESULT
                                                                        from   PKG_NOTECREDIT_GetCodContract1 (null, i1.codobiect, i.datadoc, vCodContract))
                          inner join nartobj obj  on i1.codobiect = obj.codobiect
                          INNER JOIN nart1 art1 ON art1.codarticol = obj.codarticol AND I.AN*12+I.LUNA BETWEEN art1.ALStart AND art1.ALStop
                          INNER JOIN ntva1 tva1 ON tva1.codtva = art1.codtva        AND I.AN*12+I.LUNA BETWEEN tva1.ALStart AND tva1.ALStop
                        where
                          I.DataDoc between vDataStart and vDataStop
                          and i1.codobiect &gt; 0
                          and I1.CodObiect not in (current_setting ('PKG_NOTECREDIT.KArtDiscPrimVol', true) ::numeric,
                                                   current_setting ('PKG_NOTECREDIT.KArtDiscPrimCant', true) ::numeric,
                                                   current_setting ('PKG_NOTECREDIT.KArtPenPrimTer', true) ::numeric,
                                                   current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceF', true) ::numeric)
                          AND INSTR(current_setting ('PKG_NOTECREDIT.KArtDiscPrimTer', true) , (I1.CODOBIECT)::varchar) = 0
                          and nc1.tip = current_setting ('PKG_NOTECREDIT.tncVolum', true) ::numeric
                          and c1.codcontract = vCodContract
                          AND Coalesce(nc1.proctva,24) = PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT, 1)
                          and nc1.codncredit = RecId
                        ) I_PG
                )
              select NC1.CodNCredit1,
                NC1.CodNCredit,
                NC1.Valoare,
                NC1.CodObligStins,
                NC1.CodDoc,
                NC1.TipDoc,
                NC1.CodObligStingator,
                NC1.Obs,
                NC1.ValDif,
                NC1.Valoareold,
                I.PREFIXDOC   DOC,
                I.NRDOC       NRDOC,
                I.DATADOC     DATADOC,
                (select PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT from PKG_MONEDE_GET_SIMBOL_MONEDA (null, G.MONEDA)) MONEDA,
                A.OBS  SEDIU,
                CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end  CURS,
                round ( (V.ValM) ::numeric, 4) VALDOC,
                round ( (V.ValM * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end) ::numeric, 4) VALLEI,
                (select pkg_notecredit_GetDiscVolum.WME_RESULT from pkg_notecredit_GetDiscVolum (null, NC1.CodDoc, vCodContract, 2, RecID, 0, vCurs)) ,
                round ( (V.ValM_b) ::numeric, 4) VALDOC_B,
                round ( (V.ValM_b * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end) ::numeric, 4) VALLEI_B,
                (select pkg_notecredit_GetDiscVolum.WME_RESULT from pkg_notecredit_GetDiscVolum (null, NC1.CodDoc, vCodContract, 2, RecID, 1, vCurs)) ,
                I1.CODOBIECT,
                OBJ.DENUMIRE,
                I.CODINTR,
                NC1.CODCLASEDISC,
                OBJ.CODINTERN,
                NC1.CODNCREDIT1ORIG,
                NC1.PROCTVA,
                NC1.CODANALIZANOD,
                NC1.CODCENTRU
              from NOTECREDIT1                      NC1
                inner join INTRARI                  I    on NC1.TipDoc      = I.TipDoc
                inner join INTRARI1                 I1   on NC1.Coddoc      = I1.CodIntr1 and I1.CodIntr = I.CodIntr
                inner join VALAFIS                  V    on I1.CODINTR1     = V.CODINTR1
                inner join NARTOBJ                  OBJ  on OBJ.CodObiect   = I1.CodObiect
                left join general                   G    on I.CODINTR       = G.CODDOC and I.TipDoc = G.TipDoc
                left join TMP_CURS_REGULARIZAT_LUNA GREG on GREG.CODGENERAL = G.CODGENERAL
                left join NAGENDA                   A    on A.CODAGENDA     = I.CODLOCATIE
              where
                NC1.CodNCredit = RecId
                and NC1.Tip = current_setting ('PKG_NOTECREDIT.tncVolum', true) ::numeric
                and g.semnificatie &lt;&gt; 500
                and g.semnificatie &lt;&gt; 111
                and g.semnificatie &lt;&gt; 200
                and g.semnificatie &lt;&gt; 140
                and g.semnificatie &lt;&gt; 110;
            end if;
          end if;
        else
          if vVolumPeArticole   = 0 then
            if vIesiriPeVolum = 1 then
              insert  into TMP_NOTECREDITV (
                  CodNCredit1,
                  CodNCredit,
                  Valoare,
                  CodObligStins,
                  CodDoc,
                  TipDoc,
                  CodObligStingator,
                  Obs,
                  ValDif,
                  Valoareold,
                  DOC,
                  NRDOC,
                  DATADOC,
                  MONEDA,
                  SEDIU,
                  CURS,
                  VALDOC_N,
                  VALLEI_N,
                  DISCOUNT_N,
                  VALDOC_B,
                  VALLEI_B,
                  DISCOUNT_B,
                  CODOBIECT,
                  DENUMIRE,
                  CODDOCMASTER,
                  CODCLASEDISC,
                  CODNCREDIT1ORIG,
                  PROCTVA,
                  CODANALIZANOD,
                  CODCENTRU)
              with ValAfis as
                ( select coddoc, sum (valm)   VALM, sum (valm_b) VALM_B, tipdoc, ProcTVA
                  from (select I.CodIntr CODDOC, I1.Cant * I1.PretOrig * I1.Coefdiscmaj VALM, I1.Cant * I1.PretOrig VALM_B, 2  TIPDOC,
                                   PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT, 1) ProcTVA
                        from notecredit1      nc1
                          inner join INTRARI  I    on nc1.coddoc      = i.codintr and nc1.tipdoc = i.tipdoc
                          inner join intrari1 I1   on i.codintr       = i1.codintr
                          inner join nartobj  obj  on i1.codobiect    = obj.codobiect
                          INNER JOIN nart1 art1 ON art1.codarticol = obj.codarticol AND I.AN*12+I.LUNA BETWEEN art1.ALStart AND art1.ALStop
                          INNER JOIN ntva1 tva1 ON tva1.codtva = art1.codtva        AND I.AN*12+I.LUNA BETWEEN tva1.ALStart AND tva1.ALStop
                        where
                          I.DataDoc between vDataStart and vDataStop
                          and i1.codobiect &gt; 0
                          and I1.CodObiect not in (current_setting ('PKG_NOTECREDIT.KArtDiscPrimVol', true) ::numeric,
                                                   current_setting ('PKG_NOTECREDIT.KArtDiscPrimCant', true) ::numeric,
                                                   current_setting ('PKG_NOTECREDIT.KArtPenPrimTer', true) ::numeric,
                                                   current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceF', true) ::numeric)
                          AND INSTR(current_setting ('PKG_NOTECREDIT.KArtDiscPrimTer', true) , (I1.CODOBIECT)::varchar) = 0
                          and nc1.tip = current_setting ('PKG_NOTECREDIT.tncVolum', true) ::numeric
                          AND Coalesce(nc1.proctva,24) = PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT, 1)
                          and nc1.codncredit = RecId
                        union all
                        select I.CodIes CODDOC,
                              case
                                when i.tipdoc = 21 then (I1.Cant * i1.pretorig - I1.TVA) * coalesce (I1.CoefDiscMaj, 1)
                                else i1.cant * i1.pretorig * coalesce (I1.CoefDiscMaj, 1)
                              end VALM,
                              CASE when i.tipdoc = 21 then I1.Cant * i1.pretorig - I1.TVA else i1.cant * i1.pretorig end VALM_B,
                              1   TIPDOC,
                                   PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT, 1) ProcTVA
                        from notecredit1     nc1
                          inner join IESIRI  I    on nc1.coddoc      = i.codies and nc1.tipdoc = i.tipdoc
                          inner join iesiri1 I1   on i.codies        = i1.codies
                          inner join nartobj obj  on i1.codobiect    = obj.codobiect
                          INNER JOIN nart1 art1 ON art1.codarticol = obj.codarticol AND I.AN*12+I.LUNA BETWEEN art1.ALStart AND art1.ALStop
                          INNER JOIN ntva1 tva1 ON tva1.codtva = art1.codtva        AND I.AN*12+I.LUNA BETWEEN tva1.ALStart AND tva1.ALStop
                        where
                          I.DataDoc between vDataStart and vDataStop
                          and i1.codobiect &gt; 0
                          and (I1.CodObiect not in (current_setting ('PKG_NOTECREDIT.KArtDiscAcVol', true) ::numeric,
                                                    current_setting ('PKG_NOTECREDIT.KArtDiscAcCant', true) ::numeric,
                                                    current_setting ('PKG_NOTECREDIT.KArtPenAcTer', true) ::numeric,
                                                    current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceC', true) ::numeric)
                               and INSTR (current_setting ('PKG_NOTECREDIT.KArtDiscAcTer', true) , (I1.CODOBIECT) ::varchar) = 0)
                          and nc1.tip = current_setting ('PKG_NOTECREDIT.tncVolum', true) ::numeric
                          and nc1.codncredit = RecId
                          AND Coalesce(nc1.proctva,24) = PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT, 1)
                      ) J_PG
                  group BY coddoc, tipdoc, proctva
                )
              select NC1.CodNCredit1,
                NC1.CodNCredit,
                NC1.Valoare,
                NC1.CodObligStins,
                NC1.CodDoc,
                NC1.TipDoc,
                NC1.CodObligStingator,
                NC1.Obs,
                NC1.ValDif,
                NC1.Valoareold,
                I.PREFIXDOC     DOC,
                I.NRDOC         NRDOC,
                I.DATADOC       DATADOC,
                (select PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT from PKG_MONEDE_GET_SIMBOL_MONEDA (null, G.MONEDA)) MONEDA,
                A.OBS   SEDIU,
                CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end  CURS,
                round ( (V.ValM) ::numeric, 4) VALDOC,
                round ( (V.ValM * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end) ::numeric, 4) VALLEI,
                (select pkg_notecredit_GetDiscVolum.WME_RESULT from pkg_notecredit_GetDiscVolum (null, I.CodIntr, vCodContract, 2, RecID, 0, vCurs)) ,
                round ( (V.ValM_b) ::numeric, 4) VALDOC_B,
                round ( (V.ValM_b * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end) ::numeric, 4) VALLEI_B,
                (select pkg_notecredit_GetDiscVolum.WME_RESULT from pkg_notecredit_GetDiscVolum (null, I.CodIntr, vCodContract, 2, RecID, 1, vCurs)) ,
                0,
                '',
                I.CODINTR,
                NC1.CODCLASEDISC,
                NC1.CODNCREDIT1ORIG,
                coalesce (NC1.PROCTVA, v.proctva),
                NC1.CODANALIZANOD,
                NC1.CODCENTRU
              from NOTECREDIT1                      NC1
                inner join VALAFIS                  V    on NC1.CODDOC      = V.CODDOC  and v.tipdoc   = 2 and coalesce (nc1.proctva, 24) = v.proctva
                inner join INTRARI                  I    on NC1.Coddoc      = I.CodIntr and NC1.TipDoc = I.TipDoc
                left join general                   G    on I.CODINTR       = G.CODDOC  and I.TipDoc   = G.TipDoc
                left join TMP_CURS_REGULARIZAT_LUNA GREG on GREG.CODGENERAL = G.CODGENERAL
                left join NAGENDA                   A    on A.CODAGENDA     = I.CODLOCATIE
              where
                NC1.CodNCredit = RecId
                and NC1.Tip = current_setting ('PKG_NOTECREDIT.tncVolum', true) ::numeric
                and g.semnificatie &lt;&gt; 500
                and g.semnificatie &lt;&gt; 111
                and g.semnificatie &lt;&gt; 200
                and g.semnificatie &lt;&gt; 140
                and g.semnificatie &lt;&gt; 110
              union all
              select NC1.CodNCredit1,
                NC1.CodNCredit,
                NC1.Valoare,
                NC1.CodObligStins,
                NC1.CodDoc,
                NC1.TipDoc,
                NC1.CodObligStingator,
                NC1.Obs,
                NC1.ValDif,
                NC1.Valoareold,
                I.PREFIXDOC  DOC,
                I.NRDOC      NRDOC,
                I.DATADOC    DATADOC,
                (select PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT from PKG_MONEDE_GET_SIMBOL_MONEDA (null, G.MONEDA)) MONEDA,
                A.OBS  SEDIU,
                CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end  CURS,
                round ( (V.ValM) ::numeric, 4) VALDOC,
                round ( (V.ValM * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end) ::numeric, 4) VALLEI,
                (select pkg_notecredit_GetDiscVolum.WME_RESULT from pkg_notecredit_GetDiscVolum (null, I.CodIes, vCodContract, 1, RecId, 0, vCurs)) ,
                round ( (V.ValM_b) ::numeric, 4) VALDOC_B,
                round ( (V.ValM_b * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end) ::numeric, 4) VALLEI_B,
                (select pkg_notecredit_GetDiscVolum.WME_RESULT from pkg_notecredit_GetDiscVolum (null, I.CodIes, vCodContract, 1, RecId, 1, vCurs)) ,
                0,
                '',
                I.CODIES,
                NC1.CODCLASEDISC,
                NC1.CODNCREDIT1ORIG,
                NC1.PROCTVA,
                NC1.CODANALIZANOD,
                NC1.CODCENTRU
              from NOTECREDIT1                      NC1
                inner join IESIRI                   I    on NC1.Coddoc      = I.CodIes and NC1.TipDoc = I.TipDoc
                inner join VALAFIS                  V    on V.CODDOC        = I.CODIES and V.TIPDOC = 1 and coalesce (nc1.proctva, 24) = v.proctva
                left join general                   G    on I.CODIES        = G.CODDOC and I.TipDoc = G.TipDoc
                left join TMP_CURS_REGULARIZAT_LUNA GREG on GREG.CODGENERAL = G.CODGENERAL
                left join NAGENDA                   A    on A.CODAGENDA     = I.CODLOCATIE
              where
                NC1.CodNCredit = RecId
                and NC1.Tip = current_setting ('PKG_NOTECREDIT.tncVolum', true) ::numeric
                and G.Semnificatie = 200;
            else
              insert  into TMP_NOTECREDITV (
                  CodNCredit1,
                  CodNCredit,
                  Valoare,
                  CodObligStins,
                  CodDoc,
                  TipDoc,
                  CodObligStingator,
                  Obs,
                  ValDif,
                  Valoareold,
                  DOC,
                  NRDOC,
                  DATADOC,
                  MONEDA,
                  SEDIU,
                  CURS,
                  VALDOC_N,
                  VALLEI_N,
                  DISCOUNT_N,
                  VALDOC_B,
                  VALLEI_B,
                  DISCOUNT_B,
                  CODOBIECT,
                  DENUMIRE,
                  CODDOCMASTER,
                  CODCLASEDISC,
                  CODNCREDIT1ORIG,
                  PROCTVA,
                  CODANALIZANOD,
                  CODCENTRU)
              with ValAfis as
                ( select coddoc, sum (valm)   VALM, sum (valm_b) VALM_B, tipdoc, proctva
                  from (select I.CodIntr CODDOC, I1.Cant * I1.PretOrig * I1.Coefdiscmaj VALM, I1.Cant * I1.PretOrig VALM_B, 2 TIPDOC,
                                   PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT, 1) ProcTVA
                        from notecredit1      nc1
                          inner join INTRARI  I    on nc1.coddoc      = i.codintr and nc1.tipdoc = i.tipdoc
                          inner join intrari1 I1   on i.codintr       = i1.codintr
                          inner join nartobj  obj  on i1.codobiect    = obj.codobiect
                          INNER JOIN nart1 art1 ON art1.codarticol = obj.codarticol AND I.AN*12+I.LUNA BETWEEN art1.ALStart AND art1.ALStop
                          INNER JOIN ntva1 tva1 ON tva1.codtva = art1.codtva        AND I.AN*12+I.LUNA BETWEEN tva1.ALStart AND tva1.ALStop
                        where
                          I.DataDoc between vDataStart and vDataStop
                          and i1.codobiect &gt; 0
                          and I1.CodObiect not in (current_setting ('PKG_NOTECREDIT.KArtDiscPrimVol', true) ::numeric,
                                                   current_setting ('PKG_NOTECREDIT.KArtDiscPrimCant', true) ::numeric,
                                                   current_setting ('PKG_NOTECREDIT.KArtPenPrimTer', true) ::numeric,
                                                   current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceF', true) ::numeric)
                          AND INSTR(current_setting ('PKG_NOTECREDIT.KArtDiscPrimTer', true) , (I1.CODOBIECT)::varchar) = 0
                          and nc1.tip = current_setting ('PKG_NOTECREDIT.tncVolum', true) ::numeric
                          AND Coalesce(nc1.proctva,24) = PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT, 1)
                          and nc1.codncredit = RecId
                     ) K_PG
                  group BY coddoc, tipdoc, proctva
                )
              select NC1.CodNCredit1,
                NC1.CodNCredit,
                NC1.Valoare,
                NC1.CodObligStins,
                NC1.CodDoc,
                NC1.TipDoc,
                NC1.CodObligStingator,
                NC1.Obs,
                NC1.ValDif,
                NC1.Valoareold,
                I.PREFIXDOC     DOC,
                I.NRDOC         NRDOC,
                I.DATADOC       DATADOC,
                (select PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT from PKG_MONEDE_GET_SIMBOL_MONEDA (null, G.MONEDA)) MONEDA,
                A.OBS  SEDIU,
                CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end  CURS,
                round ( (V.ValM) ::numeric, 4) VALDOC,
                round ( (V.ValM * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end) ::numeric, 4) VALLEI,
                (select pkg_notecredit_GetDiscVolum.WME_RESULT from pkg_notecredit_GetDiscVolum (null, I.CodIntr, vCodContract, 2, RecID, 0, vCurs)) ,
                round ( (V.ValM_b) ::numeric, 4) VALDOC_B,
                round ( (V.ValM_b * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end) ::numeric, 4) VALLEI_B,
                (select pkg_notecredit_GetDiscVolum.WME_RESULT from pkg_notecredit_GetDiscVolum (null, I.CodIntr, vCodContract, 2, RecID, 1, vCurs)) ,
                0,
                '',
                I.CODINTR,
                NC1.CODCLASEDISC,
                NC1.CODNCREDIT1ORIG,
                coalesce (NC1.PROCTVA, v.proctva),
                NC1.CODANALIZANOD,
                NC1.CODCENTRU
              from NOTECREDIT1                      NC1
                inner join VALAFIS                  V    on NC1.CODDOC      = V.CODDOC  and v.tipdoc = 2 and coalesce (nc1.proctva, 24) = v.proctva
                inner join INTRARI                  I    on NC1.Coddoc      = I.CodIntr and NC1.TipDoc = I.TipDoc
                left join general                   G    on I.CODINTR       = G.CODDOC  and I.TipDoc = G.TipDoc
                left join TMP_CURS_REGULARIZAT_LUNA GREG on GREG.CODGENERAL = G.CODGENERAL
                left join NAGENDA                   A    on A.CODAGENDA     = I.CODLOCATIE
              where
                NC1.CodNCredit = RecId
                and NC1.Tip = current_setting ('PKG_NOTECREDIT.tncVolum', true) ::numeric
                and g.semnificatie &lt;&gt; 500
                and g.semnificatie &lt;&gt; 111
                and g.semnificatie &lt;&gt; 200
                and g.semnificatie &lt;&gt; 140
                and g.semnificatie &lt;&gt; 110;
            end if;
          else
            if vIesiriPeVolum = 1 then
              insert  into TMP_NOTECREDITV (
                  CodNCredit1,
                  CodNCredit,
                  Valoare,
                  CodObligStins,
                  CodDoc,
                  TipDoc,
                  CodObligStingator,
                  Obs,
                  ValDif,
                  Valoareold,
                  DOC,
                  NRDOC,
                  DATADOC,
                  MONEDA,
                  SEDIU,
                  CURS,
                  VALDOC_N,
                  VALLEI_N,
                  DISCOUNT_N,
                  VALDOC_B,
                  VALLEI_B,
                  DISCOUNT_B,
                  CODOBIECT,
                  DENUMIRE,
                  CODDOCMASTER,
                  CODCLASEDISC,
                  CODINTERN,
                  CODNCREDIT1ORIG,
                  PROCTVA,
                  CODANALIZANOD,
                  CODCENTRU)
              with ValAfis as
                ( select coddoc1, valm, valm_b, TipDoc
                  from (select I1.CodIntr1 CODDOC1, I1.Cant * I1.PretOrig * I1.Coefdiscmaj VALM, I1.Cant * I1.PretOrig VALM_B, 2  TIPDOC
                        from notecredit1      nc1
                          inner join INTRARI  I    on nc1.tipdoc      = i.tipdoc
                          inner join intrari1 I1   on i.codintr       = i1.codintr and nc1.coddoc = i1.codintr1
                          inner join nartobj  obj  on i1.codobiect    = obj.codobiect
                          INNER JOIN nart1 art1 ON art1.codarticol = obj.codarticol AND I.AN*12+I.LUNA BETWEEN art1.ALStart AND art1.ALStop
                          INNER JOIN ntva1 tva1 ON tva1.codtva = art1.codtva        AND I.AN*12+I.LUNA BETWEEN tva1.ALStart AND tva1.ALStop
                        where
                          I.DataDoc between vDataStart and vDataStop
                          and i1.codobiect &gt; 0
                          and I1.CodObiect not in (current_setting ('PKG_NOTECREDIT.KArtDiscPrimVol', true) ::numeric,
                                                   current_setting ('PKG_NOTECREDIT.KArtDiscPrimCant', true) ::numeric,
                                                   current_setting ('PKG_NOTECREDIT.KArtPenPrimTer', true) ::numeric,
                                                   current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceF', true) ::numeric)
                          AND INSTR(current_setting ('PKG_NOTECREDIT.KArtDiscPrimTer', true) , (I1.CODOBIECT)::varchar) = 0
                          and nc1.tip = current_setting ('PKG_NOTECREDIT.tncVolum', true) ::numeric
                          AND Coalesce(nc1.proctva,24) = PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT, 1)
                          and nc1.codncredit = RecId
                        union all
                        select I1.CodIes1 CODDOC1,
                              CASE when i.tipdoc = 21 then (I1.Cant * i1.pretorig - I1.TVA) * coalesce (I1.CoefDiscMaj, 1)
                                   else i1.cant * i1.pretorig * coalesce (I1.CoefDiscMaj, 1)
                              end VALM,
                              CASE when i.tipdoc = 21 then I1.Cant * i1.pretorig - I1.TVA
                                   else i1.cant * i1.pretorig
                              end VALM_B,
                              1  TIPDOC
                        from notecredit1     nc1
                          inner join IESIRI  I    on nc1.tipdoc      = i.tipdoc
                          inner join iesiri1 I1   on i.codies        = i1.codies and nc1.coddoc = i1.codies1
                          inner join nartobj obj  on i1.codobiect    = obj.codobiect
                          INNER JOIN nart1 art1 ON art1.codarticol = obj.codarticol AND I.AN*12+I.LUNA BETWEEN art1.ALStart AND art1.ALStop
                          INNER JOIN ntva1 tva1 ON tva1.codtva = art1.codtva        AND I.AN*12+I.LUNA BETWEEN tva1.ALStart AND tva1.ALStop
                        where
                          I.DataDoc between vDataStart and vDataStop
                          and i1.codobiect &gt; 0
                          and (I1.CodObiect not in (current_setting ('PKG_NOTECREDIT.KArtDiscAcVol', true) ::numeric,
                                                    current_setting ('PKG_NOTECREDIT.KArtDiscAcCant', true) ::numeric,
                                                    current_setting ('PKG_NOTECREDIT.KArtPenAcTer', true) ::numeric,
                                                    current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceC', true) ::numeric)
                          and INSTR (current_setting ('PKG_NOTECREDIT.KArtDiscAcTer', true) , (I1.CODOBIECT) ::varchar) = 0)
                          and nc1.tip = current_setting ('PKG_NOTECREDIT.tncVolum', true) ::numeric
                          and nc1.codncredit = RecId
                          AND Coalesce(nc1.proctva,24) = PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT, 1)
                          and nc1.codncredit = RecId
                          ) L_PG
                )
              select NC1.CodNCredit1,
                NC1.CodNCredit,
                NC1.Valoare,
                NC1.CodObligStins,
                NC1.CodDoc,
                NC1.TipDoc,
                NC1.CodObligStingator,
                NC1.Obs,
                NC1.ValDif,
                NC1.Valoareold,
                I.PREFIXDOC  DOC,
                I.NRDOC      NRDOC,
                I.DATADOC    DATADOC,
                (select PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT from PKG_MONEDE_GET_SIMBOL_MONEDA (null, G.MONEDA)) MONEDA,
                A.OBS  SEDIU,
                CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end  CURS,
                round ( (V.ValM) ::numeric, 4) VALDOC,
                round ( (V.ValM * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end) ::numeric, 4) VALLEI,
                (select pkg_notecredit_GetDiscVolum.WME_RESULT from pkg_notecredit_GetDiscVolum (null, NC1.CodDoc, vCodContract, 2, RecID, 0, vCurs)) ,
                round ( (V.ValM_b) ::numeric, 4) VALDOC_B,
                round ( (V.ValM_b * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end) ::numeric, 4) VALLEI_B,
                (select pkg_notecredit_GetDiscVolum.WME_RESULT from pkg_notecredit_GetDiscVolum (null, NC1.CodDoc, vCodContract, 2, RecID, 1, vCurs)) ,
                I1.CODOBIECT,
                OBJ.DENUMIRE,
                I.CODINTR,
                NC1.CODCLASEDISC,
                OBJ.CODINTERN,
                NC1.CODNCREDIT1ORIG,
                coalesce (NC1.PROCTVA, 24),
                NC1.CODANALIZANOD,
                NC1.CODCENTRU
              from NOTECREDIT1                      NC1
                inner join INTRARI                  I    on NC1.TipDoc      = I.TipDoc
                inner join INTRARI1                 I1   on NC1.Coddoc      = I1.CodIntr1 and I1.CodIntr = I.CodIntr
                inner join VALAFIS                  V    on I1.CODINTR1     = V.CODDOC1 and V.TIPDOC = 2
                inner join NARTOBJ                  OBJ  on OBJ.CodObiect   = I1.CodObiect
                left join general                   G    on I.CODINTR       = G.CODDOC and I.TipDoc = G.TipDoc
                left join TMP_CURS_REGULARIZAT_LUNA GREG on GREG.CODGENERAL = G.CODGENERAL
                left join NAGENDA                   A    on A.CODAGENDA     = I.CODLOCATIE
              where
                NC1.CodNCredit = RecId
                and NC1.Tip = current_setting ('PKG_NOTECREDIT.tncVolum', true) ::numeric
                and g.semnificatie &lt;&gt; 500
                and g.semnificatie &lt;&gt; 111
                and g.semnificatie &lt;&gt; 200
                and g.semnificatie &lt;&gt; 140
                and g.semnificatie &lt;&gt; 110
              union all
              select NC1.CodNCredit1,
                NC1.CodNCredit,
                NC1.Valoare,
                NC1.CodObligStins,
                NC1.CodDoc,
                NC1.TipDoc,
                NC1.CodObligStingator,
                NC1.Obs,
                NC1.ValDif,
                NC1.Valoareold,
                I.PREFIXDOC   DOC,
                I.NRDOC       NRDOC,
                I.DATADOC     DATADOC,
                (select PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT from PKG_MONEDE_GET_SIMBOL_MONEDA (null, G.MONEDA)) MONEDA,
                A.OBS  SEDIU,
                CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end  CURS,
                round ( (V.ValM) ::numeric, 4) VALDOC,
                round ( (V.ValM * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end) ::numeric, 4) VALLEI,
                (select pkg_notecredit_GetDiscVolum.WME_RESULT from pkg_notecredit_GetDiscVolum (null, I1.CodIes1, vCodContract, 1, RecId, 0, vCurs)) ,
                round ( (V.ValM_b) ::numeric, 4) VALDOC_B,
                round ( (V.ValM_b * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end) ::numeric, 4) VALLEI_B,
                (select pkg_notecredit_GetDiscVolum.WME_RESULT from pkg_notecredit_GetDiscVolum (null, I1.CodIes1, vCodContract, 1, RecId, 1, vCurs)) ,
                i1.codobiect,
                obj.denumire,
                I.CODIES,
                NC1.CODCLASEDISC,
                OBJ.CODINTERN,
                NC1.CODNCREDIT1ORIG,
                coalesce (NC1.PROCTVA, 24),
                NC1.CODANALIZANOD,
                NC1.CODCENTRU
              from NOTECREDIT1                      NC1
                inner join IESIRI1                  I1   on NC1.Coddoc      = I1.CodIes1
                inner join IESIRI                   I    on I1.CODIES       = I.CODIES and NC1.TipDoc = I.TipDoc
                inner join VALAFIS                  V    on V.CODDOC1       = I1.CODIES1 and V.TIPDOC = 1
                inner join NARTOBJ                  OBJ  on OBJ.CODOBIECT   = I1.CODOBIECT
                left join general                   G    on I.CODIES        = G.CODDOC and I.TipDoc = G.TipDoc
                left join TMP_CURS_REGULARIZAT_LUNA GREG on GREG.CODGENERAL = G.CODGENERAL
                left join NAGENDA                   A    on A.CODAGENDA     = I.CODLOCATIE
              where
                NC1.CodNCredit = RecId
                and NC1.Tip = current_setting ('PKG_NOTECREDIT.tncVolum', true) ::numeric
                and G.Semnificatie = 200;
            else
              insert  into TMP_NOTECREDITV (
                  CodNCredit1,
                  CodNCredit,
                  Valoare,
                  CodObligStins,
                  CodDoc,
                  TipDoc,
                  CodObligStingator,
                  Obs,
                  ValDif,
                  Valoareold,
                  DOC,
                  NRDOC,
                  DATADOC,
                  MONEDA,
                  SEDIU,
                  CURS,
                  VALDOC_N,
                  VALLEI_N,
                  DISCOUNT_N,
                  VALDOC_B,
                  VALLEI_B,
                  DISCOUNT_B,
                  CODOBIECT,
                  DENUMIRE,
                  CODDOCMASTER,
                  CODCLASEDISC,
                  CODINTERN,
                  CODNCREDIT1ORIG,
                  PROCTVA,
                  CODANALIZANOD,
                  CODCENTRU)
              with ValAfis as
                ( select codintr1, valm, valm_b
                  from (select I1.CodIntr1, I1.Cant * I1.PretOrig * I1.Coefdiscmaj VALM, I1.Cant * I1.PretOrig  VALM_B
                      from notecredit1      nc1
                        inner join INTRARI  I    on nc1.tipdoc      = i.tipdoc
                        inner join intrari1 I1   on i.codintr       = i1.codintr and nc1.coddoc = i1.codintr1
                        inner join nartobj  obj  on i1.codobiect    = obj.codobiect
                        INNER JOIN nart1 art1 ON art1.codarticol = obj.codarticol AND I.AN*12+I.LUNA BETWEEN art1.ALStart AND art1.ALStop
                        INNER JOIN ntva1 tva1 ON tva1.codtva = art1.codtva        AND I.AN*12+I.LUNA BETWEEN tva1.ALStart AND tva1.ALStop
                      where
                        I.DataDoc between vDataStart and vDataStop
                        and i1.codobiect &gt; 0
                        and I1.CodObiect not in (current_setting ('PKG_NOTECREDIT.KArtDiscPrimVol', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtDiscPrimCant', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtPenPrimTer', true) ::numeric,
                                                 current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceF', true) ::numeric)
                        AND INSTR(current_setting ('PKG_NOTECREDIT.KArtDiscPrimTer', true) , (I1.CODOBIECT)::varchar) = 0
                        and nc1.tip = current_setting ('PKG_NOTECREDIT.tncVolum', true) ::numeric
                        AND Coalesce(nc1.proctva,24) = PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT, 1)
                        and nc1.codncredit = RecId) M_PG
                )
              select NC1.CodNCredit1,
                NC1.CodNCredit,
                NC1.Valoare,
                NC1.CodObligStins,
                NC1.CodDoc,
                NC1.TipDoc,
                NC1.CodObligStingator,
                NC1.Obs,
                NC1.ValDif,
                NC1.Valoareold,
                I.PREFIXDOC   DOC,
                I.NRDOC       NRDOC,
                I.DATADOC     DATADOC,
                (select PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT from PKG_MONEDE_GET_SIMBOL_MONEDA (null, G.MONEDA)) MONEDA,
                A.OBS  SEDIU,
                CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end  CURS,
                round ( (V.ValM) ::numeric, 4) VALDOC,
                round ( (V.ValM * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end) ::numeric, 4) VALLEI,
                (select pkg_notecredit_GetDiscVolum.WME_RESULT from pkg_notecredit_GetDiscVolum (null, NC1.CodDoc, vCodContract, 2, RecID, 0, vCurs)) ,
                round ( (V.ValM_b) ::numeric, 4) VALDOC_B,
                round ( (V.ValM_b * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end) ::numeric, 4) VALLEI_B,
                (select pkg_notecredit_GetDiscVolum.WME_RESULT from pkg_notecredit_GetDiscVolum (null, NC1.CodDoc, vCodContract, 2, RecID, 1, vCurs)) ,
                I1.CODOBIECT,
                OBJ.DENUMIRE,
                I.CODINTR,
                NC1.CODCLASEDISC,
                OBJ.CODINTERN,
                NC1.CODNCREDIT1ORIG,
                coalesce (NC1.PROCTVA, 24),
                NC1.CODANALIZANOD,
                NC1.CODCENTRU
              from NOTECREDIT1                      NC1
                inner join INTRARI                  I    on NC1.TipDoc      = I.TipDoc
                inner join INTRARI1                 I1   on NC1.Coddoc      = I1.CodIntr1 and I1.CodIntr = I.CodIntr
                inner join VALAFIS                  V    on I1.CODINTR1     = V.CODINTR1
                inner join NARTOBJ                  OBJ  on OBJ.CodObiect   = I1.CodObiect
                left join general                   G    on I.CODINTR       = G.CODDOC and I.TipDoc = G.TipDoc
                left join TMP_CURS_REGULARIZAT_LUNA GREG on GREG.CODGENERAL = G.CODGENERAL
                left join NAGENDA                   A    on A.CODAGENDA     = I.CODLOCATIE
              where
                NC1.CodNCredit = RecId
                and NC1.Tip = current_setting ('PKG_NOTECREDIT.tncVolum', true) ::numeric
                and g.semnificatie &lt;&gt; 500
                and g.semnificatie &lt;&gt; 111
                and g.semnificatie &lt;&gt; 200
                and g.semnificatie &lt;&gt; 140
                and g.semnificatie &lt;&gt; 110;
            end if;
          end if;
        end if;
      end if;
      if vAreCorectii &gt; 0 then
        UPDATE tmp_notecreditv tmpv
        set valoare = valoare + coalesce ( (select sum (coalesce (valoare, 0) - coalesce (valoareold, 0)) from notecredit1 WHERE codncredit1orig = tmpv.codncredit1) , 0);
      end if;
    end if;

    begin
      select coalesce (PretBrutV, 0) INTO vPretBrutV from tmp_notecredit;
    exception
    when others then
      vPretBrutV := 0;
    end;

    if vPretBrutV = 1 then
      UPDATE tmp_notecreditv set ValDoc = ValDoc_b, ValLei = ValLei_b, Discount = Discount_b;
    else
      UPDATE tmp_notecreditv set ValDoc = ValDoc_N, ValLei = ValLei_N, Discount = Discount_N;
    end if;

    UPDATE tmp_notecreditv set procdisc = valoare / vallei * 100;
    UPDATE tmp_notecredit  set TotalDiscV = (select sum (valoare) from tmp_notecreditv);

    BEGIN
      select nvl(Previzionare,0) into vPrevizionare from tmp_notecredit;
      exception when others then vPrevizionare := 0;
    END;

    select count(*) INTO vCount from notecredit1 WHERE codncredit = recid and tip = current_setting ('PKG_NOTECREDIT.tncTermen', true) ::numeric;

    perform PKG_NOTECREDIT_MAKE_MANEVRA_T (vCodContract);
    if vCount &gt; 0 then
      if vTipDoc = 58 then
        if vValOrig &gt; 0 then
          insert  into TMP_NOTECREDITT (
              CODNCREDIT1,
              CODNCREDIT,
              VALOARE,
              CODOBLIGSTINS,
              CODDOC,
              TIPDOC,
              CODOBLIGSTINGATOR,
              Obs,
              ValDif,
              Valoareold,
              doc,
              Cont,
              Moneda,
              Termen,
              Subunitatea,
              Sediu,
              Curs,
              ValDoc,
              ValLei,
              ValPlata,
              DocPlata,
              ZilePlata,
              Discount,
              Articol,
              CodObiect,
              Cant,
              ValFaraTVA,
              CODCLASEDISC,
              ProcTVA,
              ValOrig,
              CODANALIZANOD,
              CODCENTRU )
            select NC1.CodNCredit1,
            NC1.CodNCredit,
            NC1.Valoare,
            NC1.CodObligStins,
            NC1.CodDoc,
            NC1.TipDoc,
            NC1.CodObligStingator,
            NC1.Obs,
            NC1.ValDif,
            NC1.Valoareold,
            coalesce (I.prefixdoc, '') || ' ' || coalesce (I.nrdoc::varchar , '') || '/' || coalesce (to_char (I.datadoc, 'dd.mm.yyyy') , '') ,
            (select PKG_LIST_BASE_UTILS_decode_iCont.WME_RESULT from PKG_LIST_BASE_UTILS_decode_iCont (null, obstins.icont, obstins.codpart, i.an * 12 + i.luna, obstins.semnificatie)) ,
            (select PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT from PKG_MONEDE_GET_SIMBOL_MONEDA (null, coalesce (gstins.MONEDA, 0))) ,
            obstins.termen,
            i.subunitatea,
            A.Obs,
            CASE when coalesce (GREG.CURS, GSTINS.CURS) = 0 then 1 else coalesce (GREG.CURS, GSTINS.CURS) end ,
            CASE when i.tipdoc = 21 then i1.pretorig * i1.cant else i1.pretorig * i1.cant + i1.tva end ,
            round ( (CASE when i.tipdoc = 21 then i1.pretorig * i1.cant else i1.pretorig * i1.cant + i1.tva end
                     *
                     CASE when coalesce (GREG.CURS, GSTINS.CURS) = 0 then 1 else coalesce (GREG.CURS, GSTINS.CURS) end)
              ::numeric, 4)
            ,
            CASE when (select pkg_notecredit_IsCumulat.WME_RESULT from pkg_notecredit_IsCumulat (null, i1.codies1, C.CODCONTRACT, 1)) = 1
                   THEN CASE when i.tipdoc = 21 then i1.pretorig * i1.cant else i1.pretorig * i1.cant + i1.tva END
                   else sign(obstins.valoare) * stingere.valoare *
                   case when coalesce(i.valdoc,0)=0 then 0 else ---razvan
                   (case when i.tipdoc = 21 then i1.pretorig*i1.cant else i1.pretorig*i1.cant+i1.tva end) / i.valdoc end
            END ,
            CASE when (select pkg_notecredit_IsCumulat.WME_RESULT from pkg_notecredit_IsCumulat (null, i1.codies1, C.CODCONTRACT, 1)) = 1 then 'TOTAL CUMULAT'
                 else CASE when gstingator.tipdoc = 28 then coalesce ('PV' || ' ', '') || coalesce (comp.nrdoc::varchar , '') || '/' || coalesce (to_char (comp.datadoc, 'dd.mm.yyyy') , '')
                           else coalesce (t1.doc, '') || ' ' || coalesce (t1.nrdoc::varchar , '') || '/' || coalesce (to_char (t1.datadoc, 'dd.mm.yyyy') , '')
                      END
            END ,
            coalesce (T1.Datadoc, COMP.datadoc) - I.Datadoc::DATE,
            (select pkg_notecredit_GETDISCTERMENCLI.WME_RESULT
             from pkg_notecredit_GETDISCTERMENCLI (null, to_char (coalesce (T1.Datadoc, COMP.datadoc) , 'DD.MM.YYYY') ,
                                                   coalesce (T1.Datadoc, COMP.datadoc) - I.Datadoc, C.CODCONTRACT, I1.CodIes1,
                                                   CASE when gstingator.tipdoc = 28 and obstins.valoare &lt; 0 then - stingere.valoare else stingere.valoare end)) ,
            OBJ.Denumire,
            I1.CodObiect,
            I1.Cant,
            CASE when i.tipdoc = 21 then i1.pretorig * i1.cant - i1.TVA else i1.pretorig * i1.cant end ,
            NC1.CODCLASEDISC,
            coalesce (NC1.PROCTVA, 24) ,
            CASE when i.tipdoc = 21 then i1.pretorig * i1.cant * i1.coefdiscmaj else i1.pretorig * i1.cant * i1.coefdiscmaj + i1.tva END,
            NC1.CODANALIZANOD,
            NC1.CODCENTRU,
            TO_DATE(TMP.VALOARE2,'DD.MM.YYYY')
          from NOTECREDIT1      NC1
            inner join IESIRI1  I1          on NC1.CodDoc             = I1.CodIes1
            inner join NARTOBJ  OBJ         on I1.CodObiect           = OBJ.CodObiect
            inner join IESIRI   I           on I1.CodIes              = I.CodIes and I.TIPDOC = NC1.TIPDOC
            inner join general  GSTINS      on I.CodIes               = GSTINS.CodDoc and I.TipDoc = GSTINS.TipDoc
            INNER JOIN OBLIGPIF obstins     on NC1.CODOBLIGSTINS      = obstins.codobligpif and gstins.codgeneral = obstins.codgeneral
            left join OBLIGPIF  obstingator on NC1.CODOBLIGSTINGATOR  = obstingator.codobligpif
            left join stingere              on stingere.codstinspif   = obstins.codobligpif and stingere.codstingatorpif = obstingator.codobligpif
            left join general GSTINGATOR    on obstingator.codgeneral = GSTINGATOR.CODGENERAL
            left join (select TT1.DOC, TT1.NRDOC, TT1.DATADOC, TT1.CODTREZOR1, TT.TIPDOC
                       from TREZOR1 TT1 inner join TREZOR TT on TT.CODTREZOR = TT1.CODTREZOR
                      ) T1 on T1.CODTREZOR1 = GSTINGATOR.CODDOC and T1.TIPDOC = GSTINGATOR.TIPDOC
            left join (select c.datadoc, c.nrdoc, c.codcompens, 28  TIPDOC from compens c) comp on comp.codcompens = gstingator.coddoc and comp.tipdoc = gstingator.tipdoc
            left join NAGENDA                      A       on I.CODLOCATIE = A.CODAGENDA
            left join TMP_CURS_REGULARIZAT_LUNA    GREG    on GREG.CODGENERAL = GSTINS.CODGENERAL
            left join NOTECREDIT                   NC      on NC1.CODNCREDIT = NC.CODNCREDIT
            left join CONTRACT                     C       on NC.CODCONTRACT = C.CODCONTRACT
            LEFT JOIN TMP_MANEVRA_LISTE            TMP     ON TMP.FILTRU     = 'CODOBIECT' AND TMP.FILTRU1 = 'TERMENFIX' AND TO_NUMBER(TMP.VALOARE) = OBJ.CODOBIECT AND case when vPrevizionare = 1 then I.DATADOC ELSE COALESCE(T1.Datadoc, COMP.datadoc) END BETWEEN TO_DATE(TMP.VALOARE1,'DD.MM.YYYY') AND TO_DATE(TMP.VALOARE2,'DD.MM.YYYY')
          where
            gstins.semnificatie &lt;&gt; 240
            and gstins.semnificatie &lt;&gt; 500
            and gstins.semnificatie &lt;&gt; 211
            and gstins.semnificatie &lt;&gt; 210
            and NC1.CodNCredit = RecId
            and NC1.Tip = current_setting ('PKG_NOTECREDIT.tncTermen', true) ::numeric;
        else
          insert  into TMP_NOTECREDITT (
              CODNCREDIT1,
              CODNCREDIT,
              VALOARE,
              CODOBLIGSTINS,
              CODDOC,
              TIPDOC,
              CODOBLIGSTINGATOR,
              Obs,
              ValDif,
              Valoareold,
              doc,
              Cont,
              Moneda,
              Termen,
              Subunitatea,
              Sediu,
              Curs,
              ValDoc,
              ValLei,
              ValPlata,
              DocPlata,
              ZilePlata,
              Discount,
              Articol,
              CodObiect,
              Cant,
              ValFaraTVA,
              CODCLASEDISC,
              ProcTVA,
              ValOrig,
              CODANALIZANOD,
              CODCENTRU,
              TERMENFIX)
          select NC1.CodNCredit1,
            NC1.CodNCredit,
            NC1.Valoare,
            NC1.CodObligStins,
            NC1.CodDoc,
            NC1.TipDoc,
            NC1.CodObligStingator,
            NC1.Obs,
            NC1.ValDif,
            NC1.Valoareold,
            coalesce (I.prefixdoc, '') || ' ' || coalesce (I.nrdoc::varchar , '') || '/' || coalesce (to_char (I.datadoc, 'dd.mm.yyyy') , '') ,
            (select PKG_LIST_BASE_UTILS_decode_iCont.WME_RESULT from PKG_LIST_BASE_UTILS_decode_iCont (null, obstins.icont, obstins.codpart, i.an * 12 + i.luna, obstins.semnificatie)) ,
            (select PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT from PKG_MONEDE_GET_SIMBOL_MONEDA (null, coalesce (gstins.MONEDA, 0))) ,
            obstins.termen,
            i.subunitatea,
            A.Obs,
            CASE when coalesce (GREG.CURS, GSTINS.CURS) = 0 then 1 else coalesce (GREG.CURS, GSTINS.CURS) end ,
            CASE when i.tipdoc = 21 then i1.pretorig * i1.cant * i1.coefdiscmaj else i1.pretorig * i1.cant * i1.coefdiscmaj + i1.tva end ,
            round ( (CASE when i.tipdoc = 21 then i1.pretorig * i1.cant * i1.coefdiscmaj else i1.pretorig * i1.cant * i1.coefdiscmaj + i1.tva end
                      *
                     CASE when coalesce (GREG.CURS, GSTINS.CURS) = 0 then 1 else coalesce (GREG.CURS, GSTINS.CURS) end)
              ::numeric, 4),
            CASE when (select pkg_notecredit_IsCumulat.WME_RESULT from pkg_notecredit_IsCumulat (null, i1.codies1, C.CODCONTRACT, 1)) = 1
                   THEN CASE when i.tipdoc = 21 then i1.pretorig * i1.cant * i1.coefdiscmaj else i1.pretorig * i1.cant * i1.coefdiscmaj + i1.tva END
                   else sign(obstins.valoare) * stingere.valoare *
                     (case when coalesce(i.valdoc,0)=0 then 0 else ---razvan,
                     (case when i.tipdoc = 21 then i1.pretorig*i1.cant*i1.coefdiscmaj else i1.pretorig*i1.cant*i1.coefdiscmaj+i1.tva end) / i.valdoc end)
            end ,
            CASE when (select pkg_notecredit_IsCumulat.WME_RESULT from pkg_notecredit_IsCumulat (null, i1.codies1, C.CODCONTRACT, 1)) = 1 then 'TOTAL CUMULAT'
                 else CASE when gstingator.tipdoc = 28 then coalesce ('PV' || ' ', '') || coalesce (comp.nrdoc::varchar , '') || '/' || coalesce (to_char (comp.datadoc, 'dd.mm.yyyy') , '')
                           else coalesce (t1.doc, '') || ' ' || coalesce (t1.nrdoc::varchar , '') || '/' || coalesce (to_char (t1.datadoc, 'dd.mm.yyyy') , '')
                      END
            END ,
            coalesce (T1.Datadoc, COMP.datadoc) - I.Datadoc::DATE,
            (select pkg_notecredit_GETDISCTERMENCLI.WME_RESULT
             from pkg_notecredit_GETDISCTERMENCLI (null, to_char (coalesce (T1.Datadoc, COMP.datadoc) , 'DD.MM.YYYY') ,
                                                   coalesce (T1.Datadoc, COMP.datadoc) - I.Datadoc, C.CODCONTRACT, I1.CodIes1,
                                                   CASE when gstingator.tipdoc = 28 and obstins.valoare &lt; 0 then - stingere.valoare else stingere.valoare end)) ,
            OBJ.Denumire,
            I1.CodObiect,
            I1.Cant,
            CASE when i.tipdoc = 21 then (i1.pretorig * i1.cant) * i1.coefdiscmaj - i1.TVA else (i1.pretorig * i1.cant) * i1.coefdiscmaj end ,
            NC1.CODCLASEDISC,
            coalesce (NC1.PROCTVA, 24) ,
            CASE when i.tipdoc = 21 then i1.pretorig * i1.cant * i1.coefdiscmaj else i1.pretorig * i1.cant * i1.coefdiscmaj + i1.tva END,
            NC1.CODANALIZANOD,
            NC1.CODCENTRU,
            TO_DATE(TMP.VALOARE2,'DD.MM.YYYY')
          from NOTECREDIT1      NC1
            inner join IESIRI1  I1          on NC1.CodDoc             = I1.CodIes1
            inner join NARTOBJ  OBJ         on I1.CodObiect           = OBJ.CodObiect
            inner join IESIRI   I           on I1.CodIes              = I.CodIes and I.TIPDOC = NC1.TIPDOC
            inner join general  GSTINS      on I.CodIes               = GSTINS.CodDoc and I.TipDoc = GSTINS.TipDoc
            INNER JOIN OBLIGPIF obstins     on NC1.CODOBLIGSTINS      = obstins.codobligpif and gstins.codgeneral = obstins.codgeneral
            left join OBLIGPIF  obstingator on NC1.CODOBLIGSTINGATOR  = obstingator.codobligpif
            left join stingere              on stingere.codstinspif   = obstins.codobligpif and stingere.codstingatorpif = obstingator.codobligpif
            left join general GSTINGATOR    on obstingator.codgeneral = GSTINGATOR.CODGENERAL
            left join (select TT1.DOC, TT1.NRDOC, TT1.DATADOC, TT1.CODTREZOR1, TT.TIPDOC
                       from TREZOR1 TT1 inner join TREZOR TT on TT.CODTREZOR = TT1.CODTREZOR
                      ) T1 on T1.CODTREZOR1 = GSTINGATOR.CODDOC and T1.TIPDOC = GSTINGATOR.TIPDOC
            left join (select c.datadoc, c.nrdoc, c.codcompens, 28  TIPDOC from compens c) comp on comp.codcompens = gstingator.coddoc and comp.tipdoc = gstingator.tipdoc
            left join NAGENDA                      A       on I.CODLOCATIE    = A.CODAGENDA
            left join TMP_CURS_REGULARIZAT_LUNA    GREG    on GREG.CODGENERAL = GSTINS.CODGENERAL
            left join NOTECREDIT                   NC      on NC1.CODNCREDIT  = NC.CODNCREDIT
            left join CONTRACT                     C       on NC.CODCONTRACT  = C.CODCONTRACT
            LEFT JOIN TMP_MANEVRA_LISTE            TMP     ON TMP.FILTRU      = 'CODOBIECT' AND TMP.FILTRU1 = 'TERMENFIX' AND TO_NUMBER(TMP.VALOARE) = OBJ.CODOBIECT AND case when vPrevizionare = 1 then I.DATADOC ELSE COALESCE(T1.Datadoc, COMP.datadoc) END BETWEEN TO_DATE(TMP.VALOARE1,'DD.MM.YYYY') AND TO_DATE(TMP.VALOARE2,'DD.MM.YYYY')
          where
            gstins.semnificatie &lt;&gt; 240
            and gstins.semnificatie &lt;&gt; 500
            and gstins.semnificatie &lt;&gt; 211
            and gstins.semnificatie &lt;&gt; 210
            and NC1.CodNCredit = RecId
            and NC1.Tip = current_setting ('PKG_NOTECREDIT.tncTermen', true) ::numeric;
        end if;
      else
        insert  into TMP_NOTECREDITT (
            CODNCREDIT1,
            CODNCREDIT,
            VALOARE,
            CODOBLIGSTINS,
            CODDOC,
            TIPDOC,
            CODOBLIGSTINGATOR,
            Obs,
            ValDif,
            Valoareold,
            doc,
            Cont,
            Moneda,
            Termen,
            Subunitatea,
            Sediu,
            Curs,
            ValDoc,
            ValLei,
            ValPlata,
            DocPlata,
            ZilePlata,
            Discount,
            Articol,
            CodObiect,
            Cant,
            ValFaraTVA,
            CODCLASEDISC,
            ProcTVA,
            CODANALIZANOD,
            CODCENTRU,
            TERMENFIX)
        select NC1.CodNCredit1,
          NC1.CodNCredit,
          NC1.Valoare,
          NC1.CodObligStins,
          NC1.CodDoc,
          NC1.TipDoc,
          NC1.CodObligStingator,
          NC1.Obs,
          NC1.ValDif,
          NC1.Valoareold,
          coalesce (I.prefixdoc, '') || ' ' || coalesce (I.nrdoc::varchar , '') || '/' || coalesce (to_char (I.datadoc, 'dd.mm.yyyy') , '') ,
          (select PKG_LIST_BASE_UTILS_decode_iCont.WME_RESULT from PKG_LIST_BASE_UTILS_decode_iCont (null, obstins.icont, obstins.codpart, i.an * 12 + i.luna, obstins.semnificatie)) ,
          (   select PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT from PKG_MONEDE_GET_SIMBOL_MONEDA (null, coalesce (gstins.MONEDA, 0))) ,
          obstins.termen,
          i.subunitatea,
          A.Obs,
          CASE when coalesce (GREG.CURS, GSTINS.CURS) = 0 then 1 else coalesce (GREG.CURS, GSTINS.CURS) end ,
          i1.pu * i1.cant + i1.tva,
          round ( ( (i1.pu * i1.cant + i1.tva) * CASE when coalesce (GREG.CURS, GSTINS.CURS) = 0 then 1 else coalesce (GREG.CURS, GSTINS.CURS) end) ::numeric, 4) ,
          CASE when (select pkg_notecredit_IsCumulat.WME_RESULT from pkg_notecredit_IsCumulat (null, i1.codintr1, C.CODCONTRACT, 2)) = 1 then i1.pu * i1.cant + i1.tva
               when coalesce(i.valdoc,0)=0 then 0 ---razvan
               else sign (obstins.valoare) * stingere.valoare * (i1.pu * i1.cant + i1.tva) / i.valdoc
          END ,
          CASE when (select pkg_notecredit_IsCumulat.WME_RESULT from pkg_notecredit_IsCumulat (null, i1.codintr1, C.CODCONTRACT, 2)) = 1 then 'TOTAL CUMULAT'
               else CASE when gstingator.tipdoc = 28 then coalesce ('PV' || ' ', '') || coalesce (comp.nrdoc::varchar , '') || '/' || coalesce (to_char (comp.datadoc, 'dd.mm.yyyy') , '')
                         else coalesce (t1.doc, '') || ' ' || coalesce (t1.nrdoc::varchar , '') || '/' || coalesce (to_char (t1.datadoc, 'dd.mm.yyyy') , '')
                    END
          END ,
          coalesce (T1.Datadoc, comp.datadoc) - I.Datadoc::DATE,
          (select pkg_notecredit_GETDISCTERMENFURN.WME_RESULT
           from pkg_notecredit_GETDISCTERMENFURN (null, to_char (coalesce (T1.Datadoc, comp.datadoc) , 'DD.MM.YYYY') ,
                                                  coalesce (T1.Datadoc, comp.datadoc) - I.Datadoc, C.CODCONTRACT, I1.CodIntr1,
                                                  CASE when gstingator.tipdoc = 28 and obstins.valoare &lt; 0 then - stingere.valoare else stingere.valoare end)) ,
          OBJ.Denumire,
          I1.CodObiect,
          I1.Cant,
          i1.pretorig * i1.cant * i1.coefdiscmaj,
          NC1.CODCLASEDISC,
          coalesce (NC1.PROCTVA, 24),
          NC1.CODANALIZANOD,
          NC1.CODCENTRU,
          TO_DATE(TMP.VALOARE2,'DD.MM.YYYY')
        from NOTECREDIT1      NC1
          inner join INTRARI1 I1          on NC1.CodDoc             = I1.CodIntr1
          inner join NARTOBJ  OBJ         on I1.CodObiect           = OBJ.CodObiect
          inner join INTRARI  I           on I1.CodIntr             = I.CodIntr and NC1.TIPDOC = I.TIPDOC
          inner join general  GSTINS      on I.CodIntr              = GSTINS.CodDoc and I.TipDoc = GSTINS.TipDoc
          INNER JOIN OBLIGPIF obstins     on NC1.CODOBLIGSTINS      = obstins.codobligpif and gstins.codgeneral = obstins.codgeneral
          left join OBLIGPIF  obstingator on NC1.CODOBLIGSTINGATOR  = obstingator.codobligpif
          left join stingere              on stingere.codstinspif   = obstins.codobligpif and stingere.codstingatorpif = obstingator.codobligpif
          left join general GSTINGATOR    on obstingator.codgeneral = GSTINGATOR.CODGENERAL
          left join (select TT1.DOC, TT1.NRDOC, TT1.DATADOC, TT1.CODTREZOR1, TT.TIPDOC
                     from TREZOR1 TT1 inner join TREZOR TT on TT.CODTREZOR = TT1.CODTREZOR
                    ) T1 on T1.CODTREZOR1 = GSTINGATOR.CODDOC and T1.TIPDOC = GSTINGATOR.TIPDOC
          left join (select c.datadoc, c.nrdoc, c.codcompens, 28 TIPDOC from compens c) comp on comp.codcompens = gstingator.coddoc and comp.tipdoc = gstingator.tipdoc
          left join NAGENDA                      A       on I.CODLOCATIE    = A.CODAGENDA
          left join TMP_CURS_REGULARIZAT_LUNA    GREG    on GREG.CODGENERAL = GSTINS.CODGENERAL
          left join NOTECREDIT                   NC      on NC1.CODNCREDIT  = NC.CODNCREDIT
          left join CONTRACT                     C       on NC.CODCONTRACT  = C.CODCONTRACT
          LEFT JOIN TMP_MANEVRA_LISTE            TMP     ON TMP.FILTRU      = 'CODOBIECT' AND TMP.FILTRU1 = 'TERMENFIX' AND TO_NUMBER(TMP.VALOARE) = OBJ.CODOBIECT AND case when vPrevizionare = 1 then I.DATADOC ELSE COALESCE(T1.Datadoc, COMP.datadoc) END BETWEEN TO_DATE(TMP.VALOARE1,'DD.MM.YYYY') AND TO_DATE(TMP.VALOARE2,'DD.MM.YYYY')
        where
          gstins.semnificatie &lt;&gt; 140
          and gstins.semnificatie &lt;&gt; 600
          and gstins.semnificatie &lt;&gt; 130
          and NC1.CodNCredit = RecId
          and NC1.Tip = current_setting ('PKG_NOTECREDIT.tncTermen', true) ::numeric;
      end if;
    end if;

    if vCodContract &gt; 0 then
      DELETE from tmp_notecreditt WHERE discount = 0;

      UPDATE TMP_NOTECREDITT T
      set PREVIZIONAT = (select coalesce (PREVIZIONAT, 0) from TMP_NOTECREDIT1 WHERE CODNCREDIT1 = T.CODNCREDIT1);
    end if;

    --if vPrevizionare = 1 then
      UPDATE tmp_notecreditt set discount = previzionat, valoare = previzionat;
    --end if;

    select count(*) INTO vCount from notecredit1 WHERE codncredit = recid and tip = current_setting ('PKG_NOTECREDIT.tncCantitate', true) ::numeric;

    if vCount &gt; 0 then
      if vTipDoc = 58 then
        if vCodContract &gt; 0 THEN
         vTotCant := 0;
     begin
       select
         sum(i1.cant) totalcant into vTotCant
       from notecredit1 nc1
             inner join notecredit nc on nc.codncredit = nc1.codncredit
             inner join iesiri1 i1 on nc1.coddoc = i1.codies1
             inner join iesiri   i on i1.codies    = i.codies
             left join contract1 c1 on c1.codcontract1 = pkg_contract_GetCodContract1(i1.codobiect, i.datadoc, vCodContract)
             left join contract c on c1.codcontract = c.codcontract
       where (coalesce(i.anulat, 0) = 0)
              and nc.codcontract = vCodContract
              and nc1.tip = tncCantitate and nc1.codncredit = RecId
              and (nc.corectie = 1 or I.Datadoc between vDataStart and vDataStop)
              AND (I1.CodObiect not in (KArtDiscAcVol,KArtDiscAcCant,KArtPenAcTer,KArtDiscOffInvoiceC) AND INSTR(KArtDiscAcTer, TO_CHAR(I1.CODOBIECT)) = 0);
       exception when others then vTotCant := 0;
     end;
          insert into TMP_NOTECREDITC (
              CodNCredit1,
              CodNCredit,
              Valoare,
              CodObligStins,
              CodDoc,
              TipDoc,
              CodObligStingator,
              Obs,
              ValDif,
              Valoareold,
              ARTICOL,
              CANT,
              DOC,
              MONEDA,
              SEDIU,
              CURS,
              CODOBIECT,
              PROCDISC,
              PRET_N,
              PRET_B,
              VAL_N,
              VAL_B,
              VALLEI_N,
              VALLEI_B,
              DISCOUNT_N,
              DISCOUNT_B,
              ValFaraTVA_N,
              ValFaraTVA_B,
              CODCLASEDISC,
              CODINTERN,
              PROCTVA,
              OBSNAV,
              CODANALIZANOD,
              CODCENTRU)
          with CumulCant as
            (select i1.codobiect, sum (i1.cant) TOTALCANT, c1.codcontract1,
                sum (
                  case
                    when i.tipdoc = 21 then (i1.PretOrig * i1.cant * coalesce (i1.coefdiscmaj, 1) - i1.PretOrig * i1.cant * coalesce (i1.coefdiscmaj, 1)
                                             * (select pkg_list_base_utils_get_cota_tva_art.WME_RESULT
                                                from   pkg_list_base_utils_get_cota_tva_art (null, i1.codobiect, i.an, i.luna)
                                               ) / 100)
                    else i1.PretOrig * i1.cant * coalesce (i1.coefdiscmaj, 1)
                  end)
                / sum (i1.cant) PRETMEDIU,
                sum (
                  case
                    when i.tipdoc = 21 then (i1.PretOrig * i1.cant - i1.PretOrig * i1.cant
                                             * (select pkg_list_base_utils_get_cota_tva_art.WME_RESULT
                                                from   pkg_list_base_utils_get_cota_tva_art (null, i1.codobiect, i.an, i.luna)
                                               ) / 100)
                    else i1.PretOrig * i1.cant
                  end)
                / sum (i1.cant)      PRETMEDIU_B
              from notecredit1       nc1
                inner join notecredit nc on nc.codncredit = nc1.codncredit
                inner join iesiri1   i1 on nc1.coddoc      = i1.codies1
                inner join iesiri    i  on i1.codies       = i.codies
                left join  contract1 c1 on c1.codcontract1 = (select PKG_NOTECREDIT_GetCodContract1.WME_RESULT from PKG_NOTECREDIT_GetCodContract1 (null, i1.codobiect, i.datadoc, vCodContract))
                left join  contract c   on c1.codcontract = c.codcontract
              where
                (coalesce (i.anulat, 0) = 0)
                and nc.codcontract = vCodContract
                and nc1.tip = current_setting ('PKG_NOTECREDIT.tncCantitate', true) ::numeric
                and nc1.codncredit = RecId
                and (nc.corectie = 1 or I.Datadoc between vDataStart and vDataStop)
                and (I1.CodObiect not in (current_setting ('PKG_NOTECREDIT.KArtDiscAcVol', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtDiscAcCant', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtPenAcTer', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceC', true) ::numeric)
                     and INSTR (current_setting ('PKG_NOTECREDIT.KArtDiscAcTer', true) , (I1.CODOBIECT) ::varchar) = 0)
              group BY i1.codobiect, c1.codcontract1
            )
          select NC1.CodNCredit1, NC1.CodNCredit, NC1.Valoare, CASE when coalesce (NC1.CodObligStins, 0) = 0 then g.codgeneral else NC1.CodObligStins end ,
            NC1.CodDoc,
            NC1.TipDoc,
            NC1.CodObligStingator,
            NC1.Obs,
            NC1.ValDif,
            NC1.Valoareold,
            OBJ.Denumire ARTICOL,
            I1.cant,
            coalesce (i.prefixdoc, '') || ' ' || coalesce (i.nrdoc::varchar , '') || '/' || coalesce (to_char (i.datadoc, 'dd.mm.yyyy') , '') DOC,
            (select PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT from PKG_MONEDE_GET_SIMBOL_MONEDA (null, coalesce (g.MONEDA, 0))) MONEDA,
            A.obs  SEDIU,
            CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end CURS,
            i1.codobiect,
            0,
            CASE when i.tipdoc = 21 then round ( ( (I1.Pretorig * i1.cant * i1.coefdiscmaj - i1.tva) / i1.cant) ::numeric, 2)
                 else i1.pretorig * i1.coefdiscmaj
            end PRET,
            CASE when i.tipdoc = 21 then round ( ( (I1.Pretorig * i1.cant - i1.tva) / i1.cant) ::numeric, 2) else i1.pretorig end PRET_B,
            CASE when i.tipdoc = 21 then (I1.cant * I1.Pretorig) * i1.coefdiscmaj - i1.tva else I1.cant * I1.Pretorig * i1.coefdiscmaj end VAL,
            CASE when i.tipdoc = 21 then (I1.cant * I1.Pretorig - i1.tva) else I1.cant * I1.Pretorig end VAL_B,
            CASE when i.tipdoc = 21 then (I1.cant * I1.Pretorig) * i1.coefdiscmaj - i1.tva else I1.cant * I1.Pretorig * i1.coefdiscmaj end
             * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end VALLEI,
            CASE when i.tipdoc = 21 then (I1.cant * I1.Pretorig - i1.tva) else I1.cant * I1.Pretorig end
             * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end VALLEI_B,
            round ((SELECT wme_result FROM pkg_notecredit_GetDiscCant(NULL, I1.cant, case when i.tipdoc = 21 then (I1.cant * I1.Pretorig)*i1.coefdiscmaj - i1.tva else I1.cant * I1.Pretorig * i1.coefdiscmaj end,CumulCant.totalcant,CumulCant.codcontract1,CUmulCant.pretmediu, vTotCant, vCurs))::numeric, 2),
            round ((SELECT wme_result FROM pkg_notecredit_GetDiscCant(NULL, I1.cant, case when i.tipdoc = 21 then (I1.cant * I1.Pretorig - i1.tva) else I1.cant * I1.Pretorig end,CumulCant.totalcant,CumulCant.codcontract1,CUmulCant.pretmediu_b, vTotCant, vCurs))::NUMERIC, 2),
            CASE when i.tipdoc = 21 then (I1.Pretorig * i1.cant * i1.coefdiscmaj - i1.tva) else i1.Pretorig * i1.Cant * i1.coefdiscmaj end ,
            CASE when i.tipdoc = 21 then (I1.Pretorig * i1.cant - i1.tva) else i1.Pretorig * i1.Cant end ,
            NC1.CODCLASEDISC,
            OBJ.CODINTERN,
            coalesce (NC1.PROCTVA, 24) ,
            NC1.OBSNAV,
            NC1.CODANALIZANOD,
            NC1.CODCENTRU
          from NOTECREDIT1     NC1
            inner join iesiri1 i1 on nc1.coddoc   = i1.codies1
            inner join iesiri  i  on i1.codies    = i.codies and I.TIPDOC = NC1.TIPDOC
            inner join CumulCant  on i1.codobiect = CumulCant.codobiect
                                                    and CumulCant.CodContract1 = (select PKG_NOTECREDIT_GETCODCONTRACT1.WME_RESULT
                                                                                  from   PKG_NOTECREDIT_GETCODCONTRACT1 (null, i1.codobiect, i.datadoc, vCodContract))
            inner join general g    on g.coddoc     = i.codies and g.tipdoc = i.tipdoc and g.semnificatie not in (500, 240, 211, 100, 140, 400)
            inner join NARTOBJ OBJ  on I1.CodObiect = OBJ.Codobiect
            left join NAGENDA  A    on A.codagenda  = i.codlocatie
            left join TMP_CURS_REGULARIZAT_LUNA GREG on GREG.CODGENERAL = G.CODGENERAL
          where
            NC1.CodNCredit = RecId
            and NC1.Tip = current_setting ('PKG_NOTECREDIT.tncCantitate', true) ::numeric;
        else
          insert  into TMP_NOTECREDITC (
              CodNCredit1,
              CodNCredit,
              Valoare,
              CodObligStins,
              CodDoc,
              TipDoc,
              CodObligStingator,
              Obs,
              ValDif,
              Valoareold,
              ARTICOL,
              CANT,
              DOC,
              MONEDA,
              SEDIU,
              CURS,
              CODOBIECT,
              PROCDISC,
              PRET_N,
              PRET_B,
              VAL_N,
              VAL_B,
              VALLEI_N,
              VALLEI_B,
              DISCOUNT_N,
              DISCOUNT_B,
              ValFaraTVA_N,
              ValFaraTVA_B,
              CODCLASEDISC,
              CODINTERN,
              PROCTVA,
              OBSNAV,
              CODANALIZANOD,
              CODCENTRU)
          with CumulCant as
            ( select i1.codobiect, sum (i1.cant)  TOTALCANT
              from notecredit1     nc1
                inner join iesiri1 i1 on nc1.coddoc = i1.codies1
                inner join iesiri  i  on i1.codies  = i.codies
                inner join notecredit nc on nc.codncredit = nc1.codncredit
              where
                (coalesce (i.anulat, 0) = 0)
                and nc1.tip = current_setting ('PKG_NOTECREDIT.tncCantitate', true) ::numeric
                and nc1.codncredit = RecId
                and (nc.corectie = 1 or I.Datadoc between vDataStart and vDataStop)
                and (I1.CodObiect not in (current_setting ('PKG_NOTECREDIT.KArtDiscAcVol', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtDiscAcCant', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtPenAcTer', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceC', true) ::numeric)
                     and INSTR (current_setting ('PKG_NOTECREDIT.KArtDiscAcTer', true) , (I1.CODOBIECT) ::varchar) = 0)
              group BY i1.codobiect
            )
          select NC1.CodNCredit1,
            NC1.CodNCredit,
            NC1.Valoare,
            CASE when coalesce (NC1.CodObligStins, 0) = 0 then g.codgeneral else NC1.CodObligStins end ,
            NC1.CodDoc,
            NC1.TipDoc,
            NC1.CodObligStingator,
            NC1.Obs,
            NC1.ValDif,
            NC1.Valoareold,
            OBJ.Denumire ARTICOL,
            I1.cant,
            coalesce (i.prefixdoc, '') || ' ' || coalesce (i.nrdoc::varchar , '') || '/' || coalesce (to_char (i.datadoc, 'dd.mm.yyyy') , '') DOC,
            (select PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT from PKG_MONEDE_GET_SIMBOL_MONEDA (null, coalesce (g.MONEDA, 0))) MONEDA,
            A.obs SEDIU,
            CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end CURS,
            i1.codobiect,
            NC1.Valoare /
                          case
                            when I1.cant * I1.PU * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end = 0 then 1
                            else I1.cant * I1.PU * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end
                          end * 100,
            case
              when i.tipdoc = 21 then round ( ( (I1.Pretorig * i1.cant * i1.coefdiscmaj - i1.tva) / i1.cant) ::numeric, 2)
              else i1.pretorig * i1.coefdiscmaj
            end PRET,
            CASE when i.tipdoc = 21 then round ( ( (I1.Pretorig * i1.cant - i1.tva) / i1.cant) ::numeric, 2) else i1.pretorig end PRET_B,
            CASE when i.tipdoc = 21 then (I1.cant * I1.Pretorig) * i1.coefdiscmaj - i1.tva else I1.cant * I1.Pretorig * i1.coefdiscmaj end VAL,
            CASE when i.tipdoc = 21 then (I1.cant * I1.Pretorig - i1.tva) else I1.cant * I1.Pretorig end VAL_B,
            CASE when i.tipdoc = 21 then (I1.cant * I1.Pretorig) * i1.coefdiscmaj - i1.tva else I1.cant * I1.Pretorig * i1.coefdiscmaj end
             * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end VALLEI,
            CASE when i.tipdoc = 21 then (I1.cant * I1.Pretorig - i1.tva) else I1.cant * I1.Pretorig end
             * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end VALLEI_B,
            0,
            0,
            CASE when i.tipdoc = 21 then (I1.Pretorig * i1.cant * i1.coefdiscmaj - i1.tva) else i1.Pretorig * i1.Cant * i1.coefdiscmaj end ,
            CASE when i.tipdoc = 21 then (I1.Pretorig * i1.cant - i1.tva) else i1.Pretorig * i1.Cant end ,
            NC1.CODCLASEDISC,
            OBJ.CODINTERN,
            coalesce (NC1.PROCTVA, 24) ,
            NC1.OBSNAV,
            NC1.CODANALIZANOD,
            NC1.CODCENTRU
          from NOTECREDIT1     NC1
            inner join iesiri1 i1 on nc1.coddoc   = i1.codies1
            inner join CumulCant  on i1.codobiect = CumulCant.codobiect
            inner join iesiri  i  on i1.codies    = i.codies and I.TIPDOC = NC1.TIPDOC
            inner join general g  on g.coddoc     = i.codies and g.tipdoc = i.tipdoc and g.semnificatie not in (500, 240, 211, 100, 140, 400)
            inner join NARTOBJ OBJ  on I1.CodObiect = OBJ.Codobiect
            left join NAGENDA  A    on A.codagenda  = i.codlocatie
            left join TMP_CURS_REGULARIZAT_LUNA GREG on GREG.CODGENERAL = G.CODGENERAL
          where
            NC1.CodNCredit = RecId
            and NC1.Tip = current_setting ('PKG_NOTECREDIT.tncCantitate', true) ::numeric;
        end if;
      else
        if vCodContract &gt; 0 THEN
        vTotCant := 0;
        begin
        select
          sum(i1.cant) into vtotcant
        from notecredit1 nc1
             inner join intrari1 i1 on nc1.coddoc = i1.codintr1
             inner join intrari   i on i1.codintr    = i.codintr
             inner join contract1 c1 on c1.codcontract1 = pkg_contract_GetCodContract1(i1.codobiect, i.datadoc, vCodContract)
             inner join contract c on c.codcontract = c1.codcontract
        where (coalesce(i.anulat, 0) = 0)
              and c.codcontract = vCodContract
              and nc1.codncredit = RecId and nc1.tip = tncCantitate
              and I.Datadoc between vDataStart and vDataStop
              AND (I1.CodObiect not in (KArtDiscAcVol,KArtDiscAcCant,KArtPenAcTer,KArtDiscOffInvoiceC) AND INSTR(KArtDiscAcTer, TO_CHAR(I1.CODOBIECT)) = 0);
        exception when others then vTotCant := 0;
        end;
          insert  into TMP_NOTECREDITC (
              CodNCredit1,
              CodNCredit,
              Valoare,
              CodObligStins,
              CodDoc,
              TipDoc,
              CodObligStingator,
              Obs,
              ValDif,
              Valoareold,
              ARTICOL,
              CANT,
              DOC,
              MONEDA,
              SEDIU,
              CURS,
              CODOBIECT,
              PROCDISC,
              PRET_N,
              PRET_B,
              VAL_N,
              VAL_B,
              VALLEI_N,
              VALLEI_B,
              DISCOUNT_N,
              DISCOUNT_B,
              ValFaraTVA_N,
              ValFaraTVA_B,
              CODCLASEDISC,
              CODINTERN,
              PROCTVA,
              OBSNAV,
              CODANALIZANOD,
              CODCENTRU)
          with CumulCant as
            ( select i1.codobiect,
                sum (i1.cant) TOTALCANT,
                c1.codcontract1,
                sum (I1.cant * I1.Pretorig * I1.COEFDISCMAJ) / sum (i1.cant) PRETMEDIU,
                sum (I1.cant * I1.Pretorig) / sum (i1.cant)                  PRETMEDIU_B
              from notecredit1       nc1
                inner join intrari1  i1 on nc1.coddoc      = i1.codintr1
                inner join intrari   i  on i1.codintr      = i.codintr
                inner join contract1 c1 on c1.codcontract1 = (select PKG_NOTECREDIT_GetCodContract1.WME_RESULT
                                                              from   PKG_NOTECREDIT_GetCodContract1 (null, i1.codobiect, i.datadoc, vCodContract))
                inner join contract c on c.codcontract = c1.codcontract
              where
                (coalesce (i.anulat, 0) = 0)
                and c.codcontract = vCodContract
                and nc1.codncredit = RecId
                and nc1.tip = current_setting ('PKG_NOTECREDIT.tncCantitate', true) ::numeric
                and I.Datadoc between vDataStart and vDataStop
                and (I1.CodObiect not in (current_setting ('PKG_NOTECREDIT.KArtDiscAcVol', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtDiscAcCant', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtPenAcTer', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceC', true) ::numeric)
                     and INSTR (current_setting ('PKG_NOTECREDIT.KArtDiscAcTer', true) , (I1.CODOBIECT) ::varchar) = 0)
              group BY i1.codobiect, c1.codcontract1
            )
          select NC1.CodNCredit1, NC1.CodNCredit, NC1.Valoare, CASE when coalesce (NC1.CodObligStins, 0) = 0 then g.codgeneral else NC1.CodObligStins end ,
            NC1.CodDoc,
            NC1.TipDoc,
            NC1.CodObligStingator,
            NC1.Obs,
            NC1.ValDif,
            NC1.Valoareold,
            OBJ.Denumire ARTICOL,
            I1.cant,
            coalesce (i.prefixdoc, '') || ' ' || coalesce (i.nrdoc::varchar , '') || '/' || coalesce (to_char (i.datadoc, 'dd.mm.yyyy') , '') DOC,
            (select PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT from PKG_MONEDE_GET_SIMBOL_MONEDA (null, coalesce (g.MONEDA, 0))) MONEDA,
            A.obs SEDIU,
            CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end CURS,
            i1.codobiect,
            case
              when vCodContract = 0 then NC1.Valoare /
                case
                  when I1.cant * I1.Pretorig * I1.CoefDiscMaj * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end = 0 then 1
                  else I1.cant * I1.Pretorig * I1.CoefDiscMaj * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end
                end * 100
              else 0
            end ,
            I1.PU                                  PRET,
            I1.PretOrig                            PRET,
            I1.cant * I1.Pretorig * I1.COEFDISCMAJ VAL,
            I1.cant * I1.Pretorig                  VAL_B,
            I1.cant * I1.Pretorig * I1.COEFDISCMAJ * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end VALLEI,
            I1.cant * I1.Pretorig * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end VALLEI_B,
            round ((SELECT wme_result FROM pkg_notecredit_GetDiscCant(NULL, I1.cant, I1.cant * I1.Pretorig * I1.CoefDiscMaj * (CASE WHEN coalesce(GREG.CURS, G.CURS) = 0 THEN 1 ELSE coalesce(GREG.CURS, G.CURS) END), CumulCant.totalcant, CumulCant.CodContract1, cumulcant.pretmediu,vTotCant, vCurs))::numeric, 2),
            round ((SELECT wme_result FROM pkg_notecredit_GetDiscCant(NULL, I1.cant, I1.cant * I1.Pretorig * (CASE WHEN coalesce(GREG.CURS, G.CURS) = 0 then 1 ELSE coalesce(GREG.CURS, G.CURS) END), CumulCant.totalcant, CumulCant.CodContract1, cumulcant.pretmediu_b,vTotCant, vCurs))::NUMERIC, 2),
            I1.cant * I1.PretOrig * I1.COEFDISCMAJ,
            I1.cant * I1.PretOrig,
            NC1.CODCLASEDISC,
            OBJ.CODINTERN,
            NC1.PROCTVA,
            NC1.OBSNAV,
            NC1.CODANALIZANOD,
            NC1.CODCENTRU
          from NOTECREDIT1      NC1
            inner join intrari1 i1 on nc1.coddoc   = i1.codintr1
            inner join intrari i   on i1.codintr   = i.codintr and I.TIPDOC = NC1.TIPDOC
            inner join CumulCant on i1.codobiect = CumulCant.codobiect  and CumulCant.CodContract1 = (SELECT wme_result FROM PKG_NOTECREDIT_GETCODCONTRACT1(NULL, i1.codobiect, i.datadoc, vCodContract))
            inner join general g   on g.coddoc     = i.codintr and g.tipdoc = i.tipdoc and g.semnificatie not in (500, 111, 200, 140, 300, 240)
            inner join NARTOBJ OBJ on I1.CodObiect = OBJ.Codobiect
            left join NAGENDA  A   on A.codagenda  = i.codlocatie
            left join TMP_CURS_REGULARIZAT_LUNA GREG on GREG.CODGENERAL = G.CODGENERAL
          where
            NC1.CodNCredit = RecId and NC1.Tip = current_setting ('PKG_NOTECREDIT.tncCantitate', true) ::numeric;
        else
          insert  into TMP_NOTECREDITC (
              CodNCredit1,
              CodNCredit,
              Valoare,
              CodObligStins,
              CodDoc,
              TipDoc,
              CodObligStingator,
              Obs,
              ValDif,
              Valoareold,
              ARTICOL,
              CANT,
              DOC,
              MONEDA,
              SEDIU,
              CURS,
              CODOBIECT,
              PROCDISC,
              PRET_N,
              PRET_B,
              VAL_N,
              VAL_B,
              VALLEI_N,
              VALLEI_B,
              DISCOUNT_N,
              DISCOUNT_B,
              ValFaraTVA_N,
              ValFaraTVA_B,
              CODCLASEDISC,
              CODINTERN,
              PROCTVA,
              OBSNAV,
              CODANALIZANOD,
              CODCENTRU)
          with CumulCant as
            ( select i1.codobiect, sum (i1.cant) TOTALCANT
              from notecredit1      nc1
                inner join intrari1 i1 on nc1.coddoc = i1.codintr1
                inner join intrari  i  on i1.codintr = i.codintr
              where
                (coalesce (i.anulat, 0) = 0)
                and nc1.codncredit = RecId
                and nc1.tip = current_setting ('PKG_NOTECREDIT.tncCantitate', true) ::numeric
                and I.Datadoc between vDataStart and vDataStop
                and (I1.CodObiect not in (current_setting ('PKG_NOTECREDIT.KArtDiscAcVol', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtDiscAcCant', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtPenAcTer', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceC', true) ::numeric)
                     and INSTR (current_setting ('PKG_NOTECREDIT.KArtDiscAcTer', true) , (I1.CODOBIECT) ::varchar) = 0)
              group BY i1.codobiect
            )
          select NC1.CodNCredit1, NC1.CodNCredit, NC1.Valoare,
            CASE when coalesce (NC1.CodObligStins, 0) = 0 then g.codgeneral else NC1.CodObligStins end ,
            NC1.CodDoc,
            NC1.TipDoc,
            NC1.CodObligStingator,
            NC1.Obs,
            NC1.ValDif,
            NC1.Valoareold,
            OBJ.Denumire ARTICOL,
            I1.cant,
            coalesce (i.prefixdoc, '') || ' ' || coalesce (i.nrdoc::varchar , '') || '/' || coalesce (to_char (i.datadoc, 'dd.mm.yyyy') , '') DOC,
            (select PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT from PKG_MONEDE_GET_SIMBOL_MONEDA (null, coalesce (g.MONEDA, 0))) MONEDA,
            A.obs  SEDIU,
            CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end CURS,
            i1.codobiect,
            case
              when vCodContract = 0 then NC1.Valoare /
                case
                  when I1.cant * I1.Pretorig * I1.CoefDiscMaj * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end = 0 then 1
                  else I1.cant * I1.Pretorig * I1.CoefDiscMaj * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end
                end * 100
              else 0
            end ,
            I1.PU                                  PRET,
            I1.PretOrig                            PRET_B,
            I1.cant * I1.Pretorig * I1.COEFDISCMAJ VAL,
            I1.cant * I1.Pretorig                  VAL_B,
            I1.cant * I1.Pretorig * I1.COEFDISCMAJ *
            CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end VALLEI,
            I1.cant * I1.Pretorig * CASE when coalesce (GREG.CURS, G.CURS) = 0 then 1 else coalesce (GREG.CURS, G.CURS) end VALLEI_B,
            0,
            0,
            I1.cant * I1.PretOrig * I1.COEFDISCMAJ,
            I1.cant *               I1.PretOrig,
            NC1.CODCLASEDISC,
            OBJ.CODINTERN,
            coalesce (NC1.PROCTVA, 24) ,
            NC1.OBSNAV,
            NC1.CODANALIZANOD,
            NC1.CODCENTRU
          from NOTECREDIT1      NC1
            inner join intrari1 i1 on nc1.coddoc   = i1.codintr1
            inner join CumulCant   on i1.codobiect = CumulCant.codobiect
            inner join intrari i   on i1.codintr   = i.codintr and I.TIPDOC = NC1.TIPDOC
            inner join general g   on g.coddoc     = i.codintr and g.tipdoc = i.tipdoc and g.semnificatie not in (500, 111, 200, 140, 300, 240)
            inner join NARTOBJ OBJ on I1.CodObiect = OBJ.Codobiect
            left join NAGENDA  A   on A.codagenda  = i.codlocatie
            left join TMP_CURS_REGULARIZAT_LUNA GREG on GREG.CODGENERAL = G.CODGENERAL
          where
            NC1.CodNCredit = RecId and NC1.Tip = current_setting ('PKG_NOTECREDIT.tncCantitate', true) ::numeric;
        end if;
      end if;
    end if;

    begin
      select coalesce (PretBrutC, 0) INTO vPretBrutC from tmp_notecredit;
    exception
    when others then
      vPretBrutC := 0;
    end;

    if vPretBrutC = 1 then
      UPDATE tmp_notecreditc
      set
        Pret       = PRET_B,
        Val        = VAL_B,
        VALLEI     = VALLEI_B,
        DISCOUNT   = DISCOUNT_B,
        VALFARATVA = VALFARATVA_B;
    else
      UPDATE tmp_notecreditc
      set
        Pret       = PRET_N,
        Val        = VAL_N,
        VALLEI     = VALLEI_N,
        DISCOUNT   = DISCOUNT_N,
        VALFARATVA = VALFARATVA_N;
    end if;

    select count(*) INTO vCount from notecredit1 WHERE codncredit = recid and tip = current_setting ('PKG_NOTECREDIT.tncPenalizari', true) ::numeric;

    if vCount &gt; 0 then
      if vTipDoc = 58 then
        insert  into TMP_NOTECREDITP (
            CodNCredit1,
            CodNCredit,
            Valoare,
            CodObligStins,
            CodDoc,
            TipDoc,
            CodObligStingator,
            Obs,
            ValDif,
            Valoareold,
            DOC,
            CONT,
            MONEDA,
            TERMEN,
            SUBUNITATEA,
            SEDIU,
            CURS,
            VALDOC,
            VALLEI,
            VALPLATA,
            DOCPLATA,
            ZILEPLATA,
            DISCOUNT,
            CODANALIZANOD,
            CODCENTRU)
        select NC1.CodNCredit1,
          NC1.CodNCredit,
          NC1.Valoare,
          NC1.CodObligStins,
          NC1.CodDoc,
          NC1.TipDoc,
          NC1.CodObligStingator,
          NC1.Obs,
          NC1.ValDif,
          NC1.Valoareold,
          coalesce (i.prefixdoc, '') || ' ' || coalesce (i.nrdoc::varchar , '') || '/' || coalesce (to_char (i.datadoc, 'dd.mm.yyyy') , '') DOC,
          (select PKG_LIST_BASE_UTILS_decode_iCont.WME_RESULT
            from PKG_LIST_BASE_UTILS_decode_iCont (null, obstins.icont, obstins.codpart, i.an * 12 + i.luna, obstins.semnificatie)) CONT,
          (select PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT from PKG_MONEDE_GET_SIMBOL_MONEDA (null, coalesce (gstins.MONEDA, 0))) MONEDA,
          obstins.termen TERMEN,
          i.subunitatea  SUBUNITATEA,
          A.obs          SEDIU,
          CASE when coalesce (GREG.CURS, GSTINS.CURS) = 0 then 1 else coalesce (GREG.CURS, GSTINS.CURS) end CURS,
          obstins.valoare VALDOC,
          obstins.valoare * CASE when coalesce (GREG.CURS, Gstins.CURS) = 0 then 1 else coalesce (GREG.CURS, Gstins.CURS) end VALLEI,
          stingere.valoare,
          coalesce (t1.doc, '') || ' ' || coalesce (t1.nrdoc::varchar , '') || '/' || coalesce (to_char (t1.datadoc, 'dd.mm.yyyy') , '') DOCPLATA,
          t1.datadoc - i.datadoc::DATE,
          case
            when t1.datadoc &gt; obstins.termen then stingere.Valoare * (select pkg_notecredit_GETPROCCONTRACTPEN.WME_RESULT
                                                                      from   pkg_notecredit_GETPROCCONTRACTPEN (null, vCodContract)) / 100
            else 0
          END,
          NC1.CODANALIZANOD,
          NC1.CODCENTRU
        from NOTECREDIT1     NC1
          left join obligpif obstins      on nc1.codobligstins     = obstins.codobligpif
          left join obligpif obstingator  on nc1.codobligstingator = obstingator.codobligpif
          left join stingere              on stingere.codstinspif  = obstins.codobligpif and stingere.codstingatorpif = obstingator.codobligpif
          left join general  gstins       on gstins.codgeneral     = obstins.codgeneral
          left join general  gstingator   on gstingator.codgeneral = obstingator.codgeneral
          left join iesiri   i            on gstins.coddoc         = i.codies and gstins.tipdoc = i.tipdoc
          left join trezor1  t1           on gstingator.coddoc     = t1.codtrezor1
          left join trezor   t            on t1.codtrezor          = t.codtrezor and gstingator.tipdoc = t.tipdoc
          left join nagenda  a            on i.codlocatie          = a.codagenda
          left join TMP_CURS_REGULARIZAT_LUNA GREG on GREG.CODGENERAL = GSTINS.CODGENERAL
        where
          NC1.CodNCredit = RecId and NC1.Tip = current_setting ('PKG_NOTECREDIT.tncPenalizari', true) ::numeric;
      else
        insert  into TMP_NOTECREDITP (
            CodNCredit1,
            CodNCredit,
            Valoare,
            CodObligStins,
            CodDoc,
            TipDoc,
            CodObligStingator,
            Obs,
            ValDif,
            Valoareold,
            DOC,
            CONT,
            MONEDA,
            TERMEN,
            SUBUNITATEA,
            SEDIU,
            CURS,
            VALDOC,
            VALLEI,
            VALPLATA,
            DOCPLATA,
            ZILEPLATA,
            DISCOUNT,
            CODANALIZANOD,
            CODCENTRU)
        select NC1.CodNCredit1,
          NC1.CodNCredit,
          NC1.Valoare,
          NC1.CodObligStins,
          NC1.CodDoc,
          NC1.TipDoc,
          NC1.CodObligStingator,
          NC1.Obs,
          NC1.ValDif,
          NC1.Valoareold,
          coalesce (i.prefixdoc, '') || ' ' || coalesce (i.nrdoc::varchar , '') || '/' || coalesce (to_char (i.datadoc, 'dd.mm.yyyy') , '') DOC,
          (select PKG_LIST_BASE_UTILS_decode_iCont.WME_RESULT
           from PKG_LIST_BASE_UTILS_decode_iCont (null, obstins.icont, obstins.codpart, i.an * 12 + i.luna, obstins.semnificatie)) CONT,
          (select PKG_MONEDE_GET_SIMBOL_MONEDA.WME_RESULT from PKG_MONEDE_GET_SIMBOL_MONEDA (null, coalesce (gstins.MONEDA, 0))) MONEDA,
          obstins.termen   TERMEN,
          i.subunitatea    SUBUNITATEA,
          A.obs            SEDIU,
          CASE when coalesce (GREG.CURS, GSTINS.CURS) = 0 then 1 else coalesce (GREG.CURS, GSTINS.CURS) end CURS,
          obstins.valoare VALDOC,
          obstins.valoare * CASE when coalesce (GREG.CURS, Gstins.CURS) = 0 then 1 else coalesce (GREG.CURS, Gstins.CURS) end VALLEI,
          stingere.valoare,
          coalesce (t1.doc, '') || ' ' || coalesce (t1.nrdoc::varchar , '') || '/' || coalesce (to_char (t1.datadoc, 'dd.mm.yyyy') , '') DOCPLATA,
          t1.datadoc - i.datadoc,
          CASE when t1.datadoc &gt; obstins.termen then stingere.Valoare * (select pkg_notecredit_GETPROCCONTRACTPEN.WME_RESULT
                                                                         from pkg_notecredit_GETPROCCONTRACTPEN (null, vCodContract)) / 100
               else 0
          END,
          NC1.CODANALIZANOD,
          NC1.CODCENTRU
        from NOTECREDIT1     NC1
          left join obligpif obstins      on nc1.codobligstins     = obstins.codobligpif
          left join obligpif obstingator  on nc1.codobligstingator = obstingator.codobligpif
          left join stingere              on stingere.codstinspif  = obstins.codobligpif and stingere.codstingatorpif = obstingator.codobligpif
          left join general  gstins       on gstins.codgeneral     = obstins.codgeneral
          left join general  gstingator   on gstingator.codgeneral = obstingator.codgeneral
          left join intrari  i            on gstins.coddoc         = i.codintr and gstins.tipdoc = i.tipdoc
          left join trezor1  t1           on gstingator.coddoc     = t1.codtrezor1
          left join trezor   t            on t1.codtrezor          = t.codtrezor and gstingator.tipdoc = t.tipdoc
          left join nagenda  a            on i.codlocatie          = a.codagenda
          left join TMP_CURS_REGULARIZAT_LUNA GREG on GREG.CODGENERAL = GSTINS.CODGENERAL
        where
          NC1.CodNCredit = RecId and NC1.Tip = current_setting ('PKG_NOTECREDIT.tncPenalizari', true) ::numeric;
      end if;
    end if;

    if vTipDoc = 58 then
      insert  into tmp_notecreditfact (
          codncfact,
          CodNCredit,
          coddoc,
          tipdoc,
          prefixdoc,
          nrdoc,
          datadoc,
          valdoc,
          valt,
          restval,
          valalte,
          coddoc1)
      select NCF.codncfact,
        NCF.CodNCredit,
        NCF.coddoc,
        NCF.tipdoc,
        NCF.prefixdoc,
        NCF.nrdoc,
        NCF.datadoc,
        NCF.valdoc,
        coalesce (NCF.valt, ncf.valdoc) ,
        coalesce (NCF.valt, ncf.valdoc) - coalesce (alte.val, 0) ,
        coalesce (alte.val, 0),
        ncf.coddoc1
      from Notecreditfact NCF
        inner join iesiri i on NCF.Coddoc = i.codies and ncf.tipdoc = i.tipdoc
        left join (select sum (a.valdoc) VAL, a.coddoc, a.tipdoc from notecreditfact a WHERE a.codncredit &lt;&gt; RecId group BY a.coddoc, a.tipdoc
                  ) alte on alte.coddoc = ncf.coddoc and alte.tipdoc = ncf.tipdoc
      where
        codncredit = RecId
      UNION ALL
      select NCF.codncfact, NCF.CodNCredit, NCF.coddoc, NCF.tipdoc, NCF.prefixdoc, NCF.nrdoc, NCF.datadoc, NCF.valdoc, coalesce(NCF.valt, ncf.valdoc), coalesce(NCF.valt, ncf.valdoc) - coalesce(alte.val, 0),
        coalesce(alte.val,0), ncf.coddoc1
      from Notecreditfact NCF
      inner join iesiri1 i1 on ncf.coddoc1 = i1.codies1
      inner join iesiri i on i1.codies = i.codies and ncf.tipdoc = i.tipdoc
      left join (select sum(a.valdoc) val, a.coddoc, a.tipdoc
        from notecreditfact a
        where a.codncredit &lt;&gt; RecId
        group by a.coddoc, a.tipdoc) alte on alte.coddoc = ncf.coddoc and alte.tipdoc = ncf.tipdoc
      where codncredit = RecId;
    else
      insert  into tmp_notecreditfact (
          codncfact,
          CodNCredit,
          coddoc,
          tipdoc,
          prefixdoc,
          nrdoc,
          datadoc,
          valdoc,
          valt,
          restval,
          valalte,
          coddoc1)
      select NCF.codncfact,
        NCF.CodNCredit,
        NCF.coddoc,
        NCF.tipdoc,
        NCF.prefixdoc,
        NCF.nrdoc,
        NCF.datadoc,
        NCF.valdoc,
        coalesce (NCF.valt, ncf.valdoc) ,
        coalesce (NCF.valt, ncf.valdoc) - coalesce (alte.val, 0) ,
        coalesce (alte.val, 0),
        ncf.coddoc1
      from Notecreditfact NCF
        left join intrari i   on NCF.Coddoc = i.codintr and ncf.tipdoc = i.tipdoc
        left join iesiri  ies on ncf.coddoc = ies.codies and ncf.tipdoc = ies.tipdoc
        left join (select sum(a.valdoc) val, a.coddoc, a.tipdoc
          from notecreditfact a
          where a.codncredit &lt;&gt; RecId
          group by a.coddoc, a.tipdoc) alte on alte.coddoc = ncf.coddoc and alte.tipdoc = ncf.tipdoc
          where codncredit = RecId and (ies.codies &gt; 0 or i.codintr &gt; 0)
        union ALL
        select NCF.codncfact, NCF.CodNCredit, NCF.coddoc, NCF.tipdoc, NCF.prefixdoc, NCF.nrdoc, NCF.datadoc, NCF.valdoc, coalesce(NCF.valt, ncf.valdoc), coalesce(NCF.valt, ncf.valdoc) - coalesce(alte.val, 0),
        coalesce(alte.val,0),ncf.coddoc1
        from Notecreditfact NCF
        inner join iesiri1 i1 on i1.codies1 = ncf.coddoc1
        inner join iesiri ies on i1.codies = ies.codies and ncf.tipdoc = ies.tipdoc
        left join (select sum(a.valdoc) val, a.coddoc, a.tipdoc
          from notecreditfact a
          where a.codncredit &lt;&gt; RecId
          group by a.coddoc, a.tipdoc) alte on alte.coddoc = ncf.coddoc and alte.tipdoc = ncf.tipdoc
          where codncredit = RecId
        union ALL
        select NCF.codncfact, NCF.CodNCredit, NCF.coddoc, NCF.tipdoc, NCF.prefixdoc, NCF.nrdoc, NCF.datadoc, NCF.valdoc, coalesce(NCF.valt, ncf.valdoc), coalesce(NCF.valt, ncf.valdoc) - coalesce(alte.val, 0),
        coalesce(alte.val,0),ncf.coddoc1
            from Notecreditfact NCF
            inner join intrari1 i1 on i1.codintr1 = ncf.coddoc1
            inner join intrari i on i1.codintr = i.codintr and ncf.tipdoc = i.tipdoc
            left join (select sum(a.valdoc) val, a.coddoc, a.tipdoc
            from notecreditfact a
            where a.codncredit &lt;&gt; RecId
            group by a.coddoc, a.tipdoc) alte on alte.coddoc = ncf.coddoc and alte.tipdoc = ncf.tipdoc
          where codncredit = RecId;
    end if;

    insert  into tmp_nccadouri (
        codnccadouri,
        codncredit,
        codobiect,
        codobiectasoc,
        codobiectasocsec,
        cant,
        cantfact,
        codarticol,
        umsec,
        diferente,
        denumire,
        denumireasoc,
        denumireasocsec,
        den_um1,
        tiparticol,
        Pret,
        Paritate,
        CODANALIZANOD,
        CODCENTRU)
    select c.codnccadouri,
      c.codncredit,
      c.codobiect,
      c.codobiectasoc,
      c.codobiectasocsec,
      c.cant,
      c.cantfact,
      c.codarticol,
      c.umsec,
      c.diferente,
      obj.denumire,
      objasoc.denumire,
      objasocsec.denumire,
      num1.den_um1,
      art.tiparticol::numeric,
      0,
      num1.paritate,
      C.CODANALIZANOD,
      C.CODCENTRU
    from nccadouri        c
      left join nartobj obj        on c.codobiect        = obj.codobiect
      left join nart    art        on obj.codarticol     = art.codarticol
      left join nartobj objasoc    on c.codobiectasoc    = objasoc.codobiect
      left join nartobj objasocsec on c.codobiectasocsec = objasocsec.codobiect
      left join num1               on num1.codum1        = c.umsec
    where
      c.codncredit = RecId;

    insert  into TMP_CENTRALIZARENC (
        CODCENTRALIZARE,
        CODNCREDIT,
        CODARTICOL,
        CODOBIECT,
        CODOBIECTASOC,
        CODOBIECTASOCSEC,
        UMSEC,
        DIFERENTE,
        TIPARTICOL,
        DENUMIRE,
        DENUMIREASOC,
        DENUMIREASOCSEC,
        DEN_UM1,
        PARITATE,
        FACTURAT,
        PROCTVA,
        CODANALIZANOD,
        CODCENTRU,
        OBS, CANT)
    select C.CODCENTRALIZARE,
      C.CODNCREDIT,
      C.CODARTICOL,
      C.CODOBIECT,
      C.CODOBIECTASOC,
      C.CODOBIECTASOCSEC,
      C.UMSEC,
      C.DIFERENTE,
      NART.TIPARTICOL::numeric,
      O.DENUMIRE,
      case
        when o.codobiect &lt;&gt; coalesce ( (fnc_GetValConstantalucru ('ArtPenAc')) , '0') ::numeric then OS.DENUMIRE
        else
          case
            when vTipDoc = 58 then coalesce (iI.prefixdoc, '') || ' ' || coalesce (iI.nrdoc::varchar , '') || '/' || coalesce (to_char (ii.datadoc, 'dd.mm.yyyy') , '')
            else coalesce (it.prefixdoc, '') || ' ' || coalesce (it.nrdoc::varchar , '') || '/' || coalesce (to_char (it.datadoc, 'dd.mm.yyyy') , '')
          end
      end ,
      OSS.DENUMIRE,
      NUM1.DEN_UM1,
      0,
      C.FACTURAT,
      coalesce (C.PROCTVA, TVA1.PROCENT) ,
      C.CODCENTRU, C.CODANALIZANOD,
      C.OBS, C.CANT
    from CENTRALIZARENC     C
      inner join NOTECREDIT NC   on NC.CODNCREDIT   = C.CODNCREDIT
      INNER JOIN NARTOBJ O ON O.CODOBIECT = C.CODOBIECT
      inner join NART            on NART.CODARTICOL = O.CODARTICOL
      INNER JOIN NART1 ART1 ON art1.codarticol = o.codarticol AND NC.AN*12+NC.LUNA BETWEEN art1.ALStart AND art1.ALStop
      INNER JOIN NTVA1 TVA1 ON tva1.codtva = art1.codtva      AND NC.AN*12+NC.LUNA BETWEEN tva1.ALStart AND tva1.ALStop
      left join NARTOBJ     OS   on OS.CODOBIECT    = C.CODOBIECTASOC
      left join NARTOBJ     OSS  on OSS.CODOBIECT   = C.CODOBIECTASOCSEC
      left join NUM1             on NUM1.CODUM1     = C.UMSEC
      left join IESIRI      II   on II.CODIES       = C.CODOBIECTASOC
      left join INTRARI     IT   on IT.CODINTR      = C.CODOBIECTASOC
    where
      C.CODNCREDIT = RECID;

    if vTipDoc = 58 then
      for v_rec in (select coalesce (i1.codobiect, 0) CODOBIECT, coalesce (i1.codobiectorig, 0) CODOBIECTORIG,
                          case
                            when art.tiparticol = '0' then i1.cant
                            else CASE when i.tipdoc = 21 then I1.Cant * I1.PU - I1.TVA else I1.Cant * I1.PU end
                          end  VALOARE
                    from tmp_notecreditfact tmp
                      inner join iesiri1  i1  on i1.codies      = tmp.coddoc
                      inner join iesiri   i   on i.codies       = i1.codies
                      inner join nartobj  obj on i1.codobiect   = obj.codobiect
                      inner join nart     art on obj.codarticol = art.codarticol
                    where
                      tmp.codncredit = recid
                   )
      loop
        UPDATE tmp_centralizarenc
        set paritate = paritate + v_Rec.valoare
        where
          coalesce (codobiect, 0) = v_rec.codobiect
          and coalesce (codobiectasoc, 0) = v_Rec.codobiectorig
          and codncredit = recid;
      end loop;
    else
      for v_rec in (select coalesce (i1.codobiect, 0) CODOBIECT, coalesce (i1.codobiectorig, 0) CODOBIECTORIG,
                           CASE when art.tiparticol &lt;&gt; '0' then I1.Cant * I1.PU else i1.cant end VALOARE
                    from tmp_notecreditfact tmp
                      inner join intrari  i   on tmp.coddoc     = i.codintr and i.tipdoc = tmp.tipdoc
                      inner join intrari1 i1  on tmp.coddoc     = i1.codintr
                      inner join nartobj  obj on i1.codobiect   = obj.codobiect
                      inner join nart     art on obj.codarticol = art.codarticol
                    where
                      tmp.codncredit = recid
                      and (i1.codobiect NOT in (current_setting ('PKG_NOTECREDIT.KArtDiscPrimVol', true) ::numeric,
                                           current_setting ('PKG_NOTECREDIT.KArtDiscPrimCant', true) ::numeric,
                                           current_setting ('PKG_NOTECREDIT.KArtPenPrimTer', true) ::numeric,
                                           current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceF', true) ::numeric)
                      OR INSTR(current_setting ('PKG_NOTECREDIT.KArtDiscPrimTer', true), (I1.CODOBIECT)::varchar) = 0)
                    union all
                    select coalesce (i1.codobiect, 0)  CODOBIECT,
                      coalesce (i1.codobiectorig, 0) CODOBIECTORIG,
                      -
                      case
                        when art.tiparticol &lt;&gt; '0' then I1.Cant * I1.PU
                          else i1.cant
                      end                 VALOARE
                    from tmp_notecreditfact tmp
                      inner join iesiri   i   on tmp.coddoc     = i.codies and i.tipdoc = tmp.tipdoc
                      inner join iesiri1  i1  on tmp.coddoc     = i1.codies
                      inner join nartobj  obj on i1.codobiect   = obj.codobiect
                      inner join nart     art on obj.codarticol = art.codarticol
                    where
                      tmp.codncredit = recid
                      and (i1.codobiect NOT in (current_setting ('PKG_NOTECREDIT.KArtDiscPrimVol', true) ::numeric,
                                            current_setting ('PKG_NOTECREDIT.KArtDiscPrimCant', true) ::numeric,
                                            current_setting ('PKG_NOTECREDIT.KArtPenPrimTer', true) ::numeric,
                                            current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceF', true) ::numeric)
                      OR INSTR(current_setting ('PKG_NOTECREDIT.KArtDiscPrimTer', true), (I1.CODOBIECT)::varchar) = 0)
                  )
      loop
        UPDATE tmp_centralizarenc
        set paritate = paritate +
                        case
                          when codobiect = current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceF', true) ::numeric then - v_Rec.valoare
                          else v_rec.valoare
                        end
        where
          coalesce (codobiect, 0) = v_rec.codobiect
          and coalesce (codobiectasoc, 0) = v_Rec.codobiectorig
          and codncredit = recid;
      end loop;
    end if;

    UPDATE tmp_centralizarenc tmp
    set den_um1 = (select den_um1 from num1 WHERE codum1 = tmp.umsec);

    if vAreCorectii &gt; 0 then
      UPDATE tmp_centralizarenc
      set paritate = (select sum (valoare) from tmp_notecreditz)
      where
        codobiect in (current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceC', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceF', true) ::numeric);

      UPDATE tmp_centralizarenc
      set paritate = (select sum (valoare) from tmp_notecreditv)
      where
        codobiect in (current_setting ('PKG_NOTECREDIT.KArtDiscAcVol', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtDiscPrimVol', true) ::numeric);

      UPDATE tmp_centralizarenc
      set diferente = paritate - facturat
      where
        codobiect in (current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceC', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceF', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtDiscAcVol', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtDiscPrimVol', true) ::numeric);

      UPDATE tmp_centralizarenc tmp
      set corectii = (select sum (CC.DIFERENTE)
                      from CENTRALIZARENC       CC
                        inner join NOTECREDIT NC on NC.CODNCREDIT = CC.CODNCREDIT
                      where
                        NC.CORECTIE = 1
                        and NC.CODNCCORECTIE                  = tmp.codncredit
                        and coalesce (CC.proctva, 24)         = coalesce (tmp.proctva, 24)
                        and coalesce (CC.CODOBIECT, 0)        = coalesce (TMP.CODOBIECT, 0)
                        and coalesce (CC.CODOBIECTASOC, 0)    = coalesce (TMP.CODOBIECTASOC, 0)
                        and coalesce (CC.CODOBIECTASOCSEC, 0) = coalesce (TMP.CODOBIECTASOCSEC, 0));
    end if;

    select count(*) INTO vCount1 from tmp_centralizarenc;

    if vCount1 = 0 then
      select count(*) INTO vCount from tmp_notecreditfact;

      if vCount &gt; 0 then
        if vTipDoc = 58 then
          insert  into tmp_centralizarenc (
              CodArticol,
              CodObiect,
              DenumireAsoc,
              CodObiectAsoc,
              Denumire,
              Facturat,
              UMSec,
              Den_UM1,
              TIPARTICOL,
              paritate,
              DenumireAsocSec,
              CodObiectAsocSec,
              corectii)
          select ART.CodArticol,
            OBJ.CodObiect,
            objasoc.denumire as DENUMIREASOC,
            coalesce (objasoc.codobiect, 0) as CODOBIECTASOC,
            OBJ.Denumire,
            sum (
              case
                when art.tiparticol = '1' THEN CASE when i.tipdoc = 21 then I1.Cant * I1.PU - i1.tva else I1.Cant * I1.PU end
                else I1.Cant
              end) FACTURAT,
            Num1.CODUM1 UMSEC,
            NUM1.Den_UM1,
            ART.TIPARTICOL::numeric,
            num1.paritate,
            objasocsec.denumire as DENUMIREASOCSEC,
            coalesce (objasocsec.codobiect, 0) as CODOBIECTASOCSEC,
            (select sum (NCC1.VALOARE - NCC1.VALOAREOLD)
             from NOTECREDIT NCC inner join NOTECREDIT1 NCC1 on NCC.CODNCREDIT = NCC1.CODNCREDIT
             where NCC.CORECTIE = 1 and NCC.CODNCCORECTIE = NC.codncredit)
          from IESIRI          I
            inner join iesiri1 I1                    on i.codies         = i1.codies
            inner join nartobj OBJ                   on i1.codobiect     = obj.codobiect
            inner join nart    ART                   on OBJ.codarticol   = ART.codarticol
            inner join num1                          on art.um           = num1.codum and coalesce (num1.secundara, 0) = 0
            inner join tmp_notecreditfact tmp        on i.codies         = tmp.coddoc and tmp.tipdoc = i.tipdoc
            inner join tmp_notecredit     nc         on tmp.codncredit   = nc.codncredit
            left join nartobj             OBJASOC    on i1.codobiectorig = objasoc.codobiect
            left join contract1           c1         on i1.codobiectorig = c1.codcadou
            left join contract            c          on c1.codcontract   = c.codcontract and c.codcontract = vCodContract
            left join nartobj             OBJASOCSEC on c1.codobiectsec  = objasocsec.codobiect
          where
            I.TipDoc in (19, 21, 26)
            and I.Partener = vCodPart
            and (I1.CodObiect not in (current_setting ('PKG_NOTECREDIT.KArtDiscAcVol', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtDiscAcCant', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtPenAcTer', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceC', true) ::numeric)
                 and INSTR (current_setting ('PKG_NOTECREDIT.KArtDiscAcTer', true) , (I1.CODOBIECT) ::varchar) = 0)
            and I1.TipLinie &lt;&gt; 'T'
            and I1.TipLinie &lt;&gt; 'G'
            and I.Subunitatea = nc.subunitatea
          group by
            OBJ.CodObiect,
            Obj.Denumire,
            ART.CodArticol,
            NUM1.CodUM1,
            NUM1.Den_UM1,
            objasoc.denumire,
            objasoc.codobiect,
            Art.TipArticol,
            num1.paritate,
            objasocsec.denumire,
            objasocsec.codobiect;
        else
          insert  into tmp_centralizarenc (
              CodArticol,
              CodObiect,
              DenumireAsoc,
              CodObiectAsoc,
              Denumire,
              Facturat,
              UMSec,
              Den_UM1,
              TIPARTICOL,
              paritate,
              DenumireAsocSec,
              CodObiectAsocSec,
              corectii)
          select ART.CodArticol,
            OBJ.CodObiect,
            objasoc.denumire,
            coalesce (objasoc.codobiect, 0) ,
            OBJ.Denumire,
            sum (
              case
                when coalesce (tmp.valdoc, 0) = 0 then 0
                else CASE when art.tiparticol = '1' then I1.Cant * I1.PU else i1.Cant end * coalesce (tmp.valt, tmp.valdoc) / tmp.valdoc
              end),
            Num1.CODUM1,
            NUM1.Den_UM1,
            Art.TipArticol::numeric,
            num1.paritate,
            objasocsec.denumire,
            coalesce (objasocsec.codobiect, 0) ,
            ( select sum (NCC1.VALOARE - NCC1.VALOAREOLD)
              from NOTECREDIT NCC inner join NOTECREDIT1 NCC1 on NCC.CODNCREDIT = NCC1.CODNCREDIT
              where NCC.CORECTIE = 1 and NCC.CODNCCORECTIE = TMP.codncredit)
          from INTRARI            I
            inner join INTRARI1 I1                   on i.codintr        = i1.codintr
            inner join nartobj  OBJ                  on i1.codobiect     = obj.codobiect
            inner join nart     ART                  on OBJ.codarticol   = ART.codarticol
            inner join num1                          on art.um           = num1.codum and coalesce (num1.secundara, 0) = 0
            inner join tmp_notecreditfact tmp        on i.codintr        = tmp.coddoc and tmp.tipdoc = i.tipdoc
            left join nartobj             OBJASOC    on i1.codobiectorig = objasoc.codobiect
            left join contract1           c1         on i1.codobiectorig = c1.codcadou
            left join contract            c          on c1.codcontract   = c.codcontract and c.codcontract = vCodContract
            left join nartobj             OBJASOCSEC on c1.codobiectsec  = objasocsec.codobiect
          where
            I.TipDoc in (1, 3, 4, 5, 9)
            and I.Partener = vCodPart
            and (I1.CodObiect in (current_setting ('PKG_NOTECREDIT.KArtDiscPrimVol', true) ::numeric,
                                 current_setting ('PKG_NOTECREDIT.KArtDiscPrimCant', true) ::numeric,
                                 current_setting ('PKG_NOTECREDIT.KArtPenPrimTer', true) ::numeric,
                                 current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceF', true) ::numeric)
            OR INSTR(current_setting ('PKG_NOTECREDIT.KArtDiscPrimTer', true), (I1.CODOBIECT)::varchar) &gt; 0)
            and I1.TipLinie &lt;&gt; 'T'
            and I1.TipLinie &lt;&gt; 'G'
            and I.Subunitatea = current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric
          group by
            OBJ.CodObiect,
            Obj.Denumire,
            ART.CodArticol,
            NUM1.CodUM1,
            NUM1.Den_UM1,
            objasoc.denumire,
            objasoc.codobiect,
            Art.TipArticol,
            num1.paritate,
            objasocsec.denumire,
            objasocsec.codobiect;
        end if;
      end if;
    end if;

    UPDATE tmp_centralizarenc set PROCTVA = 24 WHERE PROCTVA is null;

    UPDATE tmp_notecredit
    set
      TOTALT     = (select round ( (sum (valdoc)) ::numeric, 2) from tmp_notecreditt) ,
      TOTALLEIT  = (select round ( (sum (vallei)) ::numeric, 2) from tmp_notecreditt) ,
      TOTALV     = (select round ( (sum (valdoc)) ::numeric, 2) from tmp_notecreditv) ,
      TOTALLEIV  = (select round ( (sum (vallei)) ::numeric, 2) from tmp_notecreditv) ,
      TOTALC     = (select round ( (sum (val))    ::numeric, 2) from tmp_notecreditc) ,
      TOTALLEIC  = (select round ( (sum (vallei)) ::numeric, 2) from tmp_notecreditc) ,
      TOTALP     = (select round ( (sum (valdoc)) ::numeric, 2) from tmp_notecreditp) ,
      TOTALLEIP  = (select round ( (sum (vallei)) ::numeric, 2) from tmp_notecreditp) ,
      TOTALZ     = (select round ( (sum (valdoc)) ::numeric, 2) from (select distinct codobligstins, valdoc from tmp_notecreditz WHERE codobligstins &gt; 0) N_PG) ,
      TOTALLEIZ  = (select round ( (sum (vallei)) ::numeric, 2) from (select distinct codobligstins, vallei from tmp_notecreditz WHERE codobligstins &gt; 0) O_PG) ,
      TOTALDISCZ = (select round ( (sum (valoare - coalesce (valoareold, 0))) ::numeric, 2) from tmp_notecreditz) ,
      TOTALFACT  = (select sum (FACTURAT)  from Tmp_Centralizarenc) ,
      TOTALDIF   = (select sum (DIFERENTE) from Tmp_Centralizarenc);

    UPDATE tmp_notecredit
    set
      TOTALZ    = TOTALZ    + (select coalesce (round ( (sum (valdoc)) ::numeric, 2) , 0) from tmp_notecreditz WHERE coalesce (codobligstins, 0) = 0) ,
      TOTALLEIZ = TOTALLEIZ + (select coalesce (round ( (sum (vallei)) ::numeric, 2) , 0) from tmp_notecreditz WHERE coalesce (codobligstins, 0) = 0);

    insert into TMP_JURNAL  (select * from JURNAL  WHERE TIPDOC = vTipDoc and CODDOC = RECID);
    insert into TMP_JURNAL1 (select * from JURNAL1 WHERE TIPDOC = vTipDoc and CODDOC = RECID);

    DELETE from TMP_RULAJ;
  end if;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_sp_lockrecord</obj_name>
  <obj_hashval>e60c98b0300f76e2b7834c6de2a2ceb7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodNCredit INTO Tmp FROM NOTECREDIT WHERE CodNCredit = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_sp_postrecords</obj_name>
  <obj_hashval>5f54a1d1ca9a2601961cc6d6542638f0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  V_REC        RECORD;
  V_REC_SUB    RECORD;
  vTrim        numeric;
  NR           numeric := 0;
  vTipDoc      numeric;
  ACARNETDOC   numeric;
  ANRDOC       numeric;
  aCodSubunit  numeric;
  aDataDoc     date;
  aDoc         varchar;
  vAreCorectii numeric;
BEGIN
  --Florin 01.06.2023 - monitor
  --Florin 20.04.2023 - sinc. Oracle (121.04.2023)
  --Florin 16.03.2023 - fixat 57653
  --Florin 07.03.2023 - sinc. Oracle
  --Laura 10.09.2021 - sinc Oracle (09.09.2021)
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_notecredit_setct_monitor('MON_47');
  perform set_config('PKG_NOTECREDIT.tncTermen',      '1', false);
  perform set_config('PKG_NOTECREDIT.tncVolum',       '2', false);
  perform set_config('PKG_NOTECREDIT.tncCantitate',   '3', false);
  perform set_config('PKG_NOTECREDIT.tncCadouri',     '4', false);
  perform set_config('PKG_NOTECREDIT.tncProvizioane', '5', false);
  perform set_config('PKG_NOTECREDIT.tncPenalizari',  '6', false);

  SELECT coalesce(AreCorectii, 0) INTO vAreCorectii FROM tmp_notecredit;

  select
    Trimestriala,
    TipDoc,
    CarnetDoc,
    NrDoc,
    Subunitatea,
    to_date(to_char(DataCreare, 'dd.mm.yyyy'), 'dd.mm.yyyy'),
    coalesce(PREFIXDOC, '') || coalesce(NRDOC::varchar , '') || '/' || coalesce(to_char(DATACREARE, 'dd.mm.yyyy'), '')
  into
    vTrim,
    vTipDoc,
    ACARNETDOC,
    ANRDOC,
    aCodSubunit,
    aDataDoc,
    aDoc
  FROM tmp_notecredit;

  if vTrim = 1 then
    DELETE FROM tmp_notecreditc;
    DELETE FROM tmp_notecreditp;
    DELETE FROM tmp_notecreditt;
    DELETE FROM tmp_notecreditz;
  end if;

  if Operation = 0 then
    SELECT CodNCredit INTO RecId FROM TMP_NOTECREDIT;

    if (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT
        FROM   PKG_USERFIRME_ValidPostLog(null, current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_NOTECREDIT.CT_MONITOR', true)))
    then
      perform pkg_userfirme_postlogcucommit('NOTECREDIT', current_setting('PKG_GLOBALS.USERNAME', true),
                                            'M', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true),
                                            aCodSubunit, aDataDoc, aDoc, null,
                                            current_setting('PKG_GLOBALS.EXE_VERSION', true));
    end if;

    UPDATE NOTECREDIT
    SET
      (CodContract2,
      CodPart,
      TipDoc,
      Subunitatea,
      DataStart,
      CODCONTV,
      CODCONTT,
      CODCONTC,
      CODCONTP,
      DataStop,
      Datafact,
      TipArticol,
      Obs,
      CodContract,
      Codmoneda,
      VOLUMPEARTICOLE,
      CODCONTZ,
      PRETBRUTC,
      PRETBRUTV,
      CODCARNET,
      Trimestriala,
      Corectie,
      CodNCCorectie,
      PrefixDoc,
      CarnetDoc,
      NrDoc,
      SeriaDoc,
      Previzionare,
      IesiriPeVolum,
      Curs,
      Inchisa,
      ValOrigTer, CODANALIZA )
      =
      (
      select
        CodContract2,
        CodPart,
        TipDoc,
        Subunitatea,
        DataStart,
        CODCONTV,
        CODCONTT,
        CODCONTC,
        CODCONTP,
        DataStop,
        DataFact,
        TipArticol,
        Obs,
        CodContract,
        CodMoneda,
        VOLUMPEARTICOLE,
        codcontz,
        PRETBRUTC,
        PRETBRUTV,
        CODCARNET,
        Trimestriala,
        Corectie,
        CodNCCorectie,
        PrefixDoc,
        CarnetDoc,
        NrDoc,
        SeriaDoc,
        Previzionare,
        IesiriPeVolum,
        Curs,
        Inchisa,
        ValOrigTer, CODANALIZA
      FROM TMP_NOTECREDIT )
    WHERE CodNCredit = RecId ;

    DELETE FROM TMP_NOTECREDIT1;
    INSERT INTO TMP_NOTECREDIT1 ( CODNCREDIT1, CODNCREDIT, TIPOPER, VALOARE, VALOAREOLD, VALDIF, CODOBLIGSTINS, CODDOC, TIPDOC, CODOBLIGSTINGATOR, OBS,
    CODCLASEDISC, PREVIZIONAT, PROCTVA, CODANALIZANOD, CODCENTRU)
    SELECT CODNCREDIT1, CODNCREDIT, 'T', VALOARE, VALOAREOLD, VALDIF, CODOBLIGSTINS, CODDOC, TIPDOC, CODOBLIGSTINGATOR, OBS, CODCLASEDISC, PREVIZIONAT, PROCTVA,
    CODANALIZANOD, CODCENTRU
    FROM TMP_NOTECREDITT;

    INSERT INTO TMP_NOTECREDIT1 ( CODNCREDIT1, CODNCREDIT, TIPOPER, VALOARE, VALOAREOLD, VALDIF, CODOBLIGSTINS, CODDOC, TIPDOC, CODOBLIGSTINGATOR, OBS, CODCLASEDISC,
    CODNCREDIT1ORIG, PROCTVA, CODANALIZANOD, CODCENTRU)
    SELECT CODNCREDIT1, CODNCREDIT, 'V', VALOARE, VALOAREOLD, VALDIF, CODOBLIGSTINS, CODDOC, TIPDOC, CODOBLIGSTINGATOR, OBS, CODCLASEDISC, CODNCREDIT1ORIG, PROCTVA,
    CODANALIZANOD, CODCENTRU
    FROM TMP_NOTECREDITV;

    if vAreCorectii &gt; 0 then
      UPDATE tmp_notecreditz tmpz
      set
        valoare = valoare - coalesce(( select sum(coalesce(valoare, 0) - coalesce(valoareold, 0)) from notecredit1 where codncredit1orig = tmpz.codncredit1 ), 0) ;
    end if;
    INSERT INTO TMP_NOTECREDIT1 ( CODNCREDIT1, CODNCREDIT, TIPOPER, VALOARE, VALOAREOLD, VALDIF, CODOBLIGSTINS, CODDOC, TIPDOC, CODOBLIGSTINGATOR, OBS,
    CODNCREDIT1ORIG, CODDISCOUNT, VALDOC, VALLEI, PROCTVA, CODANALIZANOD, CODCENTRU)
    SELECT CODNCREDIT1, CODNCREDIT, 'Z', VALOARE, VALOAREOLD, VALDIF, CODOBLIGSTINS, CODDOC, TIPDOC, CODOBLIGSTINGATOR, OBS, CODNCREDIT1ORIG, CODDISCOUNT,
    VALDOC, VALLEI, PROCTVA, CODANALIZANOD, CODCENTRU
    FROM TMP_NOTECREDITZ;
    INSERT INTO TMP_NOTECREDIT1 ( CODNCREDIT1, CODNCREDIT, TIPOPER, VALOARE, VALOAREOLD, VALDIF, CODOBLIGSTINS, CODDOC, TIPDOC, CODOBLIGSTINGATOR, OBS,
    CODCLASEDISC, PROCTVA, CODANALIZANOD, CODCENTRU)
    SELECT CODNCREDIT1, CODNCREDIT, 'C', VALOARE, VALOAREOLD, VALDIF, CODOBLIGSTINS, CODDOC, TIPDOC, CODOBLIGSTINGATOR, OBS, CODCLASEDISC, PROCTVA,
    CODANALIZANOD, CODCENTRU
    FROM TMP_NOTECREDITC;

    INSERT INTO TMP_NOTECREDIT1 ( CODNCREDIT1, CODNCREDIT, TIPOPER, VALOARE, VALOAREOLD, VALDIF, CODOBLIGSTINS, CODDOC, TIPDOC, CODOBLIGSTINGATOR, OBS,
    CODANALIZANOD, CODCENTRU)
    SELECT CODNCREDIT1, CODNCREDIT, 'P', VALOARE, VALOAREOLD, VALDIF, CODOBLIGSTINS, CODDOC, TIPDOC, CODOBLIGSTINGATOR, OBS,
    CODANALIZANOD, CODCENTRU
    FROM TMP_NOTECREDITP;

    DELETE FROM NOTECREDIT1 NC1
    WHERE NC1.CodNCredit = RecId and NC1.CODNCREDIT1 not in (SELECT CodNCredit1 FROM TMP_NOTECREDIT1 );

    for v_rec in (SELECT * FROM TMP_NOTECREDITT ) loop
      if coalesce(v_rec.CodNCredit1, 0) &gt; 0 then
        UPDATE NOTECREDIT1
        set
          TipOper           = 'T',
          Valoare           = v_Rec.Valoare,
          ValoareOld        = v_Rec.ValoareOld,
          ValDif            = v_rec.valdif,
          CodNCredit1Orig   = v_Rec.CodNCredit1Orig,
          CodObligStins     = v_rec.CodObligStins,
          CodDoc            = v_Rec.CodDoc,
          TipDoc            = v_Rec.TipDoc,
          CodObligStingator = v_rec.CodObligStingator,
          Obs               = v_rec.obs,
          CODCLASEDISC      = V_REC.CODCLASEDISC,
          PREVIZIONAT       = V_REC.PREVIZIONAT,
          Tip               = current_setting('PKG_NOTECREDIT.tncTermen', true)::numeric,
          ProcTVA           = v_rec.ProcTVA,
          CODANALIZANOD     = v_rec.CODANALIZANOD,
          CODCENTRU         = v_rec.CODCENTRU
        where
          CodNCredit1 = v_rec.CodNCredit1 ;
      else
        INSERT INTO NOTECREDIT1 ( CODNCREDIT1, CODNCREDIT, TIPOPER, VALOARE, VALOAREOLD, VALDIF, CODOBLIGSTINS, CODDOC, TIPDOC, CODOBLIGSTINGATOR, OBS,
        CODCLASEDISC, PREVIZIONAT, TIP, PROCTVA, CODANALIZANOD, CODCENTRU)
        values ( nextval('SEQ_NOTECREDIT1_CODNCREDIT1'),
        RecId,
        'T',
        v_rec.VALOARE,
        v_rec.VALOAREOLD,
        V_REC.VALDIF,
        v_rec.CODOBLIGSTINS,
        v_rec.CODDOC,
        v_rec.TIPDOC,
        v_rec.CODOBLIGSTINGATOR,
        v_rec.Obs,
        V_REC.CODCLASEDISC,
        V_REC.PREVIZIONAT,
        current_setting('PKG_NOTECREDIT.tncTermen', true)::numeric,
        v_rec.PROCTVA,
        v_rec.CODANALIZANOD, v_rec.CODCENTRU);
      end if;
    end loop;
    for v_rec in (SELECT * FROM TMP_NOTECREDITV ) loop
      if coalesce(v_rec.CodNCredit1, 0) &gt; 0 then
        UPDATE NOTECREDIT1
        set
          TipOper           = 'V',
          Valoare           = v_Rec.Valoare,
          ValoareOld        = v_Rec.ValoareOld,
          ValDif            = v_rec.valdif,
          CodObligStins     = v_rec.CodObligStins,
          CodDoc            = v_Rec.CodDoc,
          TipDoc            = v_Rec.TipDoc,
          CodObligStingator = v_rec.CodObligStingator,
          Obs               = v_rec.obs,
          CODCLASEDISC      = V_REC.CODCLASEDISC,
          Tip               = current_setting('PKG_NOTECREDIT.tncVolum', true)::numeric,
          CODNCREDIT1ORIG   = V_REC.CODNCREDIT1ORIG,
          ProcTVA           = v_rec.ProcTVA,
          CODANALIZANOD     = v_rec.CODANALIZANOD,
          CODCENTRU         = v_rec.CODCENTRU
        where
          CodNCredit1 = v_rec.CodNCredit1 ;
      else
        INSERT INTO NOTECREDIT1 ( CODNCREDIT1, CODNCREDIT, TIPOPER, VALOARE, VALOAREOLD, VALDIF, CODOBLIGSTINS, CODDOC, TIPDOC, CODOBLIGSTINGATOR, OBS,
        CODCLASEDISC, TIP, CODNCREDIT1ORIG, PROCTVA,
        CODANALIZANOD, CODCENTRU)
        values ( nextval('SEQ_NOTECREDIT1_CODNCREDIT1'),
        RecId,
        'V',
        v_rec.VALOARE,
        v_rec.VALOAREOLD,
        V_REC.VALDIF,
        v_rec.CODOBLIGSTINS,
        v_rec.CODDOC,
        v_rec.TIPDOC,
        v_rec.CODOBLIGSTINGATOR,
        v_rec.Obs,
        V_REC.CODCLASEDISC,
        current_setting('PKG_NOTECREDIT.tncVolum', true)::numeric,
        V_REC.CODNCREDIT1ORIG,
        v_rec.proctva,
        v_rec.CODANALIZANOD, v_rec.CODCENTRU);
      end if;
    end loop;

    for v_rec in (SELECT * FROM TMP_NOTECREDITZ ) loop
      if coalesce(v_rec.CodNCredit1, 0) &gt; 0 then
        UPDATE NOTECREDIT1
        set
          TipOper           = 'Z',
          Valoare           = v_Rec.Valoare,
          ValoareOld        = v_Rec.ValoareOld,
          ValDif            = v_rec.valdif,
          CodObligStins     = v_rec.CodObligStins,
          CodNCredit1Orig   = v_rec.CodNCredit1Orig,
          CodDoc            = v_Rec.CodDoc,
          TipDoc            = v_Rec.TipDoc,
          CodObligStingator = v_rec.CodObligStingator,
          Obs               = v_rec.obs,
          CODCLASEDISC      = V_REC.CODCLASEDISC,
          CODDISCOUNT       = V_REC.CODDISCOUNT,
          VALDOC            = V_REC.VALDOC,
          VALLEI            = V_REC.VALLEI,
          TIP               = current_setting('PKG_NOTECREDIT.tncProvizioane', true)::numeric,
          PROCTVA           = V_REC.PROCTVA,
          CODANALIZANOD     = v_rec.CODANALIZANOD,
          CODCENTRU         = v_rec.CODCENTRU
        where
          CodNCredit1 = v_rec.CodNCredit1 ;
      else
        INSERT INTO NOTECREDIT1 ( CODNCREDIT1, CODNCREDIT, TIPOPER, VALOARE, VALDIF, VALOAREOLD, CODOBLIGSTINS, CODDOC, TIPDOC, CODOBLIGSTINGATOR, OBS,
        CODCLASEDISC, CODNCREDIT1ORIG, CODDISCOUNT, VALDOC, VALLEI, TIP, PROCTVA,
        CODANALIZANOD, CODCENTRU)
        values ( nextval('SEQ_NOTECREDIT1_CODNCREDIT1'),
        RecId,
        'Z',
        v_rec.VALOARE,
        v_rec.VALOAREOLD,
        V_REC.VALDIF,
        v_rec.CODOBLIGSTINS,
        v_rec.CODDOC,
        v_rec.TIPDOC,
        v_rec.CODOBLIGSTINGATOR,
        v_Rec.Obs,
        V_REC.CODCLASEDISC,
        V_REC.CODNCREDIT1ORIG,
        V_REC.CODDISCOUNT,
        V_REC.VALDOC,
        V_REC.VALLEI,
        current_setting('PKG_NOTECREDIT.tncProvizioane', true)::numeric,
        V_REC.PROCTVA,
        v_rec.CODANALIZANOD, v_rec.CODCENTRU);
      end if;
    end loop;

    for v_rec in (SELECT * FROM TMP_NOTECREDITC ) loop
      if coalesce(v_rec.CodNCredit1, 0) &gt; 0 then
        UPDATE NOTECREDIT1
        set
          TipOper           = 'C',
          Valoare           = v_Rec.Valoare,
          ValoareOld        = v_Rec.ValoareOld,
          ValDif            = v_rec.valdif,
          CodObligStins     = v_rec.CodObligStins,
          CodDoc            = v_Rec.CodDoc,
          TipDoc            = v_Rec.TipDoc,
          CodObligStingator = v_rec.CodObligStingator,
          Obs               = v_rec.obs,
          CODCLASEDISC      = V_REC.CODCLASEDISC,
          TIP               = current_setting('PKG_NOTECREDIT.tncCantitate', true)::numeric,
          ProcTVA           = v_rec.ProcTVA,
          CODANALIZANOD     = v_rec.CODANALIZANOD,
          CODCENTRU         = v_rec.CODCENTRU
        where
          CodNCredit1 = v_rec.CodNCredit1 ;
      else
        INSERT INTO NOTECREDIT1 ( CODNCREDIT1, CODNCREDIT, TIPOPER, VALOARE, VALOAREOLD, CODOBLIGSTINS, CODDOC, TIPDOC, CODOBLIGSTINGATOR, OBS, VALDIF,
        CODCLASEDISC, TIP, PROCTVA ,CODANALIZANOD, CODCENTRU)
        values ( nextval('SEQ_NOTECREDIT1_CODNCREDIT1'),
        RecId,
        'C',
        v_rec.VALOARE,
        v_rec.VALOAREOLD,
        v_rec.CODOBLIGSTINS,
        v_rec.CODDOC,
        v_rec.TIPDOC,
        v_rec.CODOBLIGSTINGATOR,
        v_rec.OBS,
        V_REC.VALDIF,
        V_REC.CODCLASEDISC,
        current_setting('PKG_NOTECREDIT.tncCantitate', true)::numeric,
        v_rec.proctva,
        v_rec.CODANALIZANOD, v_rec.CODCENTRU);
      end if;
    end loop;

    for v_rec in (SELECT * FROM TMP_NOTECREDITP ) loop
      if coalesce(v_rec.CodNCredit1, 0) &gt; 0 then
        UPDATE NOTECREDIT1
        set
          TipOper           = 'P',
          Valoare           = v_Rec.Valoare,
          ValoareOld        = v_Rec.ValoareOld,
          ValDif            = v_rec.valdif,
          CodObligStins     = v_rec.CodObligStins,
          CodDoc            = v_Rec.CodDoc,
          TipDoc            = v_Rec.TipDoc,
          CodObligStingator = v_rec.CodObligStingator,
          Obs               = v_rec.obs,
          Tip               = current_setting('PKG_NOTECREDIT.tncPenalizari', true)::NUMERIC,
          CODANALIZANOD     = v_rec.CODANALIZANOD,
          CODCENTRU         = v_rec.CODCENTRU
        where
          CodNCredit1 = v_rec.CodNCredit1 ;
      else
        INSERT INTO NOTECREDIT1 ( CODNCREDIT1, CODNCREDIT, TIPOPER, VALOARE, VALOAREOLD, VALDIF, CODOBLIGSTINS, CODDOC, TIPDOC, CODOBLIGSTINGATOR, OBS, TIP,
        CODANALIZANOD, CODCENTRU)
        values ( nextval('SEQ_NOTECREDIT1_CODNCREDIT1'),
        RecId,
        'P',
        v_rec.VALOARE,
        v_rec.VALOAREOLD,
        V_REC.VALDIF,
        v_rec.CODOBLIGSTINS,
        v_rec.CODDOC,
        v_rec.TIPDOC,
        v_rec.CODOBLIGSTINGATOR,
        v_Rec.Obs,
        current_setting('PKG_NOTECREDIT.tncPenalizari', true)::numeric,
        v_rec.CODANALIZANOD, v_rec.CODCENTRU);
      end if;
    end loop;

    DELETE FROM notecreditfact
    WHERE ( codncredit = recid) and ( codncfact not in (SELECT codncfact FROM tmp_notecreditfact )) ;

    for v_rec in (SELECT * FROM TMP_NOTECREDITFACT ) loop
      if coalesce(v_rec.CodNCFact, 0) &gt; 0 then
        UPDATE NOTECREDITFACT
        set
          CODDOC    = v_rec.coddoc,
          TIPDOC    = v_Rec.TIPDOC,
          PREFIXDOC = v_rec.PREFIXDOC,
          NRDOC     = v_Rec.NRDOC,
          DATADOC   = v_Rec.DATADOC,
          VALDOC    = v_Rec.ValDoc,
          VALT      = v_rec.VALT,
          CODDOC1   = V_REC.CODDOC1
        where
          CodNCFact = v_rec.CodNCFact ;
      else
        INSERT INTO NOTECREDITFACT ( CODNCFACT, CODNCREDIT, CODDOC, TIPDOC, PREFIXDOC, NRDOC, DATADOC, VALDOC, VALT, CODDOC1)
        values ( nextval('SEQ_NOTECREDITFACT_CODNCFACT'),
        RecId,
        v_rec.CODDOC,
        v_rec.TIPDOC,
        v_rec.PREFIXDOC,
        v_rec.NRDOC,
        v_rec.DATADOC,
        v_rec.VALDOC,
        v_rec.VALT,
        V_REC.CODDOC1);
      end if;
    end loop;

    DELETE FROM nccadouri
    WHERE ( codncredit = recid) and ( codnccadouri not in (SELECT codnccadouri FROM tmp_nccadouri )) ;

    for v_rec in (SELECT * FROM TMP_NCCadouri ) loop
      if coalesce(v_rec.CodNCCadouri, 0) &gt; 0 then
        UPDATE Nccadouri
        set
          Codobiect        = v_rec.Codobiect,
          Codobiectasoc    = v_rec.Codobiectasoc,
          Codarticol       = v_rec.Codarticol,
          Umsec            = v_rec.Umsec,
          Diferente        = v_rec.Diferente,
          Codobiectasocsec = v_rec.Codobiectasocsec,
          Cant             = v_Rec.Cant,
          CantFact         = v_Rec.CantFact,
          CODANALIZANOD    = v_rec.CODANALIZANOD,
          CODCENTRU        = v_rec.CODCENTRU
        where
          CodNCCadouri = v_rec.CodNCCadouri ;
      else
        INSERT INTO NCCadouri ( Codnccadouri, Codncredit, Codobiect, Codobiectasoc, Codarticol, Umsec, Diferente, Codobiectasocsec, Cant, CantFact,
        CODANALIZANOD, CODCENTRU)
        values ( nextval('SEQ_NCCADOURI_CODNCCADOURI'),
        RecId,
        v_rec.Codobiect,
        v_rec.Codobiectasoc,
        v_rec.Codarticol,
        v_rec.Umsec,
        v_rec.Diferente,
        v_rec.codobiectasocsec,
        v_Rec.cant,
        v_rec.cantfact,
        v_rec.CODANALIZANOD, v_rec.CODCENTRU);
      end if;
    end loop;

    DELETE FROM CENTRALIZARENC
    WHERE ( codncredit = recid) and ( CODCENTRALIZARE not in (SELECT CODCENTRALIZARE FROM TMP_CENTRALIZARENC )) ;

    for v_rec in (SELECT * FROM TMP_CENTRALIZARENC ) loop
      if coalesce(v_rec.CodCentralizare, 0) &gt; 0 then
        UPDATE CENTRALIZARENC
        set
          CODARTICOL       = V_REC.CODARTICOL,
          CODOBIECT        = V_REC.CODOBIECT,
          CODOBIECTASOC    = V_REC.CODOBIECTASOC,
          CODOBIECTASOCSEC = V_REC.CODOBIECTASOCSEC,
          UMSEC            = V_REC.UMSEC,
          DIFERENTE        = V_REC.DIFERENTE,
          TIPARTICOL       = V_REC.TIPARTICOL,
          FACTURAT         = V_REC.FACTURAT,
          PROCTVA          = V_REC.PROCTVA,
          CODCENTRU        = V_REC.CODCENTRU,
          CODANALIZANOD    = V_REC.CODANALIZANOD,
          OBS              = V_REC.OBS,
          CANT             = V_REC.CANT
        where
          CodCentralizare = v_rec.CodCentralizare ;
      else
        INSERT INTO CENTRALIZARENC ( CODCENTRALIZARE, CODNCREDIT, CODARTICOL, CODOBIECT, CODOBIECTASOC, CODOBIECTASOCSEC, UMSEC, DIFERENTE, TIPARTICOL, FACTURAT,
        PROCTVA, CODCENTRU, CODANALIZANOD, OBS, CANT )
        values ( nextval('SEQ_CENTRALIZARENC_CODC'),
        recid,
        v_rec.CODARTICOL,
        v_rec.CODOBIECT,
        v_rec.CODOBIECTASOC,
        v_rec.CODOBIECTASOCSEC,
        v_rec.UMSEC,
        v_rec.DIFERENTE,
        v_rec.TIPARTICOL,
        V_REC.FACTURAT,
        V_REC.PROCTVA,
        V_REC.CODCENTRU,
        V_REC.CODANALIZANOD,
        V_REC.OBS,
        V_REC.CANT);
      end if;
    end loop;

    DELETE FROM JURNAl1
    WHERE TIPDOC = vTipDoc and CODDOC = RECID and CODJURNAL1 not in (SELECT CODJURNAL1 FROM TMP_JURNAl1 );

    for V_REC in (SELECT * FROM TMP_JURNAL1 ) loop
      if V_REC.CODJURNAL1 &gt; 0 then
        UPDATE JURNAL1
        SET
          CODDOC        = V_REC.CODDOC,
          TIPDOC        = V_REC.TIPDOC,
          INDEXLOCAL    = V_REC.INDEXLOCAL,
          CODBAZAD      = V_REC.CODBAZAD,
          ICONTBAZAD    = V_REC.ICONTBAZAD,
          TIPBAZAD      = V_REC.TIPBAZAD,
          CODBAZAC      = V_REC.CODBAZAC,
          ICONTBAZAC    = V_REC.ICONTBAZAC,
          TIPBAZAC      = V_REC.TIPBAZAC,
          CODDESCRD     = V_REC.CODDESCRD,
          ICONTD        = V_REC.ICONTD,
          TIPCONTD      = V_REC.TIPCONTD,
          ANALITICCONTD = V_REC.ANALITICCONTD,
          CODDESCRC     = V_REC.CODDESCRC,
          ICONTC        = V_REC.ICONTC,
          TIPCONTC      = V_REC.TIPCONTC,
          ANALITICCONTC = V_REC.ANALITICCONTC,
          GEST          = V_REC.GEST,
          VALOARE       = V_REC.VALOARE,
          VALOAREV      = V_REC.VALOAREV,
          OBS           = V_REC.OBS,
          AN            = V_REC.AN,
          LUNA          = V_REC.LUNA,
          DIRTY         = V_REC.DIRTY,
          SUBUNITATEA   = V_REC.SUBUNITATEA,
          DATADOC       = V_REC.DATADOC,
          document      = V_REC.DOCUMENT,
          CODCENTRU     = V_REC.CODCENTRU,
          CODANALIZANOD = V_REC.CODANALIZANOD
        where
          CODJURNAL1 = V_REC.CODJURNAl1 ;
      else
        INSERT INTO JURNAL1 ( CODJURNAL1, CODDOC, TIPDOC, INDEXLOCAL, CODBAZAD, ICONTBAZAD, TIPBAZAD, CODDESCRD, ICONTD, TIPCONTD,
                              ANALITICCONTD, CODBAZAC, ICONTBAZAC, TIPBAZAC, CODDESCRC, ICONTC, TIPCONTC, ANALITICCONTC, GEST, VALOARE,
                              VALOAREV, OBS, AN, LUNA, DIRTY, SUBUNITATEA, DATADOC, DOCUMENT, CODCENTRU, CODANALIZANOD)
        values ( nextval('SEQ_JURNAL1_CODJURNAL1'),
        RECID,
        V_REC.TIPDOC,
        V_REC.INDEXLOCAL,
        V_REC.CODBAZAD,
        V_REC.ICONTBAZAD,
        V_REC.TIPBAZAD,
        V_REC.CODDESCRD,
        V_REC.ICONTD,
        V_REC.TIPCONTD,
        V_REC.ANALITICCONTD,
        V_REC.CODBAZAC,
        V_REC.ICONTBAZAC,
        V_REC.TIPBAZAC,
        V_REC.CODDESCRC,
        V_REC.ICONTC,
        V_REC.TIPCONTC,
        V_REC.ANALITICCONTC,
        V_REC.GEST,
        V_REC.VALOARE,
        V_REC.VALOAREV,
        V_REC.OBS,
        V_REC.AN,
        V_REC.LUNA,
        V_REC.DIRTY,
        V_REC.SUBUNITATEA,
        V_REC.DATADOC,
        V_REC.DOCUMENT,
        V_REC.CODCENTRU,
        V_REC.CODANALIZANOD
      );
      end if;
    end loop;

    DELETE FROM JURNAL
    WHERE TIPDOC = vTipDoc and CODDOC = RECID and CODJURNAL not in (SELECT CODJURNAL FROM TMP_JURNAl );

    for V_REC in (SELECT * FROM TMP_JURNAL ) loop
      if V_REC.CODJURNAL &gt; 0 then
        UPDATE JURNAL
        set
          CODDOC      = V_REC.CODDOC,
          TIPDOC      = V_REC.TIPDOC,
          INDEXLOCAL  = V_REC.INDEXLOCAL,
          CONTD       = V_REC.CONTD,
          CONTC       = V_REC.CONTC,
          GEST        = V_REC.GEST,
          VALOARE     = V_REC.VALOARE,
          VALOAREV    = V_REC.VALOAREV,
          OBS         = V_REC.OBS,
          AN          = V_REC.AN,
          LUNA        = V_REC.LUNA,
          SUBUNITATEA = V_REC.SUBUNITATEA,
          DATADOC     = V_REC.DATADOC,
          document    = V_REC.DOCUMENT,
          CODCENTRU   = V_REC.CODCENTRU,
          CODANALIZANOD = V_REC.CODANALIZANOD

        where
          CODJURNAL = V_REC.CODJURNAl ;
      else
        INSERT INTO JURNAL ( CODJURNAL, CODDOC, TIPDOC, INDEXLOCAL, CONTD, CONTC, GEST, VALOARE, VALOAREV, OBS, AN, LUNA, SUBUNITATEA, DATADOC, DOCUMENT, CODCENTRU, CODANALIZANOD)
        values ( nextval('SEQ_JURNAL_CODJURNAL'),
        RECID,
        V_REC.TIPDOC,
        V_REC.INDEXLOCAL,
        V_REC.CONTD,
        V_REC.CONTC,
        V_REC.GEST,
        V_REC.VALOARE,
        V_REC.VALOAREV,
        V_REC.OBS,
        V_REC.AN,
        V_REC.LUNA,
        V_REC.SUBUNITATEA,
        V_REC.DATADOC,
        V_REC.DOCUMENT,
        V_REC.CODCENTRU,
        V_REC.CODANALIZANOD);
      end if;
    end loop;
  ELSE
    SELECT nextval('SEQ_NOTECREDIT_CODNCREDIT') INTO RecId;

    if (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT
        FROM   PKG_USERFIRME_ValidPostLog(null, current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_NOTECREDIT.CT_MONITOR', true)))
    then
      perform pkg_userfirme_postlogcucommit('NOTECREDIT', current_setting('PKG_GLOBALS.USERNAME', true),
                                            'A', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true),
                                            aCodSubunit, aDataDoc, aDoc, null, current_setting('PKG_GLOBALS.EXE_VERSION', true));
    end if;

    INSERT INTO NOTECREDIT ( CodNCredit, CodContract2, CodPart, TipDoc, Subunitatea, DataStart, CODCONTV, CODCONTT, CODCONTC, CODCONTP,
                             DataStop, An, Luna, DataFact, TipArticol, Obs, CodContract, CodMoneda, VOLUMPEARTICOLE, CODCONTZ, PRETBRUTC,
                             PRETBRUTV, CODCARNET, Trimestriala, Corectie, CodNCCorectie, PrefixDoc, CarnetDoc, NrDoc, SeriaDoc, userid,
                             datacreare, Previzionare, IesiriPeVolum, Curs, Inchisa, ValOrigTer, CODANALIZA)
    select
      RecId,
      tmp.CodContract2,
      tmp.CodPart,
      tmp.TipDoc,
      tmp.Subunitatea,
      tmp.DataStart,
      tmp.CODCONTV,
      tmp.CODCONTT,
      tmp.CODCONTC,
      tmp.CODCONTP,
      tmp.DataStop,
      tmp.An,
      tmp.Luna,
      tmp.DataFact,
      Tmp.TipArticol,
      Tmp.obs,
      TMP.codcontract,
      TMP.CODMONEDA,
      tmp.volumpearticole,
      TMP.CODCONTZ,
      TMP.PRETBRUTC,
      TMP.PRETBRUTV,
      TMP.CODCARNET,
      TMP.Trimestriala,
      TMP.Corectie,
      TMP.CodNCCorectie,
      TMP.PrefixDoc,
      TMP.CarnetDoc,
      TMP.NrDoc,
      TMP.SeriaDoc,
      current_setting('PKG_GLOBALS.USERID', true)::numeric,
      current_timestamp,
      tmp.Previzionare,
      tmp.Iesiripevolum,
      TMP.Curs,
      tmp.Inchisa,
      tmp.ValOrigTer,
      tmp.CODANALIZA
    FROM TMP_NOTECREDIT tmp;

    INSERT INTO NOTECREDIT1 ( CodNCredit1, CodNCredit, Valoare, ValoareOld, ValDif, CodObligStins, TipOper, CodDoc, TipDoc, CodObligStingator, Obs, CODCLASEDISC,
    PREVIZIONAT, TIP, PROCTVA, CODANALIZANOD,
      CODCENTRU)
    select
      nextval('SEQ_NOTECREDIT1_CODNCREDIT1'),
      RecId,
      Valoare,
      ValoareOld,
      ValDif,
      CodObligStins,
      'T',
      CodDoc,
      TipDoc,
      CodObligStingator,
      Obs,
      CODCLASEDISC,
      PREVIZIONAT,
      current_setting('PKG_NOTECREDIT.tncTermen', true)::numeric,
      PROCTVA,
      CODANALIZANOD,
      CODCENTRU
    FROM TMP_NOTECREDITT;

    INSERT INTO NOTECREDIT1 ( CodNCredit1, CodNCredit, Valoare, ValoareOld, ValDif, CodObligStins, TipOper, CodDoc, TipDoc, CodObligStingator, Obs, CODCLASEDISC,
    TIP, CODNCREDIT1ORIG, PROCTVA,CODANALIZANOD,
      CODCENTRU)
    select
      nextval('SEQ_NOTECREDIT1_CODNCREDIT1'),
      RecId,
      Valoare,
      ValoareOld,
      ValDif,
      CodObligStins,
      'V',
      CodDoc,
      TipDoc,
      CodObligStingator,
      Obs,
      CODCLASEDISC,
      current_setting('PKG_NOTECREDIT.tncVolum', true)::numeric,
      CODNCREDIT1ORIG,
      PROCTVA,
      CODANALIZANOD,
      CODCENTRU
    FROM TMP_NOTECREDITV;

    INSERT INTO NOTECREDIT1 ( CodNCredit1, CodNCredit, Valoare, ValoareOld, ValDif, CodObligStins, TipOper, CodDoc, TipDoc, CodObligStingator, Obs, CODCLASEDISC,
    CODNCREDIT1ORIG, CODDISCOUNT, VALDOC, VALLEI, TIP, PROCTVA,
    CODANALIZANOD,
    CODCENTRU)
    select
      nextval('SEQ_NOTECREDIT1_CODNCREDIT1'),
      RecId,
      Valoare,
      ValoareOld,
      ValDif,
      CodObligStins,
      'Z',
      CodDoc,
      TipDoc,
      CodObligStingator,
      Obs,
      CODCLASEDISC,
      CODNCREDIT1ORIG,
      CODDISCOUNT,
      VALDOC,
      VALLEI,
      current_setting('PKG_NOTECREDIT.tncProvizioane', true)::numeric,
      PROCTVA,
      CODANALIZANOD,
      CODCENTRU
    FROM TMP_NOTECREDITZ;

    INSERT INTO NOTECREDIT1 ( CodNCredit1, CodNCredit, Valoare, ValoareOld, ValDif, CodObligStins, TipOper, CodDoc, TipDoc, CodObligStingator, Obs, CODCLASEDISC,
    TIP, PROCTVA,
    CODANALIZANOD,
    CODCENTRU)
    select
      nextval('SEQ_NOTECREDIT1_CODNCREDIT1'),
      RecId,
      Valoare,
      ValoareOld,
      ValDif,
      CodObligStins,
      'C',
      CodDoc,
      TipDoc,
      CodObligStingator,
      Obs,
      CODCLASEDISC,
      current_setting('PKG_NOTECREDIT.tncCantitate', true)::numeric,
      PROCTVA,
      CODANALIZANOD,
      CODCENTRU
    FROM TMP_NOTECREDITC;

    INSERT INTO NOTECREDIT1 ( CodNCredit1, CodNCredit, Valoare, ValoareOld, ValDif, CodObligStins, TipOper, CodDoc, TipDoc, CodObligStingator, Obs, TIP,
    CODANALIZANOD,
    CODCENTRU)
    select
      nextval('SEQ_NOTECREDIT1_CODNCREDIT1'),
      RecId,
      Valoare,
      ValoareOld,
      ValDif,
      CodObligStins,
      'P',
      CodDoc,
      TipDoc,
      CodObligStingator,
      Obs,
      current_setting('PKG_NOTECREDIT.tncPenalizari', true)::NUMERIC,
      CODANALIZANOD,
      CODCENTRU
    FROM TMP_NOTECREDITP;

    INSERT INTO NOTECREDITFACT ( CODNCFACT, CODNCREDIT, CODDOC, TIPDOC, PREFIXDOC, NRDOC, DATADOC, VALDOC, VALT, CODDOC1)
    select
      nextval('SEQ_NOTECREDITFACT_CODNCFACT'),
      RecId,
      CODDOC,
      TIPDOC,
      PREFIXDOC,
      NRDOC,
      DATADOC,
      VALDOC,
      VALT,
      CODDOC1
    FROM tmp_notecreditfact;

    INSERT INTO NCCadouri ( Codnccadouri, Codncredit, Codobiect, Codobiectasoc, Codarticol, Umsec, Diferente, Codobiectasocsec, Cant, CantFact,
    CODANALIZANOD,
    CODCENTRU)
    select
      nextval('SEQ_NCCADOURI_CODNCCADOURI'),
      RecId,
      Codobiect,
      Codobiectasoc,
      Codarticol,
      Umsec,
      Diferente,
      Codobiectasocsec,
      Cant,
      CantFact,
      CODANALIZANOD,
      CODCENTRU
    FROM tmp_nccadouri;

    INSERT INTO CENTRALIZARENC ( CODCENTRALIZARE, CODNCREDIT, CODARTICOL, CODOBIECT, CODOBIECTASOC, CODOBIECTASOCSEC, UMSEC, DIFERENTE, TIPARTICOL, FACTURAT,
    PROCTVA, CODCENTRU, CODANALIZANOD,
    OBS, CANT )
    select
      nextval('SEQ_CENTRALIZARENC_CODC'),
      recid,
      CODARTICOL,
      CODOBIECT,
      CODOBIECTASOC,
      CODOBIECTASOCSEC,
      UMSEC,
      DIFERENTE,
      TIPARTICOL,
      FACTURAT,
      PROCTVA,
      CODCENTRU,
      CODANALIZANOD,
      OBS,
      CANT
    FROM TMP_CENTRALIZARENC;

    INSERT INTO JURNAL1 ( CODJURNAL1, CODDOC, TIPDOC, INDEXLOCAL, CODBAZAD, ICONTBAZAD, TIPBAZAD, CODDESCRD, ICONTD, TIPCONTD, ANALITICCONTD, CODBAZAC, ICONTBAZAC,
    TIPBAZAC, CODDESCRC, ICONTC, TIPCONTC, ANALITICCONTC, GEST, VALOARE, VALOAREV, OBS, AN, LUNA, DIRTY, SUBUNITATEA, DATADOC, DOCUMENT,
    CODCENTRU, CODANALIZANOD)
      (
      select
        nextval('SEQ_JURNAL1_CODJURNAL1'),
        RECID,
        TIPDOC,
        INDEXLOCAL,
        CODBAZAD,
        ICONTBAZAD,
        TIPBAZAD,
        CODDESCRD,
        ICONTD,
        TIPCONTD,
        ANALITICCONTD,
        CODBAZAC,
        ICONTBAZAC,
        TIPBAZAC,
        CODDESCRC,
        ICONTC,
        TIPCONTC,
        ANALITICCONTC,
        GEST,
        VALOARE,
        VALOAREV,
        OBS,
        AN,
        LUNA,
        DIRTY,
        SUBUNITATEA,
        DATADOC,
        DOCUMENT,
        CODCENTRU, CODANALIZANOD
      FROM TMP_JURNAL1 );

    INSERT INTO JURNAL ( CODJURNAL, CODDOC, TIPDOC, INDEXLOCAL, CONTD, CONTC, GEST, VALOARE, VALOAREV, OBS, AN, LUNA, SUBUNITATEA, DATADOC, DOCUMENT, CODCENTRU, CODANALIZANOD)
      (
      select
        nextval('SEQ_JURNAL_CODJURNAL'),
        RECID,
        TIPDOC,
        INDEXLOCAL,
        CONTD,
        CONTC,
        GEST,
        VALOARE,
        VALOAREV,
        OBS,
        AN,
        LUNA,
        SUBUNITATEA,
        DATADOC,
        DOCUMENT,
        CODCENTRU, CODANALIZANOD
      FROM TMP_JURNAL );
  end if;

  for V_REC in (SELECT * FROM TMP_RULAJ ) loop
    SELECT count(*) INTO NR
    FROM NCONTRUL
    WHERE
      CODCONT  = V_REC.CODCONT
      and AN   = current_setting('PKG_GLOBALS.ANLUCRU'  , true)::numeric
      and LUNA = current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric;

    if NR = 0 then
      INSERT INTO NCONTRUL ( CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, AN, LUNA )
      values ( nextval('SEQ_NCONTRUL_CODCONTRUL'),
      V_REC.CODCONT,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric,
      current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric );
    end if;

    UPDATE NCONTRUL
    set
      RULAJCD  = RULAJCD  + (CASE when V_REC.TIP = 'D' then V_REC.VALOARE  else 0 end ) ,
      RULAJCC  = RULAJCC  + (CASE when V_REC.TIP = 'C' then V_REC.VALOARE  else 0 end ) ,
      RULAJVCD = RULAJVCD + (CASE when V_REC.TIP = 'D' then V_REC.VALOAREV else 0 end ) ,
      RULAJVCC = RULAJVCC + (CASE when V_REC.TIP = 'C' then V_REC.VALOAREV else 0 end )
    where
      CODCONT  = V_REC.CODCONT
      and AN   = current_setting('PKG_GLOBALS.ANLUCRU'  , true)::numeric
      and LUNA = current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric ;

    if coalesce(V_REC.SUBUNITATEA, 0) &lt;&gt; 0 then
      for V_REC_SUB in (SELECT * FROM NCONTRUL
                        WHERE
                          CODCONT  = V_REC.CODCONT
                          and AN   = current_setting('PKG_GLOBALS.ANLUCRU'  , true)::numeric
                          and LUNA = current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric
                       )
      loop
        SELECT count(*) INTO NR FROM NCONTRULSUB WHERE CODCONTRUL = V_REC_SUB.CODCONTRUL and SUBUNITATEA = V_REC.SUBUNITATEA;

        if NR = 0 then
          INSERT INTO NCONTRULSUB ( CODCONTRULSUB, CODCONTRUL, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, SUBUNITATEA )
          values ( nextval('SEQ_NCONTRULSUB_CODRULSUB'), V_REC_SUB.CODCONTRUL, 0, 0, 0, 0, 0, 0, 0, 0, V_REC.SUBUNITATEA );
        end if;

        UPDATE NCONTRULSUB
        set
          RULAJCD  = RULAJCD  + (CASE when V_REC.TIP = 'D' then V_REC.VALOARE  else 0 end ) ,
          RULAJCC  = RULAJCC  + (CASE when V_REC.TIP = 'C' then V_REC.VALOARE  else 0 end ) ,
          RULAJVCD = RULAJVCD + (CASE when V_REC.TIP = 'D' then V_REC.VALOAREV else 0 end ) ,
          RULAJVCC = RULAJVCC + (CASE when V_REC.TIP = 'C' then V_REC.VALOAREV else 0 end )
        where
          CODCONTRUL = V_REC_SUB.CODCONTRUL
          and SUBUNITATEA = V_REC.SUBUNITATEA ;
      end loop;
    end if;
  end loop;

  perform PKG_GLOBALS_MarkDirtyJurnal();

  if    ( current_setting('PKG_NOTECREDIT.CARNETDOC_I', true)::numeric &lt;&gt; 0)
    and ( current_setting('PKG_NOTECREDIT.NRDOC_I', true)::numeric &lt;&gt; 0)
    and ( ACARNETDOC &lt;&gt; current_setting('PKG_NOTECREDIT.CARNETDOC_I', true)::numeric
         or
          ANRDOC &lt;&gt; current_setting('PKG_NOTECREDIT.NRDOC_I', true)::NUMERIC
        )
  then
    perform PKG_CARNETEDOC_RELEASENUMARDOC(current_setting('PKG_NOTECREDIT.CARNETDOC_I', true)::numeric,
                                           current_setting('PKG_NOTECREDIT.NRDOC_I', true)::numeric);
    perform PKG_CARNETEDOC_COMPACTEAZAINTERVALE(current_setting('PKG_NOTECREDIT.CARNETDOC_I', true)::numeric);
  end if;

  if ACARNETDOC &lt;&gt; 0 then
    perform PKG_CARNETEDOC_SOLVENUMARDOC(ACARNETDOC, (ANRDOC)::character varying);
  end if;

  perform NotifyModif(OPERATION, RECID, 'CONTRACT');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_test1</obj_name>
  <obj_hashval>558bbd3f44e28a639fe7cd272906c537</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_test1()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM tmp_manevra_liste;
  INSERT INTO tmp_manevra_liste(filtru, valoare) VALUES('CODPART', 240);
  PERFORM PKG_NOTECREDIT_GEN_TMP_PEN(0, '05.11.2019', 0, 0, 1, '05.11.2019', 1,NULL);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_npartretail_clear_part_tables</obj_name>
  <obj_hashval>8b7b0d438cdf23008809d2bb3e7b9215</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_npartretail_clear_part_tables()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM TMP_MANEVRA;
  DELETE FROM TMP_NPART;
  DELETE FROM TMP_NPART1;
  DELETE FROM TMP_NPARTCODFISC;
  DELETE FROM TMP_NPARTTR;
  DELETE FROM TMP_NPARTDISC;
  DELETE FROM TMP_NPARTB;
  DELETE FROM TMP_NAGENDA;
  DELETE FROM TMP_NLOCALIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_npartretail_prepare_part_baza_for_sync</obj_name>
  <obj_hashval>b2b678c8003cf34dc2b9b6be5c469369</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_npartretail_prepare_part_baza_for_sync(acodpostretail numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM TMP_MANEVRA;
  DELETE FROM TMP_NPART;
  DELETE FROM TMP_NPART1;
  DELETE FROM TMP_NPARTCODFISC;
  DELETE FROM TMP_NPARTTR;
  DELETE FROM TMP_NPARTDISC;
  DELETE FROM TMP_NPARTB;
  DELETE FROM TMP_NAGENDA;
  DELETE FROM TMP_NLOCALIT;

  INSERT INTO TMP_MANEVRA(CODUNIC)
  SELECT CODSYNCPART FROM SYNCPARTRETAIL WHERE SINCRONIZAT = 0 AND  CODPOSTRETAIL = aCODPOSTRETAIL;

  INSERT INTO TMP_NPART(CODPART, DEN_PART, REGCOM, CODEXTERN, CODMONEDA, AUTORIZATIE, CODINTERN, CODCLASA, CODCATEGPRET, TIPPART, SCADENTAC, SCADENTAV, DISCOUNT, CODCATEGDISC, BLOCAT, TIPPARTENER, DATAADAUGARII, OBS, POZA, PERSOANAFIZICA, COLDISCOUNT, INFOBLOCAT, EXPIRAREAUTORIZ, CODSTATISTICBNR, MUSAICOLET, STRATEGIC, CIFRAAFACERI, DOMENIUACTIV, NRANGAJATI, SURSALEAD, LEAD, TVALAINCASARE, MODAPLICPROCDISC, PROCCURSTRANSF, FIDELIZARE, DATANASTERE, MAJORARI, TIPBLOCAJ, POPRIRE_ANAF, CODRESPONSABIL, CODDOMENIUACT, DOCDEFONORCOM, MODPROMOFACTCOM, VALIDAREPRETOFERTA, IESCUCOMANDA, CANTMINCMD, ZIAPROVIZ, PERAPROVIZ)
  SELECT P.CODPART, P.DEN_PART, P.REGCOM, P.CODEXTERN, P.CODMONEDA, P.AUTORIZATIE, P.CODINTERN, P.CODCLASA, P.CODCATEGPRET, P.TIPPART, P.SCADENTAC, P.SCADENTAV, P.DISCOUNT, P.CODCATEGDISC, P.BLOCAT, P.TIPPARTENER, P.DATAADAUGARII, P.OBS, P.POZA, P.PERSOANAFIZICA, P.COLDISCOUNT, P.INFOBLOCAT, P.EXPIRAREAUTORIZ, P.CODSTATISTICBNR, P.MUSAICOLET, P.STRATEGIC, P.CIFRAAFACERI, P.DOMENIUACTIV, P.NRANGAJATI, P.SURSALEAD, P.LEAD, P.TVALAINCASARE, P.MODAPLICPROCDISC, P.PROCCURSTRANSF, P.FIDELIZARE, P.DATANASTERE, P.MAJORARI, P.TIPBLOCAJ, P.POPRIRE_ANAF, P.CODRESPONSABIL, P.CODDOMENIUACT, P.DOCDEFONORCOM, P.MODPROMOFACTCOM, P.VALIDAREPRETOFERTA, P.IESCUCOMANDA, P.CANTMINCMD, P.ZIAPROVIZ, P.PERAPROVIZ
  FROM NPART P, TMP_MANEVRA M, SYNCPARTRETAIL SY
  WHERE M.CODUNIC = SY.CODSYNCPART AND  SY.CODPART = P.CODPART;

  INSERT INTO TMP_NPART1(CODPART1, CODPART, CODIOPART, CREDITCLIENT, VOLUMTRANZC, CREDITFURN, VOLUMTRANZF, ANSTART, LUNASTART, SCADENTAV, SCADENTAC, DISCOUNT, CASSBAZAMIN, SIMBOLCASS)
  SELECT P1.CODPART1, P1.CODPART, P1.CODIOPART, P1.CREDITCLIENT, P1.VOLUMTRANZC, P1.CREDITFURN, P1.VOLUMTRANZF, P1.ANSTART, P1.LUNASTART, P1.SCADENTAV, P1.SCADENTAC, P1.DISCOUNT, P1.CASSBAZAMIN, P1.SIMBOLCASS
  FROM NPART1 P1, TMP_MANEVRA M, SYNCPARTRETAIL SY
  WHERE M.CODUNIC = SY.CODSYNCPART AND  SY.CODPART = P1.CODPART;

  INSERT INTO TMP_NPARTCODFISC(COD_CODFISCAL, CODPART, CODFISCAL, PRINCIPAL)
  SELECT P.COD_CODFISCAL, P.CODPART, P.CODFISCAL, PRINCIPAL
  FROM NPARTCODFISC P, TMP_MANEVRA M, SYNCPARTRETAIL SY
  WHERE M.CODUNIC = SY.CODSYNCPART AND  SY.CODPART = P.CODPART;

  INSERT INTO TMP_NPARTTR(CODPARTTR, CODPART, DELEGAT, CNP, DOC, SERIEDOC, NRDOC, ELIBERAT, MIJLTRANSP, NRTRANSP, ACTIV, DATADOC, CODPERS, CODAUTO, IMPLICIT, OBS, PERMIS, NRPASS, CODTARA, ADRESA, CODLOCALIT, TELEFON, EMAIL)
  SELECT P.CODPARTTR, P.CODPART, P.DELEGAT, P.CNP, P.DOC, P.SERIEDOC, P.NRDOC, P.ELIBERAT, P.MIJLTRANSP, P.NRTRANSP, P.ACTIV, P.DATADOC, P.CODPERS, P.CODAUTO, P.IMPLICIT, P.OBS, P.PERMIS, P.NRPASS, P.CODTARA, P.ADRESA, P.CODLOCALIT, P.TELEFON, P.EMAIL
  FROM NPARTTR P, TMP_MANEVRA M, SYNCPARTRETAIL SY
  WHERE M.CODUNIC = SY.CODSYNCPART AND  SY.CODPART = P.CODPART;

  INSERT INTO TMP_NPARTDISC(CODPARTDISC, CODPART, CODCATEGDISC, INDEXLOCAL)
  SELECT P.CODPARTDISC, P.CODPART, P.CODCATEGDISC, P.INDEXLOCAL
  FROM NPARTDISC P, TMP_MANEVRA M, SYNCPARTRETAIL SY
  WHERE M.CODUNIC = SY.CODSYNCPART AND  SY.CODPART = P.CODPART;

  INSERT INTO TMP_NPARTB(CODPARTB, CODPART, CODBANK, IMPLICIT, CODLOCALIT, CONTBANCA, SUCURSALA, CODSWIFT, CODMONEDA, TIPCOMISION, OBS)
  SELECT P.CODPARTB, P.CODPART, P.CODBANK, P.IMPLICIT, P.CODLOCALIT, P.CONTBANCA, P.SUCURSALA, P.CODSWIFT, P.CODMONEDA, P.TIPCOMISION, P.OBS
  FROM NPARTB P, TMP_MANEVRA M, SYNCPARTRETAIL SY
  WHERE M.CODUNIC = SY.CODSYNCPART AND  SY.CODPART = P.CODPART;

  INSERT INTO TMP_NAGENDA(CODAGENDA, TIP, CODLOCALIT, SEDIUSOCIAL, TELEFON, FAX, EMAIL, SECTOR, STRADA, NR1, NR2, BLOC, SCARA, ETAJ, APART, CODPOSTAL, KM, OBS, CODBANKCONT, CODPART, CODGEST, CODSUBUNIT, CODTIPSEDIU, CODFISCAL, CODAGENT, CODCLIENT, CODTRASEU, POZTRASEU, CODTRASEU1, POZTRASEU1, INACTIV, CODCORESP, TRANSPCLIENT, COEFUTILAJE, SUPRAFATA, MODSERVIRE, IDSEDIU, COD_CODFISCAL, TELEFONP, EDI_EXPTIP, EDI_PARTTIP, EDI_PARTID, EDI_OBJTIP, GLN, GESTLIVRARE, LONGITUDINE, LATITUDINE, OBS2, EDI_IMPTIP, EDI_FURNTIP, EDI_FURNID, EDI_OBJTIPIMP, EDI_EXPCUMUL, EDI_EXPEAN)
  SELECT P.CODAGENDA, P.TIP, P.CODLOCALIT, P.SEDIUSOCIAL, P.TELEFON, P.FAX, P.EMAIL, P.SECTOR, P.STRADA, P.NR1, P.NR2, P.BLOC, P.SCARA, P.ETAJ, P.APART, P.CODPOSTAL, P.KM, P.OBS, P.CODBANKCONT, P.CODPART, P.CODGEST, P.CODSUBUNIT, P.CODTIPSEDIU, P.CODFISCAL, P.CODAGENT, P.CODCLIENT, P.CODTRASEU, P.POZTRASEU, P.CODTRASEU1, P.POZTRASEU1, P.INACTIV, P.CODCORESP, P.TRANSPCLIENT, P.COEFUTILAJE, P.SUPRAFATA, P.MODSERVIRE, P.IDSEDIU, P.COD_CODFISCAL, P.TELEFONP, P.EDI_EXPTIP, P.EDI_PARTTIP, P.EDI_PARTID, P.EDI_OBJTIP, P.GLN, P.GESTLIVRARE, P.LONGITUDINE, P.LATITUDINE, P.OBS2, P.EDI_IMPTIP, P.EDI_FURNTIP, P.EDI_FURNID, P.EDI_OBJTIPIMP, P.EDI_EXPCUMUL, P.EDI_EXPEAN
  FROM NAGENDA P, TMP_MANEVRA M, SYNCPARTRETAIL SY
  WHERE M.CODUNIC = SY.CODSYNCPART AND  SY.CODPART = P.CODPART;

  INSERT INTO TMP_NLOCALIT(CODLOCALIT, DEN_LOCALIT, TIP, CODJUDET, OBS, CODTARA, DENSUP, SIRUTA, CODZONA, LATITUDINE, LONGITUDINE)
  SELECT L.CODLOCALIT, L.DEN_LOCALIT, L.TIP, L.CODJUDET, L.OBS, L.CODTARA, L.DENSUP, L.SIRUTA, L.CODZONA, L.LATITUDINE, L.LONGITUDINE
  FROM TMP_NAGENDA A, NLOCALIT L
  WHERE COALESCE( A.CODLOCALIT, 0) &lt;&gt; 0 AND  L.CODLOCALIT = A.CODLOCALIT;

  INSERT INTO TMP_NLOCALIT(CODLOCALIT, DEN_LOCALIT, TIP, CODJUDET, OBS, CODTARA, DENSUP, SIRUTA, CODZONA, LATITUDINE, LONGITUDINE)
  SELECT L.CODLOCALIT, L.DEN_LOCALIT, L.TIP, L.CODJUDET, L.OBS, L.CODTARA, L.DENSUP, L.SIRUTA, L.CODZONA, L.LATITUDINE, L.LONGITUDINE
  FROM TMP_NPARTB A, NLOCALIT L
  WHERE COALESCE( A.CODLOCALIT, 0) &lt;&gt; 0 AND  L.CODLOCALIT = A.CODLOCALIT;

  INSERT INTO TMP_NLOCALIT(CODLOCALIT, DEN_LOCALIT, TIP, CODJUDET, OBS, CODTARA, DENSUP, SIRUTA, CODZONA, LATITUDINE, LONGITUDINE)
  SELECT L.CODLOCALIT, L.DEN_LOCALIT, L.TIP, L.CODJUDET, L.OBS, L.CODTARA, L.DENSUP, L.SIRUTA, L.CODZONA, L.LATITUDINE, L.LONGITUDINE
  FROM TMP_NPARTTR A, NLOCALIT L
  WHERE COALESCE( A.CODLOCALIT, 0) &lt;&gt; 0 AND  L.CODLOCALIT = A.CODLOCALIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_npartretail_set_flag_modif</obj_name>
  <obj_hashval>65aa0ef6a1b48e63bacd77172e9283a1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_npartretail_set_flag_modif(acodpartretail numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  UPDATE NPARTRETAIL SET TIPMODIF = 'M' WHERE CODPARTRETAIL = aCODPARTRETAIL;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nzone_sp_postrecords</obj_name>
  <obj_hashval>a071fc14d8ff4b7abfb60dd2f1782d96</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nzone_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  operation = 0 THEN
    SELECT codzona INTO RecId FROM tmp_nzone;

    UPDATE nzone
    SET
    (den_zona, SIMBOL, OBS) = (SELECT den_zona, SIMBOL, OBS FROM tmp_nzone)
    WHERE
     codzona = recid;
  ELSE
    SELECT NEXTVAL('SEQ_NZONE_CODZONA') INTO RECID;

    INSERT INTO nzone(codzona, den_zona, simbol, obs)
    SELECT RECID, den_zona, simbol, obs FROM tmp_nzone;
  END IF;

  PERFORM NotifyModif( OPERATION, RECID, 'NZONE');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_obiective_sp_gotorecord</obj_name>
  <obj_hashval>da3ad43b529a688e78fd8640df8f842d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_obiective_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_OBIECTIVE
  SELECT * FROM OBIECTIVE WHERE CodOBIECTIV = RECID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oferta_getcodoferta1pretminpart</obj_name>
  <obj_hashval>628ab27e6059ef5dab795f7f0a5669f0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oferta_getcodoferta1pretminpart(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT adata date, INOUT acodoferta numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  vPret double precision;
begin
  vPret := 0;
  FOR v_rec IN
  (
  SELECT o1.codoferta1, o1.pret
  FROM nartobj obj
      INNER JOIN oferta1 o1 ON  o1.codobiect = obj.codobiect
      INNER JOIN oferta  o  ON  o.codoferta  = o1.codoferta
  WHERE
     o1.codobiect = aCodObiect and  o.CodOferta = aCodOferta
  )
  LOOP
    vPret := v_rec.Pret;
    EXIT ;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_opreg_sp_postrecords</obj_name>
  <obj_hashval>9b918dcb4742454be73215b0ae298ba6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_opreg_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  vCod  numeric;
begin
  IF  Operation = 0 THEN
    SELECT CodOp INTO RecId FROM TMP_OPREG;

    UPDATE OPREG
    SET
    (CODOP, CODPART, CODBanca, OBS, TIPTRANZ, TIPDECONT, ZIDECONT, CODMONEDA, VALOARE, AN_Start, LUNA_Start, AN_MAX, LUNA_MAX, SUBUNITATEA)
    =
    (SELECT CODOP, CODPART, CODBanca, OBS, TIPTRANZ, TIPDECONT, ZIDECONT, CODMONEDA, VALOARE, AN_Start, LUNA_Start, AN_MAX, LUNA_MAX, SUBUNITATEA
     FROM TMP_OPREG
    )
    WHERE
     CodOp = RecId;

    DELETE FROM OpReg1 WHERE CodOp = RecID AND CodOp1 NOT IN (SELECT CodOp1 FROM TMP_OpReg1);

    FOR v_rec IN (SELECT CodOp1, CODOP, TERMEN, Stins, Obs FROM TMP_OpReg1 ORDER BY TERMEN) LOOP
      IF  COALESCE( v_rec.CodOp1, 0) &gt; 0 THEN
        UPDATE OpReg1
        SET
        CodOp1 = v_rec.CodOp1,
        CODOP  = v_rec.CODOP,
        TERMEN = v_rec.TERMEN,
        Stins  = v_rec.Stins,
        Obs    = v_rec.Obs
        WHERE
         CodOp1 = v_rec.CodOp1;
      ELSE
        SELECT NEXTVAL('SEQ_OPREG1_CODOPREG1') INTO vCod;

        INSERT INTO OpReg1(CodOp1, CODOP, TERMEN, Stins, Obs)
        VALUES(vCod, RecId, v_rec.TERMEN, v_rec.Stins, v_rec.Obs);
      END IF;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_OPREG_CODOP') INTO RecID;

    INSERT INTO OPREG(CODOP, CODPART, CODBanca, OBS, TIPTRANZ, TIPDECONT, ZIDECONT, CODMONEDA, VALOARE, AN_Start, LUNA_Start, AN_MAX, LUNA_MAX, SUBUNITATEA)
    (SELECT RecId, CODPART, CODBanca, OBS, TIPTRANZ, TIPDECONT, ZIDECONT, CODMONEDA, VALOARE, AN_Start, LUNA_Start, AN_MAX, LUNA_MAX, SUBUNITATEA
     FROM TMP_OPREG
    );

    FOR v_rec IN (SELECT CodOp1, CODOP, TERMEN, Stins, Obs FROM TMP_OpReg1 ORDER BY TERMEN) LOOP
      SELECT NEXTVAL('SEQ_OPREG1_CODOPREG1') INTO vCod;

      INSERT INTO OpReg1(CodOp1, CODOP, TERMEN, Stins, Obs)
      VALUES(vCod, RecId, v_rec.TERMEN, v_rec.Stins, v_rec.Obs);
    END LOOP;
  END IF;

  PERFORM NotifyModif( OPERATION, RECID, 'OPREG');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_set_interval_dinamic</obj_name>
  <obj_hashval>fc48a266cb19c2161b00ff2ae6077ec4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_set_interval_dinamic(INOUT acodjob1 numeric, INOUT adataini character varying, INOUT adatafin character varying, INOUT alunaanini numeric, INOUT alunaanfin numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  dDataIni date;
  dDataFin date;
BEGIN
  -- Stef 27.07.2020
  dDataIni := To_Date( aDataIni, 'dd.mm.yyyy');
  dDataFin := To_Date( aDataFin, 'dd.mm.yyyy');
  PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC( aCodJob1, dDataIni, dDataFin, aLunaAnIni, aLunaAnFin);
  aDataIni := To_Char( dDataIni, 'dd.mm.yyyy');
  aDataFin := To_Char( dDataFin, 'dd.mm.yyyy');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_orar_initenviroment</obj_name>
  <obj_hashval>70b0d3f79c99c3dcb80be255cc7cf050</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_orar_initenviroment(acodjob numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  NULL;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pachete_carnetdoc_i</obj_name>
  <obj_hashval>51fc919c8ff74840707dcc8d41d744be</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pachete_carnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PACHETE.CARNETDOC_I', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pachete_getnrdoc_i</obj_name>
  <obj_hashval>ff79533267cde6fd6678d979e6e6dfac</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pachete_getnrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PACHETE.NRDOC_I', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pachete_getpartener</obj_name>
  <obj_hashval>cd2509434e8c192747875974f15c62c5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pachete_getpartener(INOUT wme_result character varying, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
aDenPart varchar;
begin
  --Florin 12.01.2022 - sinc. Oracle (11.01.2022)
SELECT CASE
 when P.TipPart = 'PARTENER' or P.TIPPART IS NULL then PA.Den_Part
 WHEN  P.TipPart = 'SUBUNITATE' THEN S.Den_Subunit
 WHEN  P.TipPart = 'GESTIUNE' THEN G.Den_Gest

 END
INTO aDenPart
FROM pachete p
LEFT JOIN NPART PA ON  P.CodPart = PA.CodPart
LEFT JOIN NGEST G ON  P.CodPart = G.Codgest
LEFT JOIN NSUBUNIT S ON  P.CodPart = S.CodSubunit
WHERE
   p.codpachete = recid;
WME_Result :=  adenpart;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pachete_nrdoc_i</obj_name>
  <obj_hashval>181388a5563a1539654fa9783857448b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pachete_nrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PACHETE.NRDOC_I', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pachete_setcarnetdoc_i</obj_name>
  <obj_hashval>6c65ebd0ea10f01a82979fadfe0bfb21</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pachete_setcarnetdoc_i(acarnetdoc_i numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PACHETE.CARNETDOC_I',to_char(aCARNETDOC_I,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pachete_sp_gotorecord</obj_name>
  <obj_hashval>23984af38e786c9bcba2a382074cb1c6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pachete_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Florin 12.04.2023 - sinc. Oracle (10.04.2023)
  --Florin 06.03.2023 - fixat 57477
  --Florin 03.03.2023 - sinc. Oracle
  --Florin 29.06.2022 - fnc_getprocenttvaart
  --Florin 16.05.2022 - sinc. Oracle (13.05.2022)
  --Florin 05.05.2022 - sinc. Oracle (04.05.2022)
  --Florin 04.03.2022 - sinc. Oracle (03.03.2022)
  --Florin 16.11.2021 - fixat 52001
  --Florin 11.01.2022 - sinc. Oracle
  --Florin 12.01.2022 - sinc. Oracle
  --Florin 28.01.2022 - sinc. Oracle (25.01.2022)
  perform pkg_pachete_setct_monitor('MON_61');
  INSERT INTO TMP_PACHETE (CodPachete, DataP, UserID, DataCreare,
      Subunitate, Gestiune, CarnetDoc, NrDoc,
      Colector, DataColectare, Verificator, DataVerificare,
      Transportator, DataTransport, NrPachete, Operat,
      Blocat, Anulat, IdentificatorP, Listat,
      An, Luna, CodPart, TipPart,
      Sediu, Delegat, SerieDoc, Den_Part,
      Masa, Volum, Den_Sediu, NumeDelegat,
      TipLivrare, TipPachet, Sponsorizare) (   SELECT P.codpachete, P.DataP, P.UserID,
        P.DataCreare, P.Subunitate, P.Gestiune, P.CarnetDoc,
        P.NrDoc, P.Colector, P.DataColectare, P.Verificator,
        P.DataVerificare, P.Transportator, P.DataTransport, P.NrPachete,
        P.Operat, P.Blocat, P.Anulat, P.IdentificatorP,
        P.Listat, P.An, P.Luna, P.CodPart,
        P.TipPart, P.Sediu, P.Delegat, DC.Serie,
        CASE
          WHEN P.TipPart = 'PARTENER' THEN PA.Den_Part
          WHEN P.TipPart = 'SUBUNITATE' THEN S.Den_Subunit
          WHEN P.TipPart = 'GESTIUNE' THEN G.Den_Gest
        END DEN_PART,
        COALESCE ( (SELECT PKG_PACHETE_GetMasa.WME_RESULT  FROM PKG_PACHETE_GetMasa  (NULL,RecId)) , 0) ,
        COALESCE ( (SELECT PKG_PACHETE_GetVolum.WME_RESULT FROM PKG_PACHETE_GetVolum (NULL,RecId)) , 0) ,
        A.obs, TR.Delegat, COALESCE (P.TipLivrare, 3) , COALESCE (P.TipPachet, 0), COALESCE(Sponsorizare, 0)
      FROM PACHETE           P
        LEFT JOIN DOCCARNETE DC ON P.CARNETDOC = DC.CODCARNET
        LEFT JOIN NPART      PA ON P.CodPart   = PA.CodPart
        LEFT JOIN NGEST      G  ON P.CodPart   = G.Codgest
        LEFT JOIN NSUBUNIT   S  ON P.CodPart   = S.CodSubunit
        LEFT JOIN NAGENDA    A  ON P.Sediu     = A.CODAGENDA
        LEFT JOIN NPARTTR    TR ON P.Delegat   = TR.CodPartTr
      WHERE
        codpachete = RecId);

  INSERT INTO TMP_PACHETE1 (CodPachete, CodDoc, TipDoc, DenTipDoc, SerieDoc, NrDoc, DataDoc, CodPart, Partener)
  SELECT  DISTINCT POBJL.CodPachete CODPACHETE, I.CODIES CODDOC, I.TipDoc TIPDOC, I.PrefixDoc PREFIXDOC,
      I.SERIADOC, I.NrDoc NRDOC, I.DataDoc DATADOC, I.Partener, P.Den_Part
  FROM PACHETEOBJL       POBJL
    INNER JOIN LIVR1     L1  ON L1.CODLIVR1  = POBJL.CODLIVR1
    INNER JOIN LIVR      L   ON L.CODLIVR    = L1.CODLIVR
    INNER JOIN IESIRI1   I1  ON I1.CODIES1   = L1.CODIES1
    INNER JOIN IESIRI    I   ON I1.CODIES    = I.CodIes AND COALESCE (I.Anulat, 0) &lt;&gt; 1 AND L.CODIES = I.CODIES
    LEFT JOIN DOCCARNETE DCI ON I.CarnetDoc  = DCI.CodCarnet
    LEFT JOIN NPART      P   ON I.Partener   = P.CodPart
    LEFT JOIN NSUBUNIT   S   ON I.Codsubunit = S.CodSubunit
  WHERE
    POBJL.CodPachete = RecId
  UNION ALL
                      SELECT distinct
                             POBJL.CodPachete CodPachete,
                             C.CODCOMANDA CodDoc,
                             C.TipDoc TipDoc,
                             C.PrefixDoc PrefixDoc,
                             C.SERIADOC,
                             C.NrDoc NrDoc,
                             C.DataDoc DataDoc,
                             C.Partener,
                             P.Den_Part
                      FROM PACHETEOBJL POBJL
                           INNER JOIN REZERVATS R ON POBJL.CODREZERVATS = R.CODREZERVATS
                           INNER JOIN COMANDA1 C1 ON C1.CODCOMANDA1 = R.CODCOMANDA1
                           INNER JOIN COMANDA C ON C1.CODCOMANDA = C.CODCOMANDA
                           INNER JOIN NPART P ON C.Partener = P.CodPart
                      WHERE POBJL.CodPachete = RecId
                      ;

  FOR v_rec IN (SELECT p1.*
                FROM pachete1 p1 INNER JOIN tmp_pachete1 tmp ON tmp.coddoc = p1.coddoc and tmp.tipdoc = p1.tipdoc
                WHERE p1.codpachete = recid)
  LOOP
    UPDATE tmp_pachete1
    SET codpachete1 = v_rec.codpachete1
    WHERE
      coddoc = v_rec.coddoc and tipdoc = v_rec.tipdoc;
  END LOOP;

  INSERT INTO TMP_PACHETEOBJ (CODPACHETEOBJ, CODPACHETE, CODNIRSTOC, CANT, REST, LIVRAT, DEN_UM1, DENUMIRE)
  SELECT POBJ.CODPACHETEOBJ, POBJ.CODPACHETE, POBJ.CODNIRSTOC, POBJ.CANT, POBJ.REST, POBJ.CANT - POBJ.REST, NUM1.DEN_UM1, OBJ.DENUMIRE
  FROM PACHETEOBJ          POBJ
    INNER JOIN NIRSTOC     NS  ON POBJ.CODNIRSTOC = NS.CODNIRSTOC
    INNER JOIN NARTOBJ     OBJ ON OBJ.CODOBIECT   = NS.CODOBIECT
    INNER JOIN NUM1            ON NUM1.CODUM1     = NS.UMSEC
  WHERE
    POBJ.CODPACHETE = RECID;

  INSERT INTO TMP_PACHETEOBJL (codpacheteobjl, codpachete, codlivr1, cant, rest, cantum1, codrezervats, CODDOC, TIPDOC,
                               DenObiect, UM, Den_UM1, CodObiect, CantAmb, Colete, CantMin, CodAmb, OK, DenAmb, CodGest, DenUM1, D1, D2, D3, pachet, MasaU, VolumU, Masa, Volum, Pret, Valoare, CodComanda1)
  SELECT PL.codpacheteobjl, PL.codpachete, PL.codlivr1, PL.cant, PL.rest, PL.cantum1, PL.codrezervats, I.CODIES CODDOC, I.TIPDOC,
         CASE WHEN COALESCE (L1.CodNirStoc, 0) = 0 THEN OBJVAL.Denumire ELSE OBJ.Denumire END DENUMIRE, ART.UM, UM1.Den_UM1, I1.CodObiect,
         AMB.CANT CANTAMB, 0 COLETE, AMB.CantMin, AMB.CODOBIECTRETURN CODAMB,
         0 OK, AMB.DENUMIRE DENAMB, COALESCE (NIR.GEST, LVAL.GEST) CODGEST, UMS.Den_UM DENUM1, NS.D1, NS.D2, NS.D3, COALESCE(PL.Pachet,0), OBJ.MASA, OBJ.VOLUM, OBJ.MASA * PL.CANT, OBJ.Volum * PL.CANT,
         COALESCE(I1.PU,0), COALESCE(I1.PU,0) * PL.CANT, 0
  FROM PACHETEOBJL     PL
    INNER JOIN LIVR1   L1     ON PL.CodLivr1    = L1.CodLivr1
    INNER JOIN IESIRI1 I1     ON I1.CODIES1     = L1.CODIES1
    INNER JOIN IESIRI  I      ON I1.CodIes      = I.CodIes AND COALESCE (I.Anulat, 0) &lt;&gt; 1
    INNER JOIN LIVR    L      ON I.CodIes       = L.CodIes AND L1.CODLIVR = L.CODLIVR
    LEFT JOIN NIRSTOC  NS     ON L1.CodNIRStoc  = NS.CodNIRStoc
    LEFT JOIN NIR      NIR    ON NS.CODNIR      = NIR.CODNIR
    LEFT JOIN LIVRVAL  LVAL   ON LVAL.CodLivr1  = L1.CODLIVR1
    LEFT JOIN NIRSER   NSR    ON L1.CodNIRSer   = NSR.CodNIRSer
    LEFT JOIN NSERII   SR     ON NSR.CodSerie   = SR.CodSerie
    LEFT JOIN NARTOBJ  OBJ    ON NS.CodObiect   = OBJ.CodObiect
    LEFT JOIN NART     ART    ON OBJ.CodArticol = ART.CodArticol
    LEFT JOIN NARTOBJ  OBJVAL ON LVAL.CodObiect = OBJVAL.CodObiect
    LEFT JOIN NUM1     UM1    ON L1.UMSec       = UM1.CodUM1
    LEFT JOIN NUM      UMS    ON ART.UM1        = UMS.CodUM
    LEFT JOIN (SELECT A.*, O.DENUMIRE
               FROM NARTAMB  A
                    INNER JOIN (SELECT CODOBIECT, COUNT(*) CATE FROM NARTAMB GROUP BY CODOBIECT HAVING COUNT(*) = 1) AMBUNIC ON AMBUNIC.CODOBIECT = A.CODOBIECT
                    INNER JOIN NARTOBJ O ON O.CODOBIECT = A.CODOBIECTRETURN
              ) AMB ON AMB.CODOBIECT = I1.CODOBIECT
  WHERE
    PL.CODPACHETE = RECID
  UNION ALL
  SELECT
    PL.codpacheteobjl,
    PL.codpachete,
    PL.codlivr1,
    PL.cant,
    PL.rest,
    PL.cantum1,
    PL.codrezervats,
    C.CODCOMANDA CODDOC,
    C.TIPDOC,
    OBJ.Denumire,
    ART.UM,
    UM1.Den_UM1,
    C1.CodObiect,
    AMB.CANT CantAmb,
    0 Colete,
    AMB.CantMin,
    AMB.CODOBIECTRETURN CodAmb,
    0 OK,
    AMB.DENUMIRE DenAmb,
    NIR.GEST CodGest,
    UMS.Den_UM DenUM1,
    NS.D1,
    NS.D2,
    NS.D3,
    COALESCE(PL.Pachet,0),
    OBJ.MASA,
    OBJ.VOLUM,
    OBJ.MASA * PL.CANT,
    OBJ.VOLUM * PL.CANT,
    PKG_PRETURI_WMROTOPRET(OBJ.ROTUNJIRE, CASE WHEN C.PRETCUAMANUNT = 1 THEN (C1.PU *100) / (100 + fnc_getprocenttvaart(OBJ.CodArticol,C.AN,C.LUNA)) ELSE C1.PU END),
    PKG_PRETURI_WMROTOPRET(OBJ.ROTUNJIRE, CASE WHEN C.PRETCUAMANUNT = 1 THEN (C1.PU *100) / (100 + fnc_getprocenttvaart(OBJ.CodArticol,C.AN,C.LUNA)) ELSE C1.PU END) * PL.CANT,
    C1.CODCOMANDA1
  FROM PACHETEOBJL PL
       INNER JOIN REZERVATS R ON PL.CODREZERVATS = R.CODREZERVATS
       INNER JOIN COMANDA1 C1 ON C1.CODCOMANDA1 = R.CODCOMANDA1
       INNER JOIN COMANDA C ON C.CODCOMANDA = C1.CODCOMANDA
       LEFT JOIN NIRSTOC NS ON R.CodNIRStoc = NS.CodNIRStoc
       LEFT JOIN NIR NIR ON NS.CODNIR = NIR.CODNIR
       LEFT JOIN NIRSER NSR ON R.CodNIRSer = NSR.CodNIRSer
       LEFT JOIN NSERII SR ON NSR.CodSerie = SR.CodSerie
       LEFT JOIN NARTOBJ OBJ ON NS.CodObiect = OBJ.CodObiect
       LEFT JOIN NART ART ON OBJ.CodArticol = ART.CodArticol
       LEFT JOIN NUM1 UM1 ON R.UMSec = UM1.CodUM1
       LEFT JOIN NUM UMS ON ART.UM1 = UMS.CodUM
       LEFT JOIN (SELECT A.*, O.DENUMIRE
                  FROM NARTAMB A
                       INNER JOIN (
                                   select CODOBIECT, COUNT(*) CATE
                                   from NARTAMB
                                   GROUP BY CODOBIECT
                                   HAVING COUNT(*) = 1
                                   ) AMBUNIC ON AMBUNIC.CODOBIECT = A.CODOBIECT
                       INNER JOIN NARTOBJ O ON O.CODOBIECT = A.CODOBIECTRETURN
                 ) AMB ON AMB.CODOBIECT = R.CODOBIECT
  WHERE PL.CODPACHETE = RECID;

  INSERT INTO TMP_PACHETEGEST (CODGEST)
  SELECT  DISTINCT CODGEST FROM TMP_PACHETEOBJL;

  UPDATE TMP_PACHETEGEST TMP
  SET DEN_GEST = (SELECT DEN_GEST FROM NGEST WHERE CODGEST = TMP.CODGEST);
  INSERT INTO TMP_PACHETECOL(PACHET,
                             MASA,
                             VOLUM, VALOARE)
  SELECT COALESCE(PACHET,0), SUM(COALESCE(MASA,0)), SUM(COALESCE(VOLUM,0)), SUM(coalesce(VALOARE, 0))
  FROM TMP_PACHETEOBJL
  GROUP BY COALESCE(PACHET,0);

   update tmp_pachete set nrpachete = (select count(1)
                                      from (select distinct pachet from tmp_pacheteobjl where pachet &gt; 0) A_PG
                                     ),
                         valoare = (select sum(coalesce(valoare,0)) from tmp_pacheteobjl);

    for v_rec in (select coddoc, tipdoc from tmp_pachete1) loop
    update tmp_pachete1 set
    masa = (
    select sum
      (
        COALESCE(PKOBJL.Cant,0) * coalesce(OBJ.Masa, 0)
      )
      FROM TMP_PACHETEOBJL PKOBJL
           INNER JOIN REZERVATS R ON R.CODREZERVATS = PKOBJL.CODREZERVATS
           INNER JOIN NIRSTOC NS ON R.CodNIRStoc = NS.CodNIRStoc
           INNER JOIN NARTOBJ OBJ ON NS.CodObiect = OBJ.CodObiect
      WHERE PKOBJL.CODDOC = V_REC.CODDOC AND PKOBJL.TIPDOC = V_REC.TIPDOC
    ),
    volum = (
    select sum
      (
        COALESCE(PKOBJL.Cant,0) * coalesce(OBJ.VOLUM, 0)
      )
      FROM TMP_PACHETEOBJL PKOBJL
           INNER JOIN REZERVATS R ON R.CODREZERVATS = PKOBJL.CODREZERVATS
           INNER JOIN NIRSTOC NS ON R.CodNIRStoc = NS.CodNIRStoc
           INNER JOIN NARTOBJ OBJ ON NS.CodObiect = OBJ.CodObiect
      WHERE PKOBJL.CODDOC = V_REC.CODDOC AND PKOBJL.TIPDOC = V_REC.TIPDOC
    ),
    valoare = (
    select sum
      (
        COALESCE(PKOBJL.Cant,0) * coalesce(PKOBJL.PRET, 0)
      )
      FROM TMP_PACHETEOBJL PKOBJL
      WHERE PKOBJL.CODDOC = V_REC.CODDOC AND PKOBJL.TIPDOC = V_REC.TIPDOC
    )
    where coddoc = v_rec.coddoc and tipdoc = v_rec.tipdoc;
  end loop;

  for v_rec in (select codgest from tmp_pachetegest) loop
    update tmp_pachetegest set
    masa = (
    select sum
      (
        COALESCE(PKOBJL.Cant,0) * coalesce(OBJ.Masa, 0)
      )
      FROM TMP_PACHETEOBJL PKOBJL
           INNER JOIN REZERVATS R ON R.CODREZERVATS = PKOBJL.CODREZERVATS
           INNER JOIN NIRSTOC NS ON R.CodNIRStoc = NS.CodNIRStoc
           INNER JOIN NARTOBJ OBJ ON NS.CodObiect = OBJ.CodObiect
      WHERE PKOBJL.CODGEST = V_REC.CODGEST
    ),
    volum = (
    select sum
      (
        COALESCE(PKOBJL.Cant,0) * coalesce(OBJ.VOLUM, 0)
      )
      FROM TMP_PACHETEOBJL PKOBJL
           INNER JOIN REZERVATS R ON R.CODREZERVATS = PKOBJL.CODREZERVATS
           INNER JOIN NIRSTOC NS ON R.CodNIRStoc = NS.CodNIRStoc
           INNER JOIN NARTOBJ OBJ ON NS.CodObiect = OBJ.CodObiect
      WHERE PKOBJL.CODGEST = V_REC.CODGEST
    ),
    valoare = (
    select sum
      (
        COALESCE(PKOBJL.Cant,0) * coalesce(PKOBJL.PRET, 0)
      )
      FROM TMP_PACHETEOBJL PKOBJL
      WHERE PKOBJL.CODGEST = V_REC.CODGEST
    )
    where CODGEST = V_REC.CODGEST;
  end loop;
  PERFORM PKG_CFGTABLES_EXT_GOTORECORD(77);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_perisabil_sp_deleterecord</obj_name>
  <obj_hashval>f62154c5aeba141f5b2ebbc1c3a71c3f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_perisabil_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM PERISABIL1 WHERE CODPERISABIL = RECID;
  DELETE FROM PERISABIL2 WHERE CODPERISABIL = RECID;
  DELETE FROM PERISABIL  WHERE CODPERISABIL = RECID;
  PERFORM NotifyModif( 2, RecId, 'PERISABIL');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_perisabil_sp_gotorecord</obj_name>
  <obj_hashval>05d16458d6878c424e76fda87cd5989a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_perisabil_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_PERISABIL(CODPERISABIL, DENUMIRE, OBS)
  SELECT CODPERISABIL, DENUMIRE, OBS FROM PERISABIL WHERE CODPERISABIL = RECID;

  INSERT INTO TMP_PERISABIL1(CODPERISABIL1, CODPERISABIL, LUNA_INI, LUNA_FIN, NrZile, NrZileDir, OBS1)
  SELECT CODPERISABIL1, CODPERISABIL, LUNA_INI, LUNA_FIN, NrZile, NrZileDir, OBS1 FROM PERISABIL1 WHERE CODPERISABIL = RECID;

  INSERT INTO TMP_PERISABIL2(CODPERISABIL2, CODPERISABIL, LUNA_INI, ZI_INI, LUNA_FIN, ZI_FIN, StocMediu, TIPSEZON, OBS1)
  SELECT CODPERISABIL2, CODPERISABIL, LUNA_INI, ZI_INI, LUNA_FIN, ZI_FIN, StocMediu, TIPSEZON, OBS1 FROM PERISABIL2 WHERE CODPERISABIL = RECID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_codcontrep</obj_name>
  <obj_hashval>757a297f959801744b4bddb088291ab5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_codcontrep(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANCONTURI.CODCONTREP', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_echiv_iopart</obj_name>
  <obj_hashval>5d404cca5dd457dd4a78c40cb587c155</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_echiv_iopart()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  NEEDECHIV numeric := 0;
BEGIN
  --Adina 11.03.2021 - add prc_al_refresh
  FOR V_REC IN (SELECT *
                FROM IOPART1 I1
                WHERE
                  I1.ANSTART * 12 + I1.LUNASTART = (SELECT MAX( I2.ANSTART * 12 + I2.LUNASTART)
                                                    FROM IOPART1 I2
                                                    WHERE
                                                      CODIOPART = I1.CODIOPART AND
                                                      I2.ANSTART * 12 + I2.LUNASTART &lt;= GETANLUCRU() * 12 + GETLUNALUCRU()
                                                   )
               )
  LOOP
    NeedEchiv := (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTFURNIZOR))    +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTCLIENT))      +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTFURNAVANS))   +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTCLIENTAVANS)) +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTFURNAVIZ))    +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTCLIENTAVIZ))  +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTFURNMF))      +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTCREDITD))     +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTDEBITD))      +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTLITIGII))     +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTFURNAVS))     +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTFURNAVIC))    +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTFURNAVIN))    +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTTERTI))       +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTFURNLEAS))    +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTNCRF))        +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTNCRC))        +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTCHELTAVANS))  +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTVENITAVANS))  +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTGARANTIEEF))  +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTGARANTIETF))  +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTGARANTIEEC))  +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTGARANTIETC))  +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF1))    +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF2))    +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF3))    +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF4))    +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF5))    +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMC1))    +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMC2))    +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMC3))    +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMC4))    +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMC5))    +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF6))    +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF7))    +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF8))    +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF9))    +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF10))   +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF11))   +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF12))   +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF13))   +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF14))   +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF15))   +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF16))   +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF17))   +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF18))   +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF19))   +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF20))   +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF21))   +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF22))   +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF23))   +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF24))   +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF25))   +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF26))   +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF27))   +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF28))   +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF29))   +
                 (SELECT PKG_PLANCONTURI_ContEchivalat.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalat(NULL, V_REC.CONTSUPLIMF30));
    IF  NeedEchiv &gt; 0 THEN
      IF  V_REC.ANSTART * 12 + V_REC.LUNASTART &lt; GETANLUCRU() * 12 + GETLUNALUCRU() THEN
        INSERT INTO IOPART1(CODIOPART1, CODIOPART, CONTFURNIZOR, CONTCLIENT, CONTFURNAVANS, CONTCLIENTAVANS, CONTFURNAVIZ, CONTCLIENTAVIZ, CONTFURNMF, CONTCREDITD, CONTDEBITD, CONTLITIGII, CONTFURNAVS, CONTFURNAVIC, CONTFURNAVIN, CONTTERTI, CONTFURNLEAS, CONTNCRF, CONTNCRC, CONTCHELTAVANS, CONTVENITAVANS, CONTGARANTIEEF, CONTGARANTIETF, CONTGARANTIEEC, CONTGARANTIETC, CONTSUPLIMF1, CONTSUPLIMF2, CONTSUPLIMF3, CONTSUPLIMF4, CONTSUPLIMF5, CONTSUPLIMC1, CONTSUPLIMC2, CONTSUPLIMC3, CONTSUPLIMC4, CONTSUPLIMC5, CONTSUPLIMF6, CONTSUPLIMF7, CONTSUPLIMF8, CONTSUPLIMF9, CONTSUPLIMF10, CONTSUPLIMF11, CONTSUPLIMF12, CONTSUPLIMF13, CONTSUPLIMF14, CONTSUPLIMF15, CONTSUPLIMF16, CONTSUPLIMF17, CONTSUPLIMF18, CONTSUPLIMF19, CONTSUPLIMF20, CONTSUPLIMF21, CONTSUPLIMF22, CONTSUPLIMF23, CONTSUPLIMF24, CONTSUPLIMF25, CONTSUPLIMF26, CONTSUPLIMF27, CONTSUPLIMF28, CONTSUPLIMF29, CONTSUPLIMF30, TVANEEXF, TVANEEXC, TVANEEXP, TVANEEXI, TIP, ANSTART, LUNASTART)
        VALUES(NEXTVAL('SEQ_IOPART1_CODIOPART1'), V_REC.CODIOPART,
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTFURNIZOR)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTCLIENT)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTFURNAVANS)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTCLIENTAVANS)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTFURNAVIZ)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTCLIENTAVIZ)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTFURNMF)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTCREDITD)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTDEBITD)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTLITIGII)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTFURNAVS)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTFURNAVIC)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTFURNAVIN)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTTERTI)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTFURNLEAS)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTNCRF)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTNCRC)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTCHELTAVANS)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTVENITAVANS)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTGARANTIEEF)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTGARANTIETF)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTGARANTIEEC)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTGARANTIETC)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF1)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF2)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF3)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF4)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF5)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMC1)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMC2)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMC3)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMC4)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMC5)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF6)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF7)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF8)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF9)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF10)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF11)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF12)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF13)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF14)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF15)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF16)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF17)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF18)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF19)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF20)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF21)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF22)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF23)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF24)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF25)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF26)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF27)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF28)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF29)),
               (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF30)),
               V_REC.TVANEEXF, V_REC.TVANEEXC, V_REC.TVANEEXP, V_REC.TVANEEXI, V_REC.TIP,
               GETANLUCRU(),
               GETLUNALUCRU()
              );
        CALL PRC_AL_REFRESH('iopart1', V_REC.CODIOPART);
      ELSE
        UPDATE IOPART1
        SET
        CONTFURNIZOR    = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTFURNIZOR)),
        CONTCLIENT      = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTCLIENT)),
        CONTFURNAVANS   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTFURNAVANS)),
        CONTCLIENTAVANS = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTCLIENTAVANS)),
        CONTFURNAVIZ    = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTFURNAVIZ)),
        CONTCLIENTAVIZ  = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTCLIENTAVIZ)),
        CONTFURNMF      = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTFURNMF)),
        CONTCREDITD     = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTCREDITD)),
        CONTDEBITD      = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTDEBITD)),
        CONTLITIGII     = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTLITIGII)),
        CONTFURNAVS     = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTFURNAVS)),
        CONTFURNAVIC    = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTFURNAVIC)),
        CONTFURNAVIN    = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTFURNAVIN)),
        CONTTERTI       = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTTERTI)),
        CONTFURNLEAS    = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTFURNLEAS)),
        CONTNCRF        = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTNCRF)),
        CONTNCRC        = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTNCRC)),
        CONTCHELTAVANS  = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTCHELTAVANS)),
        CONTVENITAVANS  = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTVENITAVANS)),
        CONTGARANTIEEF  = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTGARANTIEEF)),
        CONTGARANTIETF  = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTGARANTIETF)),
        CONTGARANTIEEC  = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTGARANTIEEC)),
        CONTGARANTIETC  = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTGARANTIETC)),
        CONTSUPLIMF1    = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF1)),
        CONTSUPLIMF2    = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF2)),
        CONTSUPLIMF3    = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF3)),
        CONTSUPLIMF4    = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF4)),
        CONTSUPLIMF5    = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF5)),
        CONTSUPLIMC1    = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMC1)),
        CONTSUPLIMC2    = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMC2)),
        CONTSUPLIMC3    = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMC3)),
        CONTSUPLIMC4    = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMC4)),
        CONTSUPLIMC5    = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMC5)),
        CONTSUPLIMF6    = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF6)),
        CONTSUPLIMF7    = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF7)),
        CONTSUPLIMF8    = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF8)),
        CONTSUPLIMF9    = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF9)),
        CONTSUPLIMF10   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF10)),
        CONTSUPLIMF11   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF11)),
        CONTSUPLIMF12   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF12)),
        CONTSUPLIMF13   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF13)),
        CONTSUPLIMF14   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF14)),
        CONTSUPLIMF15   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF15)),
        CONTSUPLIMF16   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF16)),
        CONTSUPLIMF17   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF17)),
        CONTSUPLIMF18   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF18)),
        CONTSUPLIMF19   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF19)),
        CONTSUPLIMF20   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF20)),
        CONTSUPLIMF21   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF21)),
        CONTSUPLIMF22   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF22)),
        CONTSUPLIMF23   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF23)),
        CONTSUPLIMF24   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF24)),
        CONTSUPLIMF25   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF25)),
        CONTSUPLIMF26   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF26)),
        CONTSUPLIMF27   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF27)),
        CONTSUPLIMF28   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF28)),
        CONTSUPLIMF29   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF29)),
        CONTSUPLIMF30   = (SELECT PKG_PLANCONTURI_ContEchivalent.WME_RESULT FROM PKG_PLANCONTURI_ContEchivalent(NULL, V_REC.CONTSUPLIMF30))
        WHERE
         CODIOPART1 = V_REC.CODIOPART1;
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_post_ncont_echiv</obj_name>
  <obj_hashval>2cb1faa7876481af4f4d5e0c84433fcc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_post_ncont_echiv()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  V_REC_S RECORD;
  aCOD         numeric;
  aCODCONTSOLD numeric;
  NR           numeric;
begin
  FOR V_REC IN (SELECT * FROM NCONTECHIV WHERE AN = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') AND  LUNA = 1) LOOP
    DELETE FROM NCONTECHIVSUB WHERE CODCONTECHIV = V_REC.CODCONTECHIV;
    DELETE FROM NCONTECHIV    WHERE CODCONTECHIV = V_REC.CODCONTECHIV;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_NCONTECHIV) LOOP
    aCOD := NEXTVAL('SEQ_NCONTECHIV_CODCONTECHIV');
    UPDATE TMP_NCONTECHIV    SET CODCONTECHIV = aCOD WHERE CODCONTECHIV = V_REC.CODCONTECHIV;
    UPDATE TMP_NCONTECHIVSUB SET CODCONTECHIV = aCOD WHERE CODCONTECHIV = V_REC.CODCONTECHIV;
  END LOOP;

  INSERT INTO NCONTECHIV(CODCONTECHIV, CONTVECHI, CONTNOU, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP, AN, LUNA)
  SELECT CODCONTECHIV, CONTVECHI, CONTNOU, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP, TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999'), 1
  FROM TMP_NCONTECHIV;

  INSERT INTO NCONTECHIVSUB(CODCONTECHIVSUB, CODCONTECHIV, CODSUBUNIT, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP)
  SELECT NEXTVAL('SEQ_NCONTECHIVSUB_COD'), CODCONTECHIV, CODSUBUNIT, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP
  FROM TMP_NCONTECHIVSUB;

  FOR V_REC IN (SELECT  DISTINCT CONTNOU
                FROM (SELECT CONTNOU FROM NCONTECHIV WHERE AN = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') AND  LUNA = 1
                       union
                      SELECT CODUNIC AS CONTNOU FROM TMP_MANEVRA
                     ) A_PG
               )
  LOOP
    BEGIN
      SELECT CODCONTSOLD FROM NCONTSOLD WHERE CODCONT = V_REC.CONTNOU AND  AN = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') AND  LUNA = 1;
    EXCEPTION WHEN OTHERS THEN
      aCODCONTSOLD := 0;
    END;

    IF  aCODCONTSOLD = 0 THEN
      aCODCONTSOLD := NEXTVAL('SEQ_NCONTSOLD_CODCONTSOLD');
      INSERT INTO NCONTSOLD(CODCONTSOLD, CODCONT, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP, AN, LUNA)
      VALUES(aCODCONTSOLD, V_REC.CONTNOU, 0, 0, 0, 0, 0, 0, 0, 0, TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999'), 1);
    ELSE
      UPDATE NCONTSOLD
      SET
      SOLDID      = 0,
      SOLDIC      = 0,
      SOLDVID     = 0,
      SOLDVIC     = 0,
      SOLDI_IFRS  = 0,
      SOLDVI_IFRS = 0,
      SOLDI_GRUP  = 0,
      SOLDVI_GRUP = 0
      WHERE
       CODCONTSOLD = aCODCONTSOLD;
    END IF;

    FOR V_REC_S IN (SELECT CODSUBUNIT FROM NSUBUNIT WHERE CODSUBUNIT &gt; 1) LOOP
      BEGIN
        SELECT COUNT( *) FROM NCONTSOLDSUB WHERE CODCONTSOLD = aCODCONTSOLD AND  SUBUNITATEA = V_REC_S.CODSUBUNIT;
      EXCEPTION WHEN OTHERS THEN
        NR := 0;
      END;

      IF  NR = 0 THEN
        INSERT INTO NCONTSOLDSUB(CODCONTSOLDSUB, SUBUNITATEA, CODCONTSOLD, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP)
        VALUES(NEXTVAL('SEQ_NCONTSOLDSUB_CODSOLDSUB'), V_REC_S.CODSUBUNIT, aCODCONTSOLD, 0, 0, 0, 0, 0, 0, 0, 0);
      ELSE
        UPDATE NCONTSOLDSUB
        SET
        SOLDID      = 0,
        SOLDIC      = 0,
        SOLDVID     = 0,
        SOLDVIC     = 0,
        SOLDI_IFRS  = 0,
        SOLDVI_IFRS = 0,
        SOLDI_GRUP  = 0,
        SOLDVI_GRUP = 0
        WHERE
         CODCONTSOLD = aCODCONTSOLD AND  SUBUNITATEA = V_REC_S.CODSUBUNIT;
      END IF;
    END LOOP;
  END LOOP;

  FOR V_REC IN (SELECT * FROM NCONTECHIV WHERE AN = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') AND  LUNA = 1) LOOP
    UPDATE NCONTSOLD
    SET
    SOLDID      = COALESCE( SOLDID     , 0) + COALESCE( V_REC.SOLDID     , 0),
    SOLDIC      = COALESCE( SOLDIC     , 0) + COALESCE( V_REC.SOLDIC     , 0),
    SOLDVID     = COALESCE( SOLDVID    , 0) + COALESCE( V_REC.SOLDVID    , 0),
    SOLDVIC     = COALESCE( SOLDVIC    , 0) + COALESCE( V_REC.SOLDVIC    , 0),
    SOLDI_IFRS  = COALESCE( SOLDI_IFRS , 0) + COALESCE( V_REC.SOLDI_IFRS , 0),
    SOLDVI_IFRS = COALESCE( SOLDVI_IFRS, 0) + COALESCE( V_REC.SOLDVI_IFRS, 0),
    SOLDI_GRUP  = COALESCE( SOLDI_GRUP , 0) + COALESCE( V_REC.SOLDI_GRUP , 0),
    SOLDVI_GRUP = COALESCE( SOLDVI_GRUP, 0) + COALESCE( V_REC.SOLDVI_GRUP, 0)
    WHERE
     CODCONT = V_REC.CONTNOU AND  AN = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') AND  LUNA = 1;
  END LOOP;

  FOR V_REC IN (SELECT S.CODCONTSOLD, ES.*
                FROM NCONTECHIVSUB ES, NCONTECHIV E, NCONTSOLD S
                WHERE  ES.CODCONTECHIV = E.CODCONTECHIV AND  E.AN = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999')
                  AND  E.LUNA = 1 AND  S.CODCONT = E.CONTNOU AND  S.AN = E.AN AND  S.LUNA = 1
               )
  LOOP
    UPDATE NCONTSOLDSUB
    SET
    SOLDID      = COALESCE( SOLDID     , 0) + COALESCE( V_REC.SOLDID     , 0),
    SOLDIC      = COALESCE( SOLDIC     , 0) + COALESCE( V_REC.SOLDIC     , 0),
    SOLDVID     = COALESCE( SOLDVID    , 0) + COALESCE( V_REC.SOLDVID    , 0),
    SOLDVIC     = COALESCE( SOLDVIC    , 0) + COALESCE( V_REC.SOLDVIC    , 0),
    SOLDI_IFRS  = COALESCE( SOLDI_IFRS , 0) + COALESCE( V_REC.SOLDI_IFRS , 0),
    SOLDVI_IFRS = COALESCE( SOLDVI_IFRS, 0) + COALESCE( V_REC.SOLDVI_IFRS, 0),
    SOLDI_GRUP  = COALESCE( SOLDI_GRUP , 0) + COALESCE( V_REC.SOLDI_GRUP , 0),
    SOLDVI_GRUP = COALESCE( SOLDVI_GRUP, 0) + COALESCE( V_REC.SOLDVI_GRUP, 0)
    WHERE
     CODCONTSOLD = V_REC.CODCONTSOLD AND  SUBUNITATEA = V_REC.CODSUBUNIT;
  END LOOP;

  PERFORM PKG_PLANCONTURI_SET_ECHIVALARI_AUTOMATE();
  PERFORM PKG_GLOBALS_ResetAllRecordsLunaFlags();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_sp_gotorecord</obj_name>
  <obj_hashval>ce46293a51a8aa18f9fd5fb6defae09a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC      RECORD;
  V_REC_SOLD RECORD;
  V_REC_SUB  RECORD;
  V_REC_RUL  RECORD;
  aANSFARSIT   numeric;
  aLUNASFARSIT numeric;
  aINDEX       numeric := 0;
  NR           numeric := 0;
BEGIN
  --Florin 20.04.2023 - sinc. Oracle
  --Florin 14.02.2022 - sinc. Oracle (13.02.2022)
  --Laura 17.11.2021 - sinc Oracle (17.11.2021)
  --Laura 10.11.2021 - sinc Oracle (10.11.2021)
  --Laura 22.09.2021 - sinc Oracle (21.09.2021)
  --Bogdan 05.01.2021
    INSERT INTO  TMP_NCONT ( CodCont, Simbol, Clasa, Den_cont,Name, TipCont, VizibilBalanta, BalantaSintetica, Nivel, CodParinte, SimbolSitFin, ANINACTIV, LUNAINACTIV, CODSAFT, TAXCODE, IMPOZIT, taxtype )
        ( SELECT CodCont, Simbol, Clasa, Den_cont, Name, TipCont, VizibilBalanta, BalantaSintetica, Nivel, CodParinte, SimbolSitFin, ANINACTIV, LUNAINACTIV, CODSAFT, TAXCODE, IMPOZIT, taxtype
      FROM NCONT WHERE CodCont = RecId);

  INSERT INTO TMP_NCONT1 (CodCont1, CodCont, NrAnalitice, ContTransfD, ContTransfC, ContTransfCDim, CONTSECUNDARG, CONTSECUNDARGO, CODCENTRU, CODCENTRUS, CODCENTRUSG, CODCENTRUSGO,
                          TipInchidere, ContInkidSold, Participatiune, Sincronizare, ContSecundar, ContTertiar, anstart, lunastart, codanalizanod)
  (SELECT CodCont1, CodCont, NrAnalitice, ContTransfD, ContTransfC, ContTransfCDim, CONTSECUNDARG, CONTSECUNDARGO, CODCENTRU, CODCENTRUS, CODCENTRUSG, CODCENTRUSGO, TipInchidere,
          ContInkidSold, Participatiune, Sincronizare, ContSecundar, ContTertiar, anstart, lunastart, codanalizanod
   FROM NCONT1 WHERE CodCont = RecId);

  INSERT INTO TMP_NCONT1SUB (COD, CODCONT1, SUBUNITATEA, TIPINCHIDERE, DENSUBUNIT)
  SELECT NC1S.COD, NC1S.CODCONT1, NC1S.SUBUNITATEA, NC1S.TIPINCHIDERE, NS.DEN_SUBUNIT
  FROM NCONT1SUB NC1S, NSUBUNIT NS
  WHERE EXISTS (SELECT CODCONT1 FROM TMP_NCONT1 WHERE CODCONT1 = NC1S.CODCONT1) AND NS.CODSUBUNIT = NC1S.SUBUNITATEA;

  aANSFARSIT   := 0;
  aLUNASFARSIT := 0;
  FOR V_REC IN (SELECT CODCONT1, ANSTART, LUNASTART FROM TMP_NCONT1 ORDER BY ANSTART * 12 + LUNASTART desc) LOOP
    IF (aANSFARSIT &lt;&gt; 0) AND (aLUNASFARSIT &lt;&gt; 0) THEN
      UPDATE TMP_NCONT1
      SET ANSFARSIT = aANSFARSIT, LUNASFARSIT = aLUNASFARSIT
      WHERE
        CODCONT1 = V_REC.CODCONT1;
    END IF;
    select newan, newluna from  PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA (V_REC.ANSTART, V_REC.LUNASTART, aANSFARSIT, aLUNASFARSIT) into aANSFARSIT, aLUNASFARSIT ;
  END LOOP;

  INSERT INTO TMP_NCONTSOLD (CodContSold, SoldID, SoldIC, SoldVID, SoldVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP, CodCont, An, Luna)
  (SELECT CodContSold, SoldID, SoldIC, SoldVID, SoldVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP, CodCont, An, Luna
   FROM NCONTSOLD
   WHERE CodCont = RecId AND AN = (SELECT PKG_PLANCONTURI_GET_AN_SOLDINI.WME_RESULT FROM PKG_PLANCONTURI_GET_AN_SOLDINI (NULL,NULL)) AND LUNA = 1);

  INSERT INTO TMP_NCONTSOLDSUB (CODCONTSOLDSUB, CODCONTSOLD, SUBUNITATEA, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP, DENSUBUNIT)
  SELECT CODCONTSOLDSUB, CODCONTSOLD, SUBUNITATEA, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP, SUB.DEN_SUBUNIT
  FROM NCONTSOLDSUB S, NSUBUNIT SUB
  WHERE SUB.CODSUBUNIT = S.SUBUNITATEA AND EXISTS (SELECT CODCONTSOLD FROM TMP_NCONTSOLD WHERE CODCONTSOLD = S.CODCONTSOLD);

  INSERT INTO TMP_NCONTRUL (CodContRul, RulajPD, RulajPC, CodCont, RulajCD, RulajCC, RulajVPD, RulajVPC, RulajVCD, RulajVCC, RULAJP_IFRS, RULAJVP_IFRS,
                            RULAJC_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJVP_GRUP, RULAJC_GRUP, RULAJVC_GRUP, An, Luna)
  (SELECT CodContRul, RulajPD, RulajPC, CodCont, RulajCD, RulajCC, RulajVPD, RulajVPC, RulajVCD, RulajVCC, RULAJP_IFRS, RULAJVP_IFRS, RULAJC_IFRS,
          RULAJVC_IFRS, RULAJP_GRUP, RULAJVP_GRUP, RULAJC_GRUP, RULAJVC_GRUP, An, Luna
   FROM NCONTRUL
   WHERE
        CodCont  = RecId
        AND AN   = current_setting ('PKG_GLOBALS.ANLUCRU'  , true) ::numeric
        AND LUNA = current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric);

  INSERT INTO TMP_NCONTRULSUB (CODCONTRULSUB, CODCONTRUL, SUBUNITATEA, RULAJPD,
      RULAJPC, RULAJVPD, RULAJVPC, RULAJCD,
      RULAJCC, RULAJVCD, RULAJVCC, RULAJP_IFRS,
      RULAJVP_IFRS, RULAJC_IFRS, RULAJVC_IFRS, RULAJP_GRUP,
      RULAJVP_GRUP, RULAJC_GRUP, RULAJVC_GRUP, DENSUBUNIT)
  SELECT CODCONTRULSUB, CODCONTRUL, SUBUNITATEA, RULAJPD,
    RULAJPC, RULAJVPD, RULAJVPC, RULAJCD,
    RULAJCC, RULAJVCD, RULAJVCC, RULAJP_IFRS,
    RULAJVP_IFRS, RULAJC_IFRS, RULAJVC_IFRS, RULAJP_GRUP,
    RULAJVP_GRUP, RULAJC_GRUP, RULAJVC_GRUP, S.DEN_SUBUNIT
  FROM NCONTRULSUB R, NSUBUNIT S
  WHERE
    EXISTS (SELECT CODCONTRUL FROM TMP_NCONTRUL WHERE CODCONTRUL = R.CODCONTRUL)
    AND S.CODSUBUNIT = R.SUBUNITATEA;

  aINDEX := 0;
  FOR V_REC_SOLD IN (SELECT * FROM TMP_NCONTSOLD) LOOP
    FOR V_REC_SUB IN (SELECT * FROM NSUBUNIT WHERE CODSUBUNIT &gt; 1) LOOP
      SELECT COUNT(*) INTO NR FROM TMP_NCONTSOLDSUB WHERE SUBUNITATEA = V_REC_SUB.CODSUBUNIT AND CODCONTSOLD = V_REC_SOLD.CODCONTSOLD;

      IF NR = 0 THEN
        aINDEX := aINDEX - 1;
        INSERT INTO TMP_NCONTSOLDSUB (CODCONTSOLDSUB, CODCONTSOLD, SUBUNITATEA, DENSUBUNIT)
        VALUES (aINDEX, V_REC_SOLD.CODCONTSOLD, V_REC_SUB.CODSUBUNIT, V_REC_SUB.DEN_SUBUNIT);
      END IF;
    END LOOP;
  END LOOP;

  aINDEX := 0;
  FOR V_REC_RUL IN (SELECT * FROM TMP_NCONTRUL) LOOP
    FOR V_REC_SUB IN (SELECT * FROM NSUBUNIT WHERE CODSUBUNIT &gt; 1) LOOP
      SELECT COUNT(*) INTO NR FROM TMP_NCONTRULSUB WHERE SUBUNITATEA = V_REC_SUB.CODSUBUNIT AND CODCONTRUL = V_REC_RUL.CODCONTRUL;

      IF NR = 0 THEN
        aINDEX := aINDEX - 1;
        INSERT INTO TMP_NCONTRULSUB (CODCONTRULSUB, CODCONTRUL, SUBUNITATEA, DENSUBUNIT)
        VALUES (aINDEX, V_REC_RUL.CODCONTRUL, V_REC_SUB.CODSUBUNIT, V_REC_SUB.DEN_SUBUNIT);
      END IF;
    END LOOP;
  END LOOP;

  UPDATE TMP_NCONT
  SET INACTIV = CASE WHEN COALESCE (ANINACTIV, 0) + COALESCE (LUNAINACTIV, 0) &lt;&gt; 0 THEN 1 ELSE 0 END;
  PERFORM PKG_CFGTABLES_EXT_GOTORECORD(521);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plancurs_sp_insertrecord</obj_name>
  <obj_hashval>38c40907f5f4635fc01deaee117fa9c7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plancurs_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_PlanCurs(CodPlanCurs) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_maketemporar</obj_name>
  <obj_hashval>31be6e8f929304f242aac3b4cc1aae00</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_maketemporar(asetg numeric, aang numeric, aset numeric, aan numeric, aallcls numeric, aallclss numeric, aallprod numeric, aprel boolean, removedirtycmdf boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDataCreare  timestamp;
  aSubunitatea numeric;
  dataG date;
BEGIN
  --Florin 10.11.2023 - sinc. Oracle (09.11.2023)
  --Florin 31.05.2022 - sinc. Oracle (27.05.2022)
  --Florin 01.02.2022 - sinc. Oracle (7-21.01.2022)
  --Adina 15.06.2021 - sinc.Oracle din 14.06.2021
    dataG := (SELECT wme_result FROM iso_week_to_date(NULL, aAnG, aSetG));
  aSubunitatea := current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric;
  BEGIN
    SELECT min (datacreare)
    INTO adatacreare
    FROM stareestimari
    WHERE
      an = aan
      and saptamana = aset
      and ang = aang
      and saptamanag = asetg;
  EXCEPTION
  WHEN others THEN
    aDataCreare := CURRENT_TIMESTAMP;
  END;

  IF aPrel THEN
    perform set_config ('PKG_PLANIFCMD.vAllCls',aAllCls::varchar,false);
    perform set_config ('PKG_PLANIFCMD.vAllClsS',aAllClsS::varchar,false);
    perform set_config ('PKG_PLANIFCMD.vAllProd',aAllProd::varchar,false);

    DELETE FROM tmp_nclasea;
    DELETE FROM tmp_nclaseas;
    DELETE FROM tmp_npart;

    IF NOT aAllCls = 1 THEN
      INSERT INTO tmp_nclasea (codclasea)
      SELECT valoare FROM tmp_manevra_liste WHERE filtru = 'CODCLASEA';
    END IF;

    IF NOT aAllClsS = 1 THEN
      INSERT INTO tmp_nclaseas (codclaseas)
      SELECT valoare FROM tmp_manevra_liste WHERE filtru = 'CODCLASEAS';
    END IF;

    IF NOT aAllProd = 1 THEN
      INSERT INTO tmp_npart (codpart)
      SELECT valoare FROM tmp_manevra_liste WHERE filtru = 'CODPART';
    END IF;
  END IF;

  DELETE FROM tmp_stareestimari1;
  delete FROM tmp_cmd;

   if aAllCls + aAllClsS + aAllProd &gt; 0 then
    insert into tmp_cmd_tmp(codobiect,tip)
    select o.codobiect, 'CODOBIECT'
    FROM nartobj o INNER JOIN nart a ON a.codarticol = o.codarticol
    WHERE (aAllCls  = 1 OR EXISTS (SELECT cls.codclasea   FROM tmp_nclasea cls   WHERE cls.codclasea = a.clasa))
          and (aAllClsS = 1 or exists (select clsS.codclaseas from tmp_nclaseas clsS where clsS.codclaseas = a.clasastatist))
          and (aAllProd = 1 or exists (select p.codpart from tmp_npart p where p.codpart = o.codproducator));
  end if;

  if aAllCls + aAllClsS + aAllProd &gt; 0 then
    insert into tmp_cmd_tmp(codobiect,resta,tip)
    SELECT L.CODLINIECOMANDA, SUM(L.CANT) CANT, 'STORNO'
    FROM CMDLIVRLINK L
    INNER JOIN COMANDA1    S1  ON S1.CODCOMANDA1 = L.CODCOMANDA1
    INNER JOIN COMANDA     S   ON S.CODCOMANDA   = S1.CODCOMANDA
    INNER JOIN TMP_CMD_TMP TMP ON TMP.CODOBIECT  = S1.CODOBIECT  AND TMP.TIP = 'CODOBIECT'
    WHERE S.OPERAT = 1 AND Coalesce(S.ANULAT,0) = 0 AND S.TIPDOC = 66
    GROUP BY L.CODLINIECOMANDA;
  else
    insert into tmp_cmd_tmp(codobiect,resta,tip)
        SELECT L.CODLINIECOMANDA, SUM(L.CANT) CANT, 'STORNO'
    FROM CMDLIVRLINK L
    INNER JOIN COMANDA1    S1  ON S1.CODCOMANDA1 = L.CODCOMANDA1
    INNER JOIN COMANDA     S   ON S.CODCOMANDA   = S1.CODCOMANDA
    WHERE S.OPERAT = 1 AND COALESCE(S.ANULAT,0) = 0 AND S.TIPDOC = 66
          AND L.CODCOMANDA1 = S1.CODCOMANDA1 AND S1.CODCOMANDA = S.CODCOMANDA
    GROUP BY CODLINIECOMANDA;
  end if;

  if aAllCls + aAllClsS + aAllProd &gt; 0 then
    insert into tmp_cmd_tmp(codobiect,resta,tip)
    select se1.codobiect, sum(COALESCE(se1.estimat,0)) cant, 'ESTINTP'
    FROM stareestimari1 se1
    INNER JOIN stareestimari se  ON se.codstare   = se1.codstare
    INNER JOIN tmp_cmd_tmp   tmp ON tmp.codobiect = se1.codobiect AND tmp.tip = 'CODOBIECT'
    where se.an = aAn and se.saptamana = aSet and se.AnG * 100 + se.saptamanag &lt; aAnG * 100 + aSetG
    AND se.subunitatea = aSubunitatea
    group by se1.codobiect;
  else
    insert into tmp_cmd_tmp(codobiect,resta,tip)
    select se1.codobiect, sum(COALESCE(se1.estimat,0)) cant, 'ESTINTP'
    FROM stareestimari1 se1 INNER JOIN stareestimari se  ON se.codstare   = se1.codstare
    WHERE se.an = aAn AND se.saptamana = aSet
    AND se.AnG * 100 + se.saptamanag &lt; aAnG * 100 + aSetG
    AND se.subunitatea = aSubunitatea
    group by se1.codobiect;
  end if;

  if aAllCls + aAllClsS + aAllProd &gt; 0 then
    insert into tmp_cmd_tmp(codobiect,resta,tip)
    select c1.codobiect, sum(c1.cantacceptat - COALESCE(Storno.RESTA,0)) cant, 'CMDFP'
    FROM STAREESTIMARI1 SE1
    INNER JOIN STAREESTIMARI SE     ON SE.CODSTARE    = SE1.CODSTARE
    INNER JOIN PLANIFLINK    L      ON l.codstare1    = se1.codstare1
    INNER JOIN COMANDA1      C1     ON c1.codcomanda1 = l.codcomanda1
    INNER JOIN COMANDA       C      ON c.codcomanda   = c1.codcomanda
    INNER JOIN TMP_CMD_TMP   TMP    ON tmp.codobiect  = c1.codobiect     AND TMP.TIP    = 'CODOBIECT'
    LEFT  JOIN TMP_CMD_TMP   STORNO ON STORNO.CODOBIECT = C1.CodComanda1 AND STORNO.TIP = 'STORNO'
    where se.an = aAn and se.saptamana = aSet and se.ang = aAnG and se.saptamanag = aSetG
    AND se.subunitatea = aSubunitatea
    AND c.tipdoc = 8 AND c.operat = 1 AND c.anulat = 0
    AND c1.termen between dataG AND add_days(dataG, 6)
    AND C.datadoc &gt;= add_days(current_days, - 365)
    group by c1.codobiect;
  else
    insert into tmp_cmd_tmp(codobiect,resta,tip)
    select c1.codobiect, sum(c1.cantacceptat - COALESCE(Storno.RESTA,0)) cant, 'CMDFP'
    FROM STAREESTIMARI1 SE1
    INNER JOIN STAREESTIMARI SE     ON SE.CODSTARE    = SE1.CODSTARE
    INNER JOIN PLANIFLINK    L      ON l.codstare1    = se1.codstare1
    INNER JOIN COMANDA1      C1     ON c1.codcomanda1 = l.codcomanda1
    INNER JOIN COMANDA       C      ON c.codcomanda   = c1.codcomanda
    LEFT  JOIN tmp_cmd_tmp STORNO ON STORNO.CODOBIECT = C1.CodComanda1 AND STORNO.TIP = 'STORNO'
    where se.an = aAn and se.saptamana = aSet and se.ang = aAnG and se.saptamanag = aSetG
    AND se.subunitatea = aSubunitatea
    and c.tipdoc = 8 and c.operat = 1 and c.anulat = 0
    AND c1.termen between dataG AND add_days(dataG, 6)
    AND C.datadoc &gt;= add_days(current_date, - 365)
    group by c1.codobiect;
  end if;

  if aAllCls + aAllClsS + aAllProd &gt; 0 then
    insert into tmp_cmd_tmp(codobiect,resta,tip)
    select se1.codobiect, sum(se2.restacceptat) cant, 'CMDFFIX'
    FROM STAREESTIMARI SE
    INNER JOIN STAREESTIMARI1 SE1 ON SE1.CODSTARE  = SE.CODSTARE
    INNER JOIN STAREESTIMARI2 SE2 ON SE2.CODSTARE  = SE.CODSTARE   AND SE2.CODSTARE1 = SE1.CODSTARE1
    INNER JOIN TMP_CMD_TMP    TMP ON TMP.CODOBIECT = SE1.CODOBIECT AND tmp.tip = 'CODOBIECT'
    where se.an = aAn and se.saptamana = aSet and se.ang = aAnG and se.saptamanag = aSetG
    AND se.subunitatea = aSubunitatea
    group by se1.codobiect;
  else
    insert into tmp_cmd_tmp(codobiect,resta,tip)
    select se1.codobiect, sum(se2.restacceptat) cant, 'CMDFFIX'
    from STAREESTIMARI1 SE1, STAREESTIMARI SE, stareestimari2 se2
    where se.an = aAn and se.saptamana = aSet and se.ang = aAnG and se.saptamanag = aSetG
          and se.subunitatea = aSubunitatea and SE1.CODSTARE = SE.CODSTARE
          and se2.codstare = se.codstare and se2.codstare1 = se1.codstare1
    group by se1.codobiect;
  end if;

  if aAllCls + aAllClsS + aAllProd &gt; 0 then
    insert into tmp_cmd_tmp(codobiect,resta,tip)
    SELECT SE1.CODSTARE1, SUM(PC1.REST) CANT, 'RESTC'
    FROM STAREESTIMARI1 SE1, STAREESTIMARI SE, PRECOMANDA1 PC1, PRECOMANDA PC, tmp_cmd_tmp tmp
    WHERE se.an = PC.ANC and se.saptamana = PC.SAPTAMANAC
          AND SE.ANG = PC.ANG AND SE.SAPTAMANAG = PC.SAPTAMANAG
          AND PC.USERID = PKG_GLOBALS.GETUSERID and SE1.CODSTARE = SE.CODSTARE
          and PC1.CODSTARE1 = SE1.CODSTARE1 and PC.CODPRECOMANDA = PC1.CODPRECOMANDA
          and tmp.codobiect = se1.codobiect and tmp.tip = 'CODOBIECT'
          AND PC1.REST &gt; 0
    GROUP BY SE1.CODSTARE1;
  else
    insert into tmp_cmd_tmp(codobiect,resta,tip)
    SELECT SE1.CODSTARE1, SUM(PC1.REST) CANT, 'RESTC'
    FROM STAREESTIMARI1 SE1, STAREESTIMARI SE, PRECOMANDA1 PC1, PRECOMANDA PC
    WHERE se.an = PC.ANC and se.saptamana = PC.SAPTAMANAC
          AND SE.ANG = PC.ANG AND SE.SAPTAMANAG = PC.SAPTAMANAG
          AND PC.USERID = PKG_GLOBALS.GETUSERID and SE1.CODSTARE = SE.CODSTARE
          and PC1.CODSTARE1 = SE1.CODSTARE1 and PC.CODPRECOMANDA = PC1.CODPRECOMANDA
          AND PC1.REST &gt; 0
    GROUP BY SE1.CODSTARE1;
  end if;

  if aAllCls + aAllClsS + aAllProd &gt; 0 then
    insert into tmp_cmd_tmp(codobiect,resta,tip)
    SELECT SE1.CODSTARE1, SUM(PC1.REST) CANT, 'RESTCA'
    FROM STAREESTIMARI1 SE1, STAREESTIMARI SE, PRECOMANDA1 PC1, PRECOMANDA PC, tmp_cmd_tmp tmp
    WHERE se.an = PC.ANC and se.saptamana = PC.SAPTAMANAC
          AND SE.ANG = PC.ANG AND SE.SAPTAMANAG = PC.SAPTAMANAG
          AND PC.USERID &lt;&gt; PKG_GLOBALS.GETUSERID and SE1.CODSTARE = SE.CODSTARE
          and PC1.CODSTARE1 = SE1.CODSTARE1 and PC.CODPRECOMANDA = PC1.CODPRECOMANDA
          and tmp.codobiect = se1.codobiect and tmp.tip = 'CODOBIECT'
          AND PC1.REST &gt; 0
    GROUP BY SE1.CODSTARE1;
  else
    insert into tmp_cmd_tmp(codobiect,resta,tip)
    SELECT SE1.CODSTARE1, SUM(PC1.REST) CANT, 'RESTCA'
    FROM STAREESTIMARI1 SE1, STAREESTIMARI SE, PRECOMANDA1 PC1, PRECOMANDA PC
    WHERE se.an = PC.ANC and se.saptamana = PC.SAPTAMANAC
          AND SE.ANG = PC.ANG AND SE.SAPTAMANAG = PC.SAPTAMANAG
          AND PC.USERID &lt;&gt; PKG_GLOBALS.GETUSERID and SE1.CODSTARE = SE.CODSTARE
          and PC1.CODSTARE1 = SE1.CODSTARE1 and PC.CODPRECOMANDA = PC1.CODPRECOMANDA
          AND PC1.REST &gt; 0
    GROUP BY SE1.CODSTARE1;
  end if;

  if aAnG * 100 + aSetG = aAn * 100 + aSet then
    if aAllCls + aAllClsS + aAllProd &gt; 0 then
      insert into tmp_cmd_tmp(codobiect,resta,tip)
      select c1.codobiect, sum(c1.cantacceptat - COALESCE(Storno.RESTA,0)) cant, 'CMDFL'
      from tmp_cmd_tmp tmp, comanda c, comanda1 c1
           LEFT  JOIN tmp_cmd_tmp STORNO ON STORNO.CODOBIECT = C1.CodComanda1 AND STORNO.TIP = 'STORNO'
      where c.tipdoc = 8 and c.operat = 1 and c.anulat = 0 and c.codcomanda = c1.codcomanda
            and c.subunitatea = aSubunitatea
            and c1.termen &lt;= dataG + 6
            and c.an &gt;= aAnG - 1
            and c.datacreare &gt; adatacreare
            and not exists (select se2.codcomanda1 from stareestimari2 se2 where se2.codcomanda1 = c1.codcomanda1)
            and not exists (select l.codcomanda1 from planiflink l where l.codcomanda1 = c1.codcomanda1)
            and tmp.codobiect = c1.codobiect and tmp.tip = 'CODOBIECT'
            AND C.datadoc &gt;= add_days(current_date, - 365)
      group by c1.codobiect;
    else
      insert into tmp_cmd_tmp(codobiect,resta,tip)
      select c1.codobiect, sum(c1.cantacceptat - COALESCE(Storno.RESTA,0)) cant, 'CMDFL'
      from comanda c, comanda1 c1
           LEFT JOIN tmp_cmd_tmp STORNO ON STORNO.CODOBIECT = C1.CodComanda1 AND STORNO.TIP = 'STORNO'
      where c.tipdoc = 8 and c.operat = 1 and c.anulat = 0
            and c.subunitatea = aSubunitatea
            and c1.termen &lt;= dataG + 6
            and c.an &gt;= aAnG - 1 and c.codcomanda = c1.codcomanda
            and c.datacreare &gt; adatacreare
            and not exists (select se2.codcomanda1 from stareestimari2 se2 where se2.codcomanda1 = c1.codcomanda1)
            and not exists (select l.codcomanda1 from planiflink l where l.codcomanda1 = c1.codcomanda1)
            AND C.datadoc &gt;= add_days(current_date, - 365)
      group by c1.codobiect;
    end if;

  if aAllCls + aAllClsS + aAllProd &gt; 0 then
   insert into tmp_stareestimari1 (
      codstare,
      codstare1,
      codobiect,
      stocmin,
      stocini,
      StocPrec,
      Estimari,
      CmdF,
      Necesar,
      StocFinal,
      Pret,
      StocVal,
      indexlocal,
      denumire,
      CMDFP,
      RESTPRECMD,
      RESTPRECMDA,
      DIRTY,
      DIRTYCMDF,
      PART1NEC,
      UMSec,
      UM1,
      D1,
      D2,
      D3,
      NecesarUM1,
      RelatieUM1,
      Den_UMSec,
      Den_UM1,
      consum
    )
    select
      x.codstare,
      x.codstare1,
      x.codobiect,
      x.stocmin,
      x.stocini,
      x.StocPrec,
      x.Estimari,
      x.CmdF,
      - x.Necesar,
      x.StocFinal,
      x.Pret,
      x.StocVal,
      ROW_NUMBER(),
      x.denumire,
      x.cmdfp,
      x.restprecmd,
      x.restprecmda,
      x.dirty,
      x.dirtycmdf,
      x.part1nec,
      x.UMSec,
      x.UM1,
      x.D1,
      x.D2,
      x.D3,
      - round(
        CASE
          WHEN x.RELATIEUM1 IN (1, 7) AND coalesce(x.D1,0) &lt;&gt; 0 THEN x.NECESAR/x.D1
          WHEN x.RELATIEUM1 IN (2, 8) AND coalesce(x.D1,0) * coalesce(x.D2,0) &lt;&gt; 0 THEN x.NECESAR / (coalesce(x.D1,0) * coalesce(x.D2,0))
          WHEN x.RELATIEUM1 IN (3, 9) AND coalesce(x.D1,0) * coalesce(x.D2,0) * coalesce(x.D3,0) &lt;&gt; 0 THEN x.NECESAR / (coalesce(x.D1,0) * coalesce(x.D2,0) * coalesce(x.D3,0))
          WHEN x.RELATIEUM1 IN (4, 10) THEN x.NECESAR * coalesce(x.D1,0)
          WHEN x.RELATIEUM1 IN (5, 11) THEN x.NECESAR * coalesce(x.D1,0) * coalesce(x.D2,0)
          WHEN x.RELATIEUM1 IN (6, 12) THEN x.NECESAR * coalesce(x.D1,0) * coalesce(x.D2,0) * coalesce(x.D3,0)
        END,7) NecesarUM1,
      x.RelatieUM1,
      x.Den_UMSec,
      x.Den_UM1,
      x.consum
    from
    (
     select
      se.codstare,
      se1.codstare1,
      se1.codobiect,
      coalesce(se1.stocmin,0) stocmin,
      coalesce(se1.stocini,0) StocIni,
      case
        when aSetG = aSet and aAnG = aAn then se1.StocIni
        else coalesce(se1.stocini,0) + coalesce(CmdFP_prec.resta,0) + coalesce(CmdFFix_prec.resta,0) + coalesce(CmdFL_prec.resta,0) - coalesce(EstIntP.resta,0)
      end StocPrec,
      coalesce(se1.estimat,0) Estimari,
      coalesce(CmdFP.resta,0) + coalesce(CmdFFix.resta,0) + coalesce(CmdFL.resta,0) CmdF,
      case
        when aSetG = aSet and aAnG = aAn then coalesce(se1.stocini,0) + coalesce(CmdFP_prec.resta,0) + coalesce(CmdFFix_prec.resta,0) + coalesce(CmdFL_prec.resta,0) + coalesce(CmdFP.resta,0) + coalesce(CmdFFix.resta,0) + coalesce(CmdFL.resta,0) - coalesce(se1.estimat,0)
        else coalesce(se1.stocini,0) + coalesce(CmdFP_prec.resta,0) + coalesce(CmdFFix_prec.resta,0) + coalesce(CmdFL_prec.resta,0) + coalesce(CmdFP.resta,0) + coalesce(CmdFFix.resta,0) + coalesce(CmdFL.resta,0) - coalesce(EstIntP.resta,0) - coalesce(se1.estimat,0)
      end - coalesce(se1.stocmin,0) Necesar,
      case
        when aSetG = aSet and aAnG = aAn then coalesce(se1.stocini,0) + coalesce(CmdFP_prec.resta,0) + coalesce(CmdFFix_prec.resta,0) + coalesce(CmdFL_prec.resta,0) + coalesce(CmdFP.resta,0) + coalesce(CmdFFix.resta,0) + coalesce(CmdFL.resta,0) - coalesce(se1.estimat,0)
        else coalesce(se1.stocini,0) + coalesce(CmdFP.resta,0) + coalesce(CmdFP_prec.resta,0) + coalesce(CmdFFix_prec.resta,0) + coalesce(CmdFL_prec.resta,0) + coalesce(CmdFFix.resta,0) + coalesce(CmdFL.resta,0) - coalesce(EstIntP.resta,0) - coalesce(se1.estimat,0)
      end StocFinal,
      coalesce(se1.pret,0) pret,
      coalesce(se1.pret,0) * (
        case
          when aSetG = aSet and aAnG = aAn then coalesce(se1.stocini,0) + coalesce(CmdFP_prec.resta,0) + coalesce(CmdFFix_prec.resta,0) + coalesce(CmdFL_prec.resta,0) + coalesce(CmdFP.resta,0) + coalesce(CmdFFix.resta,0) + coalesce(CmdFL.resta,0) - coalesce(se1.estimat,0)
          else coalesce(se1.stocini,0) + coalesce(CmdFP_prec.resta,0) + coalesce(CmdFFix_prec.resta,0) + coalesce(CmdFL_prec.resta,0) + coalesce(CmdFP.resta,0) + coalesce(CmdFFix.resta,0) + coalesce(CmdFL.resta,0) - coalesce(EstIntP.resta,0) - coalesce(se1.estimat,0)
        end
      ) stocval,
      obj.denumire,
      cmdfp.resta CMDFP,
      coalesce(RESTC.RESTA,0) RESTPRECMD,
      coalesce(RESTCA.RESTA,0) RESTPRECMDA,
      se1.dirty,
      se1.dirtycmdf,
      se1.part1nec,
      um.codum1 UMSec,
      um1.codum UM1,
      art.d1,
      art.d2,
      art.d3,
      art.relatieum1,
      um.Den_UM1 Den_UMSec,
      um1.Den_Um Den_UM1,
      se1.consum
    from stareestimari se
         inner join stareestimari1 se1 on se1.codstare = se.codstare
         inner join nartobj obj on se1.codobiect = obj.codobiect
         inner join nart art on art.codarticol = obj.codarticol
         left join num1 um on um.codum = art.um and coalesce(um.secundara,0) = 0
         left join num um1 on um1.codum = art.um1
         left join tmp_cmd EstIntP on EstIntP.codobiect = se1.codobiect and EstIntP.Tip = 'ESTINTP'
         left join tmp_cmd cmdfp on cmdfp.codobiect = se1.codobiect and cmdfp.tip = 'CMDFP'
         left join tmp_cmd cmdffix on cmdffix.codobiect = se1.codobiect and cmdffix.tip = 'CMDFFIX'
         left join tmp_cmd cmdfl on cmdfl.codobiect = se1.codobiect and cmdfl.tip = 'CMDFL'
         left join tmp_cmd cmdfp_prec on cmdfp_prec.codobiect = se1.codobiect and cmdfp_prec.tip = 'CMDFP_PREC'
         left join tmp_cmd cmdffix_prec on cmdffix_prec.codobiect = se1.codobiect and cmdffix_prec.tip = 'CMDFFIX_PREC'
         left join tmp_cmd cmdfl_prec on cmdfl_prec.codobiect = se1.codobiect and cmdfl_prec.tip = 'CMDFL_PREC'
         LEFT JOIN TMP_CMD RESTC ON RESTC.CODOBIECT = SE1.CODSTARE1 AND RESTC.TIP = 'RESTC'
         LEFT JOIN TMP_CMD RESTCA ON RESTCA.CODOBIECT = SE1.CODSTARE1 AND RESTCA.TIP = 'RESTCA'
    where se.an = aAn and se.saptamana = aSet and se.ang = aAnG and se.saptamanag = aSetG
            and se.subunitatea = aSubunitatea and se1.codobiect &gt; 0
            and tmp.tip = 'CODOBIECT'
      order by obj.denumire) x;
    else
      insert into tmp_stareestimari1 (
        codstare,
        codstare1,
        codobiect,
        stocmin,
        stocini,
        StocPrec,
        Estimari,
        CmdF,
        Necesar,
        StocFinal,
        Pret,
        StocVal,
        indexlocal,
        denumire,
        CMDFP,
        RESTPRECMD,
        RESTPRECMDA,
        DIRTY,
        DIRTYCMDF,
        PART1NEC,
        UMSec,
        UM1,
        D1,
        D2,
        D3,
        NecesarUM1,
        RelatieUM1,
        Den_UMSec,
        Den_UM1,
        consum
      )
      select
        x.codstare,
        x.codstare1,
        x.codobiect,
        x.stocmin,
        x.stocini,
        x.StocPrec,
        x.Estimari,
        x.CmdF,
        - x.Necesar Necesar,
        x.StocFinal,
        x.Pret,
        x.StocVal,
        ROW_NUMBER(),
        x.denumire,
        x.cmdfp,
        x.restprecmd,
        x.restprecmda,
        x.dirty,
        x.dirtycmdf,
        x.part1nec,
        x.UMSec,
        x.UM1,
        x.D1,
        x.D2,
        x.D3,
        - round(
          CASE
            WHEN x.RELATIEUM1 IN (1, 7) AND COALESCE(x.D1,0) &lt;&gt; 0 THEN x.NECESAR/x.D1
            WHEN x.RELATIEUM1 IN (2, 8) AND COALESCE(x.D1,0) * COALESCE(x.D2,0) &lt;&gt; 0 THEN x.NECESAR / (COALESCE(x.D1,0) * COALESCE(x.D2,0))
            WHEN x.RELATIEUM1 IN (3, 9) AND COALESCE(x.D1,0) * COALESCE(x.D2,0) * COALESCE(x.D3,0) &lt;&gt; 0 THEN x.NECESAR / (COALESCE(x.D1,0) * COALESCE(x.D2,0) * COALESCE(x.D3,0))
            WHEN x.RELATIEUM1 IN (4, 10) THEN x.NECESAR * COALESCE(x.D1,0)
            WHEN x.RELATIEUM1 IN (5, 11) THEN x.NECESAR * COALESCE(x.D1,0) * COALESCE(x.D2,0)
            WHEN x.RELATIEUM1 IN (6, 12) THEN x.NECESAR * COALESCE(x.D1,0) * COALESCE(x.D2,0) * COALESCE(x.D3,0)
          END,7) NecesarUM1,
        x.RelatieUM1,
        x.Den_UMSec,
        x.Den_UM1,
        x.consum
      from
      (
       select
        se.codstare,
        se1.codstare1,
        se1.codobiect,
        COALESCE(se1.stocmin,0) stocmin,
        COALESCE(se1.stocini,0) StocIni,
        case
          when aSetG = aSet and aAnG = aAn then se1.StocIni
          else COALESCE(se1.stocini,0) + COALESCE(CmdFP.resta,0) + COALESCE(CmdFFix.resta,0) + COALESCE(CmdFL.resta,0) - COALESCE(EstIntP.resta,0)
        end StocPrec,
        COALESCE(se1.estimat,0) Estimari,
        COALESCE(CmdFP.resta,0) + COALESCE(CmdFFix.resta,0) + COALESCE(CmdFL.resta,0) CmdF,
        case
          when aSetG = aSet and aAnG = aAn then COALESCE(se1.stocini,0) + COALESCE(CmdFP.resta,0) + COALESCE(CmdFFix.resta,0) + COALESCE(CmdFL.resta,0) - COALESCE(se1.estimat,0)
          else COALESCE(se1.stocini,0) + COALESCE(CmdFP.resta,0) + COALESCE(CmdFFix.resta,0) + COALESCE(CmdFL.resta,0) - COALESCE(EstIntP.resta,0) - COALESCE(se1.estimat,0)
        end - COALESCE(se1.stocmin,0) Necesar,
        case
          when aSetG = aSet and aAnG = aAn then COALESCE(se1.stocini,0) + COALESCE(CmdFP.resta,0) + COALESCE(CmdFFix.resta,0) + COALESCE(CmdFL.resta,0) - COALESCE(se1.estimat,0)
          else COALESCE(se1.stocini,0) + COALESCE(CmdFP.resta,0) + COALESCE(CmdFFix.resta,0) + COALESCE(CmdFL.resta,0) - COALESCE(EstIntP.resta,0) - COALESCE(se1.estimat,0)
        end StocFinal,
        COALESCE(se1.pret,0) pret,
        COALESCE(se1.pret,0) * (
          case
            when aSetG = aSet and aAnG = aAn then COALESCE(se1.stocini,0) + COALESCE(CmdFP.resta,0) + COALESCE(CmdFFix.resta,0) + COALESCE(CmdFL.resta,0) - COALESCE(se1.estimat,0)
            else COALESCE(se1.stocini,0) + COALESCE(CmdFP.resta,0) + COALESCE(CmdFFix.resta,0) + COALESCE(CmdFL.resta,0) - COALESCE(EstIntP.resta,0) - COALESCE(se1.estimat,0)
          end
        ) stocval,
        obj.denumire,
        cmdfp.resta CMDFP,
        COALESCE(RESTC.RESTA,0) RESTPRECMD,
        COALESCE(RESTCA.RESTA,0) RESTPRECMDA,
        se1.dirty,
        se1.dirtycmdf,
        se1.part1nec,
        um.codum1 UMSec,
        um1.codum UM1,
        art.d1,
        art.d2,
        art.d3,
        art.relatieum1,
        um.Den_UM1 Den_UMSec,
        um1.Den_Um Den_UM1,
        se1.consum
      from stareestimari se
           inner join stareestimari1 se1 on se1.codstare = se.codstare
           inner join nartobj obj on se1.codobiect = obj.codobiect
           inner join nart art on art.codarticol = obj.codarticol
           left join num1 um on um.codum = art.um and COALESCE(um.secundara,0) = 0
           left join num um1 on um1.codum = art.um1
           left join tmp_cmd_tmp EstIntP on EstIntP.codobiect = se1.codobiect and EstIntP.Tip = 'ESTINTP'
           left join tmp_cmd_tmp cmdfp on cmdfp.codobiect = se1.codobiect and cmdfp.tip = 'CMDFP'
           left join tmp_cmd_tmp cmdffix on cmdffix.codobiect = se1.codobiect and cmdffix.tip = 'CMDFFIX'
           left join tmp_cmd_tmp cmdfl on cmdfl.codobiect = se1.codobiect and cmdfl.tip = 'CMDFL'
           LEFT JOIN tmp_cmd_tmp RESTC ON RESTC.CODOBIECT = SE1.CODSTARE1 AND RESTC.TIP = 'RESTC'
           LEFT JOIN tmp_cmd_tmp RESTCA ON RESTCA.CODOBIECT = SE1.CODSTARE1 AND RESTCA.TIP = 'RESTCA'
      where se.an = aAn and se.saptamana = aSet and se.ang = aAnG and se.saptamanag = aSetG
            and se.subunitatea = aSubunitatea and se1.codobiect &gt; 0
      order by obj.denumire) x;
    end if;
  else
    if aAllCls + aAllClsS + aAllProd &gt; 0 then
      insert into tmp_cmd_tmp(codobiect,resta,tip)
      select c1.codobiect, sum(c1.cantacceptat - COALESCE(Storno.RESTA,0)) cant, 'CMDFL'
      from tmp_cmd_tmp tmp, comanda c, comanda1 c1
           LEFT  JOIN tmp_cmd_tmp STORNO ON STORNO.CODOBIECT = C1.CodComanda1 AND STORNO.TIP = 'STORNO'
      where c.tipdoc = 8 and c.operat = 1 and c.anulat = 0
            and c.subunitatea = aSubunitatea and c.codcomanda = c1.codcomanda
            and c1.termen between dataG and dataG + 6
            and c.datacreare &gt; adatacreare
            and not exists (select se2.codcomanda1 from stareestimari2 se2 where se2.codcomanda1 = c1.codcomanda1)
            and not exists (select l.codcomanda1 from planiflink l where l.codcomanda1 = c1.codcomanda1)
            and tmp.codobiect = c1.codobiect and tmp.tip = 'CODOBIECT'
            AND C.datadoc &gt;= add_days(current_date, - 365)
      group by c1.codobiect;
    else
      insert into tmp_cmd_tmp(codobiect,resta,tip)
      select c1.codobiect, sum(c1.cantacceptat - COALESCE(Storno.RESTA,0)) cant, 'CMDFL'
      from comanda c, comanda1 c1
           LEFT  JOIN tmp_cmd_tmp STORNO ON STORNO.CODOBIECT = C1.CodComanda1 AND STORNO.TIP = 'STORNO'
      where c.tipdoc = 8 and c.operat = 1 and c.anulat = 0
            and c.subunitatea = aSubunitatea
            and c1.termen between dataG and dataG + 6
            and c.datacreare &gt; adatacreare AND c.codcomanda = c1.codcomanda
            and not exists (select se2.codcomanda1 from stareestimari2 se2 where se2.codcomanda1 = c1.codcomanda1)
            and not exists (select l.codcomanda1 from planiflink l where l.codcomanda1 = c1.codcomanda1)
            AND C.datadoc &gt;= add_days(current_date, - 365)
      group by c1.codobiect;
    end if;

    if aAllCls + aAllClsS + aAllProd &gt; 0 then
      insert into tmp_cmd_tmp(codobiect,resta,tip)
      select c1.codobiect, sum(c1.cantacceptat - COALESCE(Storno.RESTA,0)) cant, 'CMDFP_PREC'
      from tmp_cmd_tmp tmp, STAREESTIMARI1 SE1, STAREESTIMARI SE, STAREESTIMARI SES, STAREESTIMARI1 SES1, planiflink l, comanda c,
           comanda1 c1
           LEFT JOIN tmp_cmd_tmp STORNO ON STORNO.CODOBIECT = C1.CodComanda1 AND STORNO.TIP = 'STORNO'
      where tmp.codobiect = se1.codobiect and tmp.tip = 'CODOBIECT'
            and se.an = aAn and se.saptamana = aSet and se.ang = aAnG and se.saptamanag = aSetG
            and se.subunitatea = aSubunitatea and SE1.CODSTARE = SE.CODSTARE
            and c.tipdoc = 8 and c.operat = 1 and c.anulat = 0 and c1.codcomanda = c.codcomanda
            and SES.AN = SE.AN AND SES.SAPTAMANA = SE.SAPTAMANA AND SES.ANG * 100 + SES.SAPTAMANAG &lt; SE.ANG * 100 + SE.SAPTAMANAG
            and SES.CODSTARE = SES1.CODSTARE AND SES1.CODOBIECT = SE1.CODOBIECT and l.codstare1 = SES1.codstare1
            and c1.codcomanda1 = l.codcomanda1
            AND C.datadoc &gt;= add_days(current_date, - 365)
      group by c1.codobiect;
    else
      insert into tmp_cmd_tmp(codobiect,resta,tip)
      select c1.codobiect, sum(c1.cantacceptat - COALESCE(Storno.RESTA,0)) cant, 'CMDFP_PREC'
      from STAREESTIMARI1 SE1, STAREESTIMARI SE, STAREESTIMARI SES, STAREESTIMARI1 SES1,
           planiflink l, comanda c, comanda1 c1
           LEFT  JOIN tmp_cmd_tmp STORNO ON STORNO.CODOBIECT = C1.CodComanda1 AND STORNO.TIP = 'STORNO'
      where se.an = aAn and se.saptamana = aSet and se.ang = aAnG and se.saptamanag = aSetG
            and se.subunitatea = aSubunitatea and SE1.CODSTARE = SE.CODSTARE
            and c.tipdoc = 8 and c.operat = 1 and c.anulat = 0
            and SES.AN = SE.AN AND SES.SAPTAMANA = SE.SAPTAMANA AND SES.ANG * 100 + SES.SAPTAMANAG &lt; SE.ANG * 100 + SE.SAPTAMANAG
            and SES.CODSTARE = SES1.CODSTARE AND SES1.CODOBIECT = SE1.CODOBIECT
            and l.codstare1 = SES1.codstare1 and c1.codcomanda1 = l.codcomanda1
            and c1.codcomanda = c.codcomanda
            AND C.datadoc &gt;= add_days(current_date, - 365)
      group by c1.codobiect;
    end if;

    if aAllCls + aAllClsS + aAllProd &gt; 0 then
      insert into tmp_cmd_tmp(codobiect,resta,tip)
      select se1.codobiect, sum(se2.restacceptat) cant, 'CMDFFIX_PREC'
      FROM tmp_cmd_tmp tmp
      INNER JOIN STAREESTIMARI1 SE1  ON SE1.CODOBIECT = TMP.CODOBIECT
      INNER JOIN STAREESTIMARI  SE   ON SE1.CODSTARE  = SE.CODSTARE
      INNER JOIN STAREESTIMARI  SES  ON SES.SAPTAMANA = SE.SAPTAMANA AND SES.AN = SE.AN AND SES.ANG * 100 + SES.SAPTAMANAG &lt; SE.ANG * 100 + SE.SAPTAMANAG
      INNER JOIN STAREESTIMARI1 SES1 ON SES1.CODSTARE = SES.CODSTARE AND SES1.CODOBIECT = SE1.CODOBIECT
      INNER JOIN STAREESTIMARI2 SE2  ON SE2.CODSTARE  = SES.CODSTARE AND SE2.CODSTARE1  = SES1.CODSTARE1
      WHERE tmp.tip = 'CODOBIECT'
      AND se.an = aAn AND se.saptamana = aSet AND se.ang = aAnG AND se.saptamanag = aSetG
      AND se.subunitatea = aSubunitatea
      group by se1.codobiect;
    else
      insert into tmp_cmd_tmp(codobiect,resta,tip)
      select se1.codobiect, sum(se2.restacceptat) cant, 'CMDFFIX_PREC'
      FROM STAREESTIMARI1 SE1
      INNER JOIN STAREESTIMARI  SE   ON SE1.CODSTARE  = SE.CODSTARE
      INNER JOIN STAREESTIMARI  SES  ON SES.SAPTAMANA = SE.SAPTAMANA AND SES.AN = SE.AN AND SES.ANG * 100 + SES.SAPTAMANAG &lt; SE.ANG * 100 + SE.SAPTAMANAG
      INNER JOIN STAREESTIMARI1 SES1 ON SES1.CODSTARE = SES.CODSTARE AND SES1.CODOBIECT = SE1.CODOBIECT
      INNER JOIN STAREESTIMARI2 SE2  ON SE2.CODSTARE  = SES.CODSTARE AND SE2.CODSTARE1  = SES1.CODSTARE1
      where se.an = aAn and se.saptamana = aSet and se.ang = aAnG and se.saptamanag = aSetG
            and se.subunitatea = aSubunitatea
      group by se1.codobiect;
    end if;

    if aAllCls + aAllClsS + aAllProd &gt; 0 then
      insert into tmp_cmd_tmp(codobiect,resta,tip)
      select c1.codobiect, sum(c1.cantacceptat - COALESCE(Storno.RESTA,0)) cant, 'CMDFL_PREC'
      from tmp_cmd_tmp tmp,comanda c,comanda1 c1
           LEFT  JOIN tmp_cmd_tmp STORNO ON STORNO.CODOBIECT = C1.CodComanda1 AND STORNO.TIP = 'STORNO'
      where c.tipdoc = 8 and c.operat = 1 and c.anulat = 0
            and c.subunitatea = aSubunitatea and tmp.codobiect = c1.codobiect and tmp.tip = 'CODOBIECT'
            and c1.termen &lt; dataG and c.codcomanda = c1.codcomanda
            and c.datacreare &gt; adatacreare
            and not exists (select se2.codcomanda1 from stareestimari2 se2 where se2.codcomanda1 = c1.codcomanda1)
            and not exists (select l.codcomanda1 from planiflink l where l.codcomanda1 = c1.codcomanda1)
            AND C.datadoc &gt;= add_days(current_date, - 365)
      group by c1.codobiect;
    else
      insert into tmp_cmd_tmp(codobiect,resta,tip)
      select c1.codobiect, sum(c1.cantacceptat - COALESCE(Storno.RESTA,0)) cant, 'CMDFL_PREC'
      from comanda c,comanda1 c1
           LEFT  JOIN tmp_cmd_tmp STORNO ON STORNO.CODOBIECT = C1.CodComanda1 AND STORNO.TIP = 'STORNO'
      where c.tipdoc = 8 and c.operat = 1 and c.anulat = 0
            and c.subunitatea = aSubunitatea
            and c1.termen &lt; dataG and c.codcomanda = c1.codcomanda
            and c.datacreare &gt; adatacreare
            and not exists (select se2.codcomanda1 from stareestimari2 se2 where se2.codcomanda1 = c1.codcomanda1)
            and not exists (select l.codcomanda1 from planiflink l where l.codcomanda1 = c1.codcomanda1)
            AND C.datadoc &gt;= add_days(current_date, - 365)
      group by c1.codobiect;
    end if;

    if aAllCls + aAllClsS + aAllProd &gt; 0 then
      insert into tmp_stareestimari1 (
        codstare,
        codstare1,
        codobiect,
        stocmin,
        stocini,
        StocPrec,
        Estimari,
        CmdF,
        Necesar,
        StocFinal,
        Pret,
        StocVal,
        indexlocal,
        denumire,
        CMDFP,
        RESTPRECMD,
        RESTPRECMDA,
        DIRTY,
        DIRTYCMDF,
        PART1NEC,
        UMSec,
        UM1,
        D1,
        D2,
        D3,
        NecesarUM1,
        RelatieUM1,
        Den_UMSec,
        Den_UM1,
        consum
      )
      select
        x.codstare,
        x.codstare1,
        x.codobiect,
        x.stocmin,
        x.stocini,
        x.StocPrec,
        x.Estimari,
        x.CmdF,
        - x.Necesar,
        x.StocFinal,
        x.Pret,
        x.StocVal,
        ROW_NUMBER(),
        x.denumire,
        x.cmdfp,
        x.restprecmd,
        x.restprecmda,
        x.dirty,
        x.dirtycmdf,
        x.part1nec,
        x.UMSec,
        x.UM1,
        x.D1,
        x.D2,
        x.D3,
        - round(
          CASE
            WHEN x.RELATIEUM1 IN (1, 7) AND COALESCE(x.D1,0) &lt;&gt; 0 THEN x.NECESAR/x.D1
            WHEN x.RELATIEUM1 IN (2, 8) AND COALESCE(x.D1,0) * COALESCE(x.D2,0) &lt;&gt; 0 THEN x.NECESAR / (COALESCE(x.D1,0) * COALESCE(x.D2,0))
            WHEN x.RELATIEUM1 IN (3, 9) AND COALESCE(x.D1,0) * COALESCE(x.D2,0) * COALESCE(x.D3,0) &lt;&gt; 0 THEN x.NECESAR / (COALESCE(x.D1,0) * COALESCE(x.D2,0) * COALESCE(x.D3,0))
            WHEN x.RELATIEUM1 IN (4, 10) THEN x.NECESAR * COALESCE(x.D1,0)
            WHEN x.RELATIEUM1 IN (5, 11) THEN x.NECESAR * COALESCE(x.D1,0) * COALESCE(x.D2,0)
            WHEN x.RELATIEUM1 IN (6, 12) THEN x.NECESAR * COALESCE(x.D1,0) * COALESCE(x.D2,0) * COALESCE(x.D3,0)
          END,7) NecesarUM1,
        x.RelatieUM1,
        x.Den_UMSec,
        x.Den_UM1,
        x.consum
      from
      (
       select
        se.codstare,
        se1.codstare1,
        se1.codobiect,
        COALESCE(se1.stocmin,0) stocmin,
        COALESCE(se1.stocini,0) StocIni,
        case
          when aSetG = aSet and aAnG = aAn then se1.StocIni
          else COALESCE(se1.stocini,0) + COALESCE(CmdFP_prec.resta,0) + COALESCE(CmdFFix_prec.resta,0) + COALESCE(CmdFL_prec.resta,0) - COALESCE(EstIntP.resta,0)
        end StocPrec,
        COALESCE(se1.estimat,0) Estimari,
        COALESCE(CmdFP.resta,0) + COALESCE(CmdFFix.resta,0) + COALESCE(CmdFL.resta,0) CmdF,
        case
          when aSetG = aSet and aAnG = aAn then COALESCE(se1.stocini,0) + COALESCE(CmdFP_prec.resta,0) + COALESCE(CmdFFix_prec.resta,0) + COALESCE(CmdFL_prec.resta,0) + COALESCE(CmdFP.resta,0) + COALESCE(CmdFFix.resta,0) + COALESCE(CmdFL.resta,0) - COALESCE(se1.estimat,0)
          else COALESCE(se1.stocini,0) + COALESCE(CmdFP_prec.resta,0) + COALESCE(CmdFFix_prec.resta,0) + COALESCE(CmdFL_prec.resta,0) + COALESCE(CmdFP.resta,0) + COALESCE(CmdFFix.resta,0) + COALESCE(CmdFL.resta,0) - COALESCE(EstIntP.resta,0) - COALESCE(se1.estimat,0)
        end - COALESCE(se1.stocmin,0) Necesar,
        case
          when aSetG = aSet and aAnG = aAn then COALESCE(se1.stocini,0) + COALESCE(CmdFP_prec.resta,0) + COALESCE(CmdFFix_prec.resta,0) + COALESCE(CmdFL_prec.resta,0) + COALESCE(CmdFP.resta,0) + COALESCE(CmdFFix.resta,0) + COALESCE(CmdFL.resta,0) - COALESCE(se1.estimat,0)
          else COALESCE(se1.stocini,0) + COALESCE(CmdFP.resta,0) + COALESCE(CmdFP_prec.resta,0) + COALESCE(CmdFFix_prec.resta,0) + COALESCE(CmdFL_prec.resta,0) + COALESCE(CmdFFix.resta,0) + COALESCE(CmdFL.resta,0) - COALESCE(EstIntP.resta,0) - COALESCE(se1.estimat,0)
        end StocFinal,
        COALESCE(se1.pret,0) pret,
        COALESCE(se1.pret,0) * (
          case
            when aSetG = aSet and aAnG = aAn then COALESCE(se1.stocini,0) + COALESCE(CmdFP_prec.resta,0) + COALESCE(CmdFFix_prec.resta,0) + COALESCE(CmdFL_prec.resta,0) + COALESCE(CmdFP.resta,0) + COALESCE(CmdFFix.resta,0) + COALESCE(CmdFL.resta,0) - COALESCE(se1.estimat,0)
            else COALESCE(se1.stocini,0) + COALESCE(CmdFP_prec.resta,0) + COALESCE(CmdFFix_prec.resta,0) + COALESCE(CmdFL_prec.resta,0) + COALESCE(CmdFP.resta,0) + COALESCE(CmdFFix.resta,0) + COALESCE(CmdFL.resta,0) - COALESCE(EstIntP.resta,0) - COALESCE(se1.estimat,0)
          end
        ) stocval,
        obj.denumire,
        cmdfp.resta CMDFP,
        COALESCE(RESTC.RESTA,0) RESTPRECMD,
        COALESCE(RESTCA.RESTA,0) RESTPRECMDA,
        se1.dirty,
        se1.dirtycmdf,
        se1.part1nec,
        um.codum1 UMSec,
        um1.codum UM1,
        art.d1,
        art.d2,
        art.d3,
        art.relatieum1,
        um.Den_UM1 Den_UMSec,
        um1.Den_Um Den_UM1,
        se1.consum
      from stareestimari se
           inner join stareestimari1 se1 on se1.codstare = se.codstare
           inner join nartobj obj on se1.codobiect = obj.codobiect
           inner join nart art on art.codarticol = obj.codarticol
           inner join tmp_cmd_tmp tmp on tmp.codobiect = se1.codobiect
           left join num1 um on um.codum = art.um and COALESCE(um.secundara,0) = 0
           left join num um1 on um1.codum = art.um1
           left join tmp_cmd_tmp EstIntP on EstIntP.codobiect = se1.codobiect and EstIntP.Tip = 'ESTINTP'
           left join tmp_cmd_tmp cmdfp on cmdfp.codobiect = se1.codobiect and cmdfp.tip = 'CMDFP'
           left join tmp_cmd_tmp cmdffix on cmdffix.codobiect = se1.codobiect and cmdffix.tip = 'CMDFFIX'
           left join tmp_cmd_tmp cmdfl on cmdfl.codobiect = se1.codobiect and cmdfl.tip = 'CMDFL'
           left join tmp_cmd_tmp cmdfp_prec on cmdfp_prec.codobiect = se1.codobiect and cmdfp_prec.tip = 'CMDFP_PREC'
           left join tmp_cmd_tmp cmdffix_prec on cmdffix_prec.codobiect = se1.codobiect and cmdffix_prec.tip = 'CMDFFIX_PREC'
           left join tmp_cmd_tmp cmdfl_prec on cmdfl_prec.codobiect = se1.codobiect and cmdfl_prec.tip = 'CMDFL_PREC'
           LEFT JOIN tmp_cmd_tmp RESTC ON RESTC.CODOBIECT = SE1.CODSTARE1 AND RESTC.TIP = 'RESTC'
           LEFT JOIN tmp_cmd_tmp RESTCA ON RESTCA.CODOBIECT = SE1.CODSTARE1 AND RESTCA.TIP = 'RESTCA'
      where se.an = aAn and se.saptamana = aSet and se.ang = aAnG and se.saptamanag = aSetG
            and se.subunitatea = aSubunitatea and se1.codobiect &gt; 0
            and tmp.tip = 'CODOBIECT'
      order by obj.denumire) x;
    else
      insert into tmp_stareestimari1 (
        codstare,
        codstare1,
        codobiect,
        stocmin,
        stocini,
        StocPrec,
        Estimari,
        CmdF,
        Necesar,
        StocFinal,
        Pret,
        StocVal,
        indexlocal,
        denumire,
        CMDFP,
        RESTPRECMD,
        RESTPRECMDA,
        DIRTY,
        DIRTYCMDF,
        PART1NEC,
        UMSec,
        UM1,
        D1,
        D2,
        D3,
        NecesarUM1,
        RelatieUM1,
        Den_UMSec,
        Den_UM1,
        consum
      )
      select
        x.codstare,
        x.codstare1,
        x.codobiect,
        x.stocmin,
        x.stocini,
        x.StocPrec,
        x.Estimari,
        x.CmdF,
        - x.Necesar,
        x.StocFinal,
        x.Pret,
        x.StocVal,
        ROW_NUMBER(),
        x.denumire,
        x.cmdfp,
        x.restprecmd,
        x.restprecmda,
        x.dirty,
        x.dirtycmdf,
        x.part1nec,
        x.UMSec,
        x.UM1,
        x.D1,
        x.D2,
        x.D3,
        - round(
          CASE
            WHEN x.RELATIEUM1 IN (1, 7) AND COALESCE(x.D1,0) &lt;&gt; 0 THEN x.NECESAR/x.D1
            WHEN x.RELATIEUM1 IN (2, 8) AND COALESCE(x.D1,0) * COALESCE(x.D2,0) &lt;&gt; 0 THEN x.NECESAR / (COALESCE(x.D1,0) * COALESCE(x.D2,0))
            WHEN x.RELATIEUM1 IN (3, 9) AND COALESCE(x.D1,0) * COALESCE(x.D2,0) * COALESCE(x.D3,0) &lt;&gt; 0 THEN x.NECESAR / (COALESCE(x.D1,0) * COALESCE(x.D2,0) * COALESCE(x.D3,0))
            WHEN x.RELATIEUM1 IN (4, 10) THEN x.NECESAR * COALESCE(x.D1,0)
            WHEN x.RELATIEUM1 IN (5, 11) THEN x.NECESAR * COALESCE(x.D1,0) * COALESCE(x.D2,0)
            WHEN x.RELATIEUM1 IN (6, 12) THEN x.NECESAR * COALESCE(x.D1,0) * COALESCE(x.D2,0) * COALESCE(x.D3,0)
          END,7) NecesarUM1,
        x.RelatieUM1,
        x.Den_UMSec,
        x.Den_UM1,
        x.consum
      from
      (
       select
        se.codstare,
        se1.codstare1,
        se1.codobiect,
        COALESCE(se1.stocmin,0) stocmin,
        COALESCE(se1.stocini,0) StocIni,
        case
          when aSetG = aSet and aAnG = aAn then se1.StocIni
          else COALESCE(se1.stocini,0) + COALESCE(CmdFP_prec.resta,0) + COALESCE(CmdFFix_prec.resta,0) + COALESCE(CmdFL_prec.resta,0) - COALESCE(EstIntP.resta,0)
        end StocPrec,
        COALESCE(se1.estimat,0) Estimari,
        COALESCE(CmdFP.resta,0) + COALESCE(CmdFFix.resta,0) + COALESCE(CmdFL.resta,0) CmdF,
        case
          when aSetG = aSet and aAnG = aAn then COALESCE(se1.stocini,0) + COALESCE(CmdFP_prec.resta,0) + COALESCE(CmdFFix_prec.resta,0) + COALESCE(CmdFL_prec.resta,0) + COALESCE(CmdFP.resta,0) + COALESCE(CmdFFix.resta,0) + COALESCE(CmdFL.resta,0) - COALESCE(se1.estimat,0)
          else COALESCE(se1.stocini,0) + COALESCE(CmdFP_prec.resta,0) + COALESCE(CmdFFix_prec.resta,0) + COALESCE(CmdFL_prec.resta,0) + COALESCE(CmdFP.resta,0) + COALESCE(CmdFFix.resta,0) + COALESCE(CmdFL.resta,0) - COALESCE(EstIntP.resta,0) - COALESCE(se1.estimat,0)
        end - COALESCE(se1.stocmin,0) Necesar,
        case
          when aSetG = aSet and aAnG = aAn then COALESCE(se1.stocini,0) + COALESCE(CmdFP_prec.resta,0) + COALESCE(CmdFFix_prec.resta,0) + COALESCE(CmdFL_prec.resta,0) + COALESCE(CmdFP.resta,0) + COALESCE(CmdFFix.resta,0) + COALESCE(CmdFL.resta,0) - COALESCE(se1.estimat,0)
          else COALESCE(se1.stocini,0) + COALESCE(CmdFP.resta,0) + COALESCE(CmdFP_prec.resta,0) + COALESCE(CmdFFix_prec.resta,0) + COALESCE(CmdFL_prec.resta,0) + COALESCE(CmdFFix.resta,0) + COALESCE(CmdFL.resta,0) - COALESCE(EstIntP.resta,0) - COALESCE(se1.estimat,0)
        end StocFinal,
        COALESCE(se1.pret,0) pret,
        COALESCE(se1.pret,0) * (
          case
            when aSetG = aSet and aAnG = aAn then COALESCE(se1.stocini,0) + COALESCE(CmdFP_prec.resta,0) + COALESCE(CmdFFix_prec.resta,0) + COALESCE(CmdFL_prec.resta,0) + COALESCE(CmdFP.resta,0) + COALESCE(CmdFFix.resta,0) + COALESCE(CmdFL.resta,0) - COALESCE(se1.estimat,0)
            else COALESCE(se1.stocini,0) + COALESCE(CmdFP_prec.resta,0) + COALESCE(CmdFFix_prec.resta,0) + COALESCE(CmdFL_prec.resta,0) + COALESCE(CmdFP.resta,0) + COALESCE(CmdFFix.resta,0) + COALESCE(CmdFL.resta,0) - COALESCE(EstIntP.resta,0) - COALESCE(se1.estimat,0)
          end
        ) stocval,
        obj.denumire,
        cmdfp.resta CMDFP,
        COALESCE(RESTC.RESTA,0) RESTPRECMD,
        COALESCE(RESTCA.RESTA,0) RESTPRECMDA,
        se1.dirty,
        se1.dirtycmdf,
        se1.part1nec,
        um.codum1 UMSec,
        um1.codum UM1,
        art.d1,
        art.d2,
        art.d3,
        art.relatieum1,
        um.Den_UM1 Den_UMSec,
        um1.Den_Um Den_UM1,
        se1.consum
      from stareestimari se
           inner join stareestimari1 se1 on se1.codstare = se.codstare
           inner join nartobj obj on se1.codobiect = obj.codobiect
           inner join nart art on art.codarticol = obj.codarticol
           left join num1 um on um.codum = art.um and COALESCE(um.secundara,0) = 0
           left join num um1 on um1.codum = art.um1
           left join tmp_cmd_tmp EstIntP on EstIntP.codobiect = se1.codobiect and EstIntP.Tip = 'ESTINTP'
           left join tmp_cmd_tmp cmdfp on cmdfp.codobiect = se1.codobiect and cmdfp.tip = 'CMDFP'
           left join tmp_cmd_tmp cmdffix on cmdffix.codobiect = se1.codobiect and cmdffix.tip = 'CMDFFIX'
           left join tmp_cmd_tmp cmdfl on cmdfl.codobiect = se1.codobiect and cmdfl.tip = 'CMDFL'
           left join tmp_cmd_tmp cmdfp_prec on cmdfp_prec.codobiect = se1.codobiect and cmdfp_prec.tip = 'CMDFP_PREC'
           left join tmp_cmd_tmp cmdffix_prec on cmdffix_prec.codobiect = se1.codobiect and cmdffix_prec.tip = 'CMDFFIX_PREC'
           left join tmp_cmd_tmp cmdfl_prec on cmdfl_prec.codobiect = se1.codobiect and cmdfl_prec.tip = 'CMDFL_PREC'
           LEFT JOIN tmp_cmd_tmp RESTC ON RESTC.CODOBIECT = SE1.CODSTARE1 AND RESTC.TIP = 'RESTC'
           LEFT JOIN tmp_cmd_tmp RESTCA ON RESTCA.CODOBIECT = SE1.CODSTARE1 AND RESTCA.TIP = 'RESTCA'
      where se.an = aAn and se.saptamana = aSet and se.ang = aAnG and se.saptamanag = aSetG
            and se.subunitatea = aSubunitatea and se1.codobiect &gt; 0
      order by obj.denumire) x;
    end if;
  end if;

  UPDATE tmp_stareestimari1
  SET
    restnecesar = CASE WHEN necesar - restprecmd - restprecmda &lt; 0 THEN 0 ELSE necesar - restprecmd - restprecmda END ,
    StocDC      = StocFinal + cmdfp,
    valnecesar  = COALESCE (necesar, 0) * COALESCE (pret, 0);

  IF RemoveDirtyCmdF THEN
    UPDATE stareestimari1 se1
    SET dirtycmdf = 0
    WHERE
      EXISTS (SELECT se.codstare
              FROM stareestimari se
              WHERE
                se.an = aAn
                and se.saptamana = aSet
                and se.ang = aang
                and se.saptamanag  = aSetG
                and se.codstare    = se1.codstare
                and se.subunitatea = aSubunitatea);

    UPDATE tmp_stareestimari1 SET dirtycmdf = 0;
  END IF;
  delete FROM tmp_cmd;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_setvallcls</obj_name>
  <obj_hashval>9850f680c2681fb8bf89e5029e391058</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_setvallcls(avallcls numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANIFCMD.vAllCls',to_char(avAllCls,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_umpletemporargenerator</obj_name>
  <obj_hashval>577cb4ed1cf2ba7de3ddf3b199bb1c88</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_umpletemporargenerator(vanset numeric, vuserid numeric, vsubunitatea numeric, vcodobiect numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V          RECORD;
  vNextAnSet numeric;
begin
  vNextAnSet := vAnSet + 1;

  DELETE FROM TMP_CMDTL WHERE USERID = vUserId;

  IF  vCodObiect &gt; 0 THEN
    FOR V IN (SELECT PNOD.CODOBIECT CODOBIECT, sum( PNOD.NECESAR) NECESAR
              FROM PLANIFNOD PNOD
                  INNER JOIN PLANIFPROD1 PP1 ON  PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                  INNER JOIN PLANIFPROD  PP  ON  PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
              WHERE PP.An * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, PP.An)) + PP.SAPTAMANA = vAnSet and  PNOD.CodObiect = vCodObiect and  PP.OPERAT = 1 AND  PP.ANULAT = 0 AND  PP.BLOCAT = 0 and  PNOD.TIP = 3 AND  PP.SUBUNITATEA = vSubunitatea
              GROUP BY PNOD.CODOBIECT
             )
    LOOP
      UPDATE  TMP_CMDTL TMP
       SET
       RESTA = COALESCE( TMP.RESTA, 0) + V.NECESAR,
       CANTA = COALESCE( TMP.CANTA, 0) + V.NECESAR
      WHERE TMP.CODOBIECT = V.CODOBIECT and  TMP.USERID = VUSERID AND  TMP.TIP = 1;

      IF NOT FOUND THEN
        INSERT INTO TMP_CMDTL(CODOBIECT, RESTA, CANTA, USERID, CODCMDTL, TIP)
        VALUES (V.CODOBIECT, V.NECESAR, V.NECESAR, VUSERID, NEXTVAL('SEQ_CMDTL_CODCMDTL'), 1) ;
      END IF;
    END LOOP;

    FOR V IN (SELECT CMD.CODOBIECT CODOBIECT, sum( IL.CANT) STINS
              FROM IESPRODLINK IL
                  INNER JOIN CMDPRODMAT CMD ON  IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT
                  INNER JOIN LANSZ1     L1  ON  CMD.CODCOMANDA1  = L1.CODCMD1_LUNI
                  INNER JOIN LANSZ      L   ON  L1.CODLANSZ = L.CODLANSZ
              WHERE COALESCE( L.ANULAT, 0) = 0 AND  L.AN * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, L.An)) + l.saptamana = vAnSet AND  CMD.TIP = 1 AND  L.SUBUNITATEA = vSubunitatea and  cmd.codobiect = vCodObiect
              GROUP BY CMD.CODOBIECT
    )
    LOOP
      UPDATE  TMP_CMDTL TMP
       SET
       RESTA = COALESCE( TMP.RESTA, 0) - V.STINS,
       CANTC = COALESCE( TMP.CANTC, 0) + V.STINS
      WHERE TMP.CODOBIECT = V.CODOBIECT AND  TMP.USERID = VUSERID AND  TMP.TIP = 1;
    END LOOP;

    FOR V IN (SELECT CMD.CODOBIECT CODOBIECT, SUM( IL.CANT) STINS
              FROM IESPRODLINK IL
                  INNER JOIN CMDPRODMAT CMD ON  IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT
                  INNER JOIN LANSZ1     L1  ON  CMD.CODCOMANDA1  = L1.CODCMD1_MARTI
                  INNER JOIN LANSZ      L   ON  L1.CODLANSZ = L.CODLANSZ
              WHERE COALESCE( L.ANULAT, 0) = 0 AND  L.AN * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, L.An)) + l.saptamana = vAnSet AND  CMD.TIP = 1 AND  L.SUBUNITATEA = vSubunitatea and  cmd.codobiect = vCodObiect
              GROUP BY CMD.CODOBIECT
             )
    LOOP
      UPDATE  TMP_CMDTL TMP
      SET
      RESTA = COALESCE( TMP.RESTA, 0) - V.STINS,
      CANTC = COALESCE( TMP.CANTC, 0) + V.STINS
      WHERE TMP.CODOBIECT = V.CODOBIECT AND  TMP.USERID = VUSERID AND  TMP.TIP = 1;
    END LOOP;

    FOR V IN (SELECT CMD.CODOBIECT CODOBIECT, SUM( IL.CANT) STINS
              FROM IESPRODLINK IL
                  INNER JOIN CMDPRODMAT CMD ON  IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT
                  INNER JOIN LANSZ1     L1  ON  CMD.CODCOMANDA1  = L1.CODCMD1_MIERCURI
                  INNER JOIN LANSZ      L   ON  L1.CODLANSZ = L.CODLANSZ
              WHERE COALESCE( L.ANULAT, 0) = 0 AND  L.AN * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, L.An)) + l.saptamana = vAnSet AND  CMD.TIP = 1 AND  L.SUBUNITATEA = vSubunitatea and  cmd.codobiect = vCodObiect
              GROUP BY CMD.CODOBIECT
  )
    LOOP
      UPDATE  TMP_CMDTL TMP
       SET
       RESTA = COALESCE( TMP.RESTA, 0) - V.STINS,
       CANTC = COALESCE( TMP.CANTC, 0) + V.STINS
      WHERE TMP.CODOBIECT = V.CODOBIECT AND  TMP.USERID = VUSERID AND  TMP.TIP = 1;
    END LOOP;

    FOR V IN (SELECT CMD.CODOBIECT CODOBIECT, SUM( IL.CANT) STINS
              FROM IESPRODLINK IL
                  INNER JOIN CMDPRODMAT CMD ON  IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT
                  INNER JOIN LANSZ1     L1  ON  CMD.CODCOMANDA1  = L1.CODCMD1_JOI
                  INNER JOIN LANSZ      L   ON  L1.CODLANSZ = L.CODLANSZ
              WHERE COALESCE( L.ANULAT, 0) = 0 AND  L.AN * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, L.An)) + l.saptamana = vAnSet AND  CMD.TIP = 1 AND  L.SUBUNITATEA = vSubunitatea and  cmd.codobiect = vCodObiect
              GROUP BY CMD.CODOBIECT
             )
    LOOP
      UPDATE  TMP_CMDTL TMP
      SET
      RESTA = COALESCE( TMP.RESTA, 0) - V.STINS,
      CANTC = COALESCE( TMP.CANTC, 0) + V.STINS
      WHERE TMP.CODOBIECT = V.CODOBIECT AND  TMP.USERID = VUSERID AND  TMP.TIP = 1;
    END LOOP;

    FOR V IN (SELECT CMD.CODOBIECT CODOBIECT, SUM( IL.CANT) STINS
              FROM IESPRODLINK IL
                  INNER JOIN CMDPRODMAT CMD ON  IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT
                  INNER JOIN LANSZ1     L1  ON  CMD.CODCOMANDA1  = L1.CODCMD1_VINERI
                  INNER JOIN LANSZ      L   ON  L1.CODLANSZ = L.CODLANSZ
              WHERE COALESCE( L.ANULAT, 0) = 0 AND  L.AN * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, L.An)) + l.saptamana = vAnSet AND  CMD.TIP = 1 AND  L.SUBUNITATEA = vSubunitatea and  cmd.codobiect = vCodObiect
              GROUP BY CMD.CODOBIECT
             )
    LOOP
      UPDATE  TMP_CMDTL TMP
      SET
      RESTA = COALESCE( TMP.RESTA, 0) - V.STINS,
      CANTC = COALESCE( TMP.CANTC, 0) + V.STINS
      WHERE TMP.CODOBIECT = V.CODOBIECT AND  TMP.USERID = VUSERID AND  TMP.TIP = 1;
    END LOOP;

    FOR V IN (SELECT CMD.CODOBIECT CODOBIECT, SUM( IL.CANT) STINS
              FROM IESPRODLINK IL
                  INNER JOIN CMDPRODMAT CMD ON  IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT
                  INNER JOIN LANSZ1     L1  ON  CMD.CODCOMANDA1  = L1.CODCMD1_SAMBATA
                  INNER JOIN LANSZ      L   ON  L1.CODLANSZ = L.CODLANSZ
              WHERE COALESCE( L.ANULAT, 0) = 0 AND  L.AN * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, L.An)) + l.saptamana = vAnSet AND  CMD.TIP = 1 AND  L.SUBUNITATEA = vSubunitatea and  cmd.codobiect = vCodObiect
              GROUP BY CMD.CODOBIECT
             )
    LOOP
      UPDATE  TMP_CMDTL TMP
      SET
      RESTA = COALESCE( TMP.RESTA, 0) - V.STINS,
      CANTC = COALESCE( TMP.CANTC, 0) + V.STINS
      WHERE TMP.CODOBIECT = V.CODOBIECT AND  TMP.USERID = VUSERID AND  TMP.TIP = 1;
    END LOOP;

    FOR V IN (SELECT CMD.CODOBIECT CODOBIECT, SUM( IL.CANT) STINS
              FROM IESPRODLINK IL
                  INNER JOIN CMDPRODMAT CMD ON  IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT
                  INNER JOIN LANSZ1     L1  ON  CMD.CODCOMANDA1  = L1.CODCMD1_DUMINICA
                  INNER JOIN LANSZ      L   ON  L1.CODLANSZ = L.CODLANSZ
              WHERE COALESCE( L.ANULAT, 0) = 0 AND  L.AN * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, L.An)) + l.saptamana = vAnSet AND  CMD.TIP = 1 AND  L.SUBUNITATEA = vSubunitatea and  cmd.codobiect = vCodObiect
              GROUP BY CMD.CODOBIECT
    ) LOOP
      UPDATE  TMP_CMDTL TMP
      SET
      RESTA = COALESCE( TMP.RESTA, 0) - V.STINS,
      CANTC = COALESCE( TMP.CANTC, 0) + V.STINS
      WHERE TMP.CODOBIECT = V.CODOBIECT AND  TMP.USERID = VUSERID AND  TMP.TIP = 1;
    END LOOP;

    FOR V IN (SELECT PNOD.CODOBIECT CODOBIECT, SUM( PNOD.NECESAR) NECESAR
              FROM PLANIFNOD PNOD
                  INNER JOIN PLANIFPROD1 PP1 ON  PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                  INNER JOIN PLANIFPROD  PP  ON  PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
              WHERE PP.An * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, PP.An)) + PP.SAPTAMANA = vNextAnSet and  PP.OPERAT = 1 AND  PP.ANULAT = 0 AND  PP.BLOCAT = 0 and  PNOD.TIP = 3 AND  PP.SUBUNITATEA = vSubunitatea and  PNOD.codobiect = vCodObiect
              GROUP BY PNOD.CODOBIECT
    )
    LOOP
      UPDATE  TMP_CMDTL TMP
      SET
      RESTA = COALESCE( TMP.RESTA, 0) + V.NECESAR,
      CANTA = COALESCE( TMP.CANTA, 0) + V.NECESAR
      WHERE TMP.CODOBIECT = V.CODOBIECT and  TMP.USERID = VUSERID AND  TMP.TIP = 2;

      IF NOT FOUND THEN
        INSERT INTO TMP_CMDTL(CODOBIECT, RESTA, CANTA, USERID, CODCMDTL, TIP)
        VALUES (V.CODOBIECT, V.NECESAR, V.NECESAR, VUSERID, NEXTVAL('SEQ_CMDTL_CODCMDTL'), 2) ;
      END IF;
    END LOOP;

    FOR V IN (SELECT CMD.CODOBIECT CODOBIECT, sum( IL.CANT) STINS
              FROM IESPRODLINK IL
                  INNER JOIN CMDPRODMAT CMD ON  IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT
                  INNER JOIN LANSZ1     L1  ON  CMD.CODCOMANDA1  = L1.CODCMD1_LUNI
                  INNER JOIN LANSZ      L   ON  L1.CODLANSZ = L.CODLANSZ
              WHERE COALESCE( L.ANULAT, 0) = 0 AND  L.AN * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, L.An)) + l.saptamana = vNextAnSet AND  CMD.TIP = 1 AND  L.SUBUNITATEA = vSubunitatea and  cmd.codobiect = vCodObiect
              GROUP BY CMD.CODOBIECT
    )
    LOOP
      UPDATE  TMP_CMDTL TMP
      SET
      RESTA = COALESCE( TMP.RESTA, 0) - V.STINS,
      CANTC = COALESCE( TMP.CANTC, 0) + V.STINS
      WHERE TMP.CODOBIECT = V.CODOBIECT AND  TMP.USERID = VUSERID AND  TMP.TIP = 2;
    END LOOP;

    FOR V IN (SELECT CMD.CODOBIECT CODOBIECT, SUM( IL.CANT) STINS
              FROM IESPRODLINK IL
                  INNER JOIN CMDPRODMAT CMD ON  IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT
                  INNER JOIN LANSZ1     L1  ON  CMD.CODCOMANDA1  = L1.CODCMD1_MARTI
                  INNER JOIN LANSZ      L   ON  L1.CODLANSZ = L.CODLANSZ
              WHERE COALESCE( L.ANULAT, 0) = 0 AND  L.AN * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, L.An)) + l.saptamana = vNextAnSet AND  CMD.TIP = 1 AND  L.SUBUNITATEA = vSubunitatea and  cmd.codobiect = vCodObiect
              GROUP BY CMD.CODOBIECT
    )
    LOOP
      UPDATE  TMP_CMDTL TMP
      SET
      RESTA = COALESCE( TMP.RESTA, 0) - V.STINS,
      CANTC = COALESCE( TMP.CANTC, 0) + V.STINS
      WHERE TMP.CODOBIECT = V.CODOBIECT AND  TMP.USERID = VUSERID AND  TMP.TIP = 2;
    END LOOP;

    FOR V IN (SELECT CMD.CODOBIECT CODOBIECT, SUM( IL.CANT) STINS
              FROM IESPRODLINK IL
                  INNER JOIN CMDPRODMAT CMD ON  IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT
                  INNER JOIN LANSZ1     L1 ON  CMD.CODCOMANDA1 = L1.CODCMD1_MIERCURI
                  INNER JOIN LANSZ      L ON  L1.CODLANSZ = L.CODLANSZ
              WHERE COALESCE( L.ANULAT, 0) = 0 AND  L.AN * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, L.An)) + l.saptamana = vNextAnSet AND  CMD.TIP = 1 AND  L.SUBUNITATEA = vSubunitatea and  cmd.codobiect = vCodObiect
              GROUP BY CMD.CODOBIECT
    )
    LOOP
      UPDATE  TMP_CMDTL TMP
      SET
      RESTA = COALESCE( TMP.RESTA, 0) - V.STINS,
      CANTC = COALESCE( TMP.CANTC, 0) + V.STINS
      WHERE TMP.CODOBIECT = V.CODOBIECT AND  TMP.USERID = VUSERID AND  TMP.TIP = 2;
    END LOOP;

    FOR V IN (
              SELECT CMD.CODOBIECT CODOBIECT, SUM( IL.CANT) STINS
              FROM IESPRODLINK IL
                  INNER JOIN CMDPRODMAT CMD ON  IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT
                  INNER JOIN LANSZ1     L1  ON  CMD.CODCOMANDA1  = L1.CODCMD1_JOI
                  INNER JOIN LANSZ      L   ON  L1.CODLANSZ = L.CODLANSZ
              WHERE COALESCE( L.ANULAT, 0) = 0 AND  L.AN * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, L.An)) + l.saptamana = vNextAnSet AND  CMD.TIP = 1 AND  L.SUBUNITATEA = vSubunitatea and  cmd.codobiect = vCodObiect
              GROUP BY CMD.CODOBIECT
             )
    LOOP
      UPDATE  TMP_CMDTL TMP
      SET
      RESTA = COALESCE( TMP.RESTA, 0) - V.STINS,
      CANTC = COALESCE( TMP.CANTC, 0) + V.STINS
      WHERE TMP.CODOBIECT = V.CODOBIECT AND  TMP.USERID = VUSERID AND  TMP.TIP = 2;
    END LOOP;

    FOR V IN (
              SELECT CMD.CODOBIECT CODOBIECT, SUM( IL.CANT) STINS
              FROM IESPRODLINK IL
                  INNER JOIN CMDPRODMAT CMD ON  IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT
                  INNER JOIN LANSZ1     L1  ON  CMD.CODCOMANDA1  = L1.CODCMD1_VINERI
                  INNER JOIN LANSZ      L   ON  L1.CODLANSZ = L.CODLANSZ
              WHERE COALESCE( L.ANULAT, 0) = 0 AND  L.AN * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, L.An)) + l.saptamana = vNextAnSet AND  CMD.TIP = 1 AND  L.SUBUNITATEA = vSubunitatea and  cmd.codobiect = vCodObiect
              GROUP BY CMD.CODOBIECT
             )
    LOOP
      UPDATE  TMP_CMDTL TMP
      SET
      RESTA = COALESCE( TMP.RESTA, 0) - V.STINS,
      CANTC = COALESCE( TMP.CANTC, 0) + V.STINS
      WHERE TMP.CODOBIECT = V.CODOBIECT AND  TMP.USERID = VUSERID AND  TMP.TIP = 2;
    END LOOP;

    FOR V IN (
              SELECT CMD.CODOBIECT CODOBIECT, SUM( IL.CANT) STINS
              FROM IESPRODLINK IL
                  INNER JOIN CMDPRODMAT CMD ON  IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT
                  INNER JOIN LANSZ1     L1  ON  CMD.CODCOMANDA1  = L1.CODCMD1_SAMBATA
                  INNER JOIN LANSZ      L   ON  L1.CODLANSZ = L.CODLANSZ
              WHERE COALESCE( L.ANULAT, 0) = 0 AND  L.AN * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, L.An)) + l.saptamana = vNextAnSet AND  CMD.TIP = 1 AND  L.SUBUNITATEA = vSubunitatea and  cmd.codobiect = vCodObiect
              GROUP BY CMD.CODOBIECT
             )
    LOOP
      UPDATE  TMP_CMDTL TMP
      SET
      RESTA = COALESCE( TMP.RESTA, 0) - V.STINS,
      CANTC = COALESCE( TMP.CANTC, 0) + V.STINS
      WHERE TMP.CODOBIECT = V.CODOBIECT AND  TMP.USERID = VUSERID AND  TMP.TIP = 2;
    END LOOP;

    FOR V IN (
              SELECT CMD.CODOBIECT CODOBIECT, SUM( IL.CANT) STINS
              FROM IESPRODLINK IL
                  INNER JOIN CMDPRODMAT CMD ON  IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT
                  INNER JOIN LANSZ1     L1  ON  CMD.CODCOMANDA1  = L1.CODCMD1_DUMINICA
                  INNER JOIN LANSZ      L   ON  L1.CODLANSZ = L.CODLANSZ
              WHERE COALESCE( L.ANULAT, 0) = 0 AND  L.AN * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, L.An)) + l.saptamana = vNextAnSet AND  CMD.TIP = 1 AND  L.SUBUNITATEA = vSubunitatea and  cmd.codobiect = vCodObiect
              GROUP BY CMD.CODOBIECT
             )
    LOOP
      UPDATE  TMP_CMDTL TMP
      SET
      RESTA = COALESCE( TMP.RESTA, 0) - V.STINS,
      CANTC = COALESCE( TMP.CANTC, 0) + V.STINS
      WHERE TMP.CODOBIECT = V.CODOBIECT AND  TMP.USERID = VUSERID AND  TMP.TIP = 2;
    END LOOP;
  ELSE
    FOR V IN (
              SELECT PNOD.CODOBIECT CODOBIECT, sum( PNOD.NECESAR) NECESAR
              FROM PLANIFNOD PNOD
                  INNER JOIN PLANIFPROD1 PP1 ON  PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                  INNER JOIN PLANIFPROD  PP  ON  PP.CODPLANIFPROD = PP1.CODPLANIFPROD
              WHERE PP.An * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, PP.An)) + PP.SAPTAMANA = vAnSet and  PP.OPERAT = 1 AND  PP.ANULAT = 0 AND  PP.BLOCAT = 0 and  PNOD.TIP = 3 AND  PP.SUBUNITATEA = vSubunitatea
              GROUP BY PNOD.CODOBIECT
             )
    LOOP
      UPDATE  TMP_CMDTL TMP
      SET RESTA = COALESCE( TMP.RESTA, 0) + V.NECESAR
      WHERE TMP.CODOBIECT = V.CODOBIECT and  TMP.USERID = VUSERID AND  TMP.TIP = 1;

      IF NOT FOUND THEN
        INSERT INTO TMP_CMDTL(CODOBIECT, RESTA, CANTA, USERID, CODCMDTL, TIP)
        VALUES (V.CODOBIECT, V.NECESAR, V.NECESAR, VUSERID, NEXTVAL('SEQ_CMDTL_CODCMDTL'), 1) ;
      END IF;
    END LOOP;

    FOR V IN (
              SELECT CMD.CODOBIECT CODOBIECT, sum( IL.CANT) STINS
              FROM IESPRODLINK IL
                  INNER JOIN CMDPRODMAT CMD ON  IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT
                  INNER JOIN LANSZ1     L1  ON  CMD.CODCOMANDA1  = L1.CODCMD1_LUNI
                  INNER JOIN LANSZ      L  ON  L1.CODLANSZ = L.CODLANSZ
              WHERE COALESCE( L.ANULAT, 0) = 0 AND  L.AN * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, L.An)) + l.saptamana = vAnSet AND  CMD.TIP = 1 AND  L.SUBUNITATEA = vSubunitatea
              GROUP BY CMD.CODOBIECT
             )
    LOOP
      UPDATE  TMP_CMDTL TMP
      SET
      RESTA = COALESCE( TMP.RESTA, 0) - V.STINS,
      CANTC = COALESCE( TMP.CANTC, 0) + V.STINS
      WHERE TMP.CODOBIECT = V.CODOBIECT AND  TMP.USERID = VUSERID AND  TMP.TIP = 1;
    END LOOP;

    FOR V IN (
              SELECT CMD.CODOBIECT CODOBIECT, SUM( IL.CANT) STINS
              FROM IESPRODLINK IL
                  INNER JOIN CMDPRODMAT CMD ON  IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT
                  INNER JOIN LANSZ1     L1  ON  CMD.CODCOMANDA1  = L1.CODCMD1_MARTI
                  INNER JOIN LANSZ      L   ON  L1.CODLANSZ = L.CODLANSZ
              WHERE COALESCE( L.ANULAT, 0) = 0 AND  L.AN * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, L.An)) + l.saptamana = vAnSet AND  CMD.TIP = 1 AND  L.SUBUNITATEA = vSubunitatea
              GROUP BY CMD.CODOBIECT
             )
    LOOP
      UPDATE  TMP_CMDTL TMP
      SET
      RESTA = COALESCE( TMP.RESTA, 0) - V.STINS,
      CANTC = COALESCE( TMP.CANTC, 0) + V.STINS
      WHERE TMP.CODOBIECT = V.CODOBIECT AND  TMP.USERID = VUSERID AND  TMP.TIP = 1;
    END LOOP;

    FOR V IN (
              SELECT CMD.CODOBIECT CODOBIECT, SUM( IL.CANT) STINS
              FROM IESPRODLINK IL
                  INNER JOIN CMDPRODMAT CMD ON  IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT
                  INNER JOIN LANSZ1     L1  ON  CMD.CODCOMANDA1  = L1.CODCMD1_MIERCURI
                  INNER JOIN LANSZ      L   ON  L1.CODLANSZ = L.CODLANSZ
              WHERE COALESCE( L.ANULAT, 0) = 0 AND  L.AN * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, L.An)) + l.saptamana = vAnSet AND  CMD.TIP = 1 AND  L.SUBUNITATEA = vSubunitatea
              GROUP BY CMD.CODOBIECT
             )
    LOOP
      UPDATE  TMP_CMDTL TMP
      SET
      RESTA = COALESCE( TMP.RESTA, 0) - V.STINS,
      CANTC = COALESCE( TMP.CANTC, 0) + V.STINS
      WHERE TMP.CODOBIECT = V.CODOBIECT AND  TMP.USERID = VUSERID AND  TMP.TIP = 1;
    END LOOP;

    FOR V IN (
              SELECT CMD.CODOBIECT CODOBIECT, SUM( IL.CANT) STINS
              FROM IESPRODLINK IL
                  INNER JOIN CMDPRODMAT CMD ON  IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT
                  INNER JOIN LANSZ1     L1  ON  CMD.CODCOMANDA1  = L1.CODCMD1_JOI
                  INNER JOIN LANSZ      L   ON  L1.CODLANSZ = L.CODLANSZ
              WHERE COALESCE( L.ANULAT, 0) = 0 AND  L.AN * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, L.An)) + l.saptamana = vAnSet AND  CMD.TIP = 1 AND  L.SUBUNITATEA = vSubunitatea
              GROUP BY CMD.CODOBIECT
             )
    LOOP
      UPDATE  TMP_CMDTL TMP
      SET
      RESTA = COALESCE( TMP.RESTA, 0) - V.STINS,
      CANTC = COALESCE( TMP.CANTC, 0) + V.STINS
      WHERE TMP.CODOBIECT = V.CODOBIECT AND  TMP.USERID = VUSERID AND  TMP.TIP = 1;
    END LOOP;

    FOR V IN (
              SELECT CMD.CODOBIECT CODOBIECT, SUM( IL.CANT) STINS
              FROM IESPRODLINK IL
                  INNER JOIN CMDPRODMAT CMD ON  IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT
                  INNER JOIN LANSZ1     L1  ON  CMD.CODCOMANDA1  = L1.CODCMD1_VINERI
                  INNER JOIN LANSZ      L   ON  L1.CODLANSZ = L.CODLANSZ
              WHERE COALESCE( L.ANULAT, 0) = 0 AND  L.AN * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, L.An)) + l.saptamana = vAnSet AND  CMD.TIP = 1 AND  L.SUBUNITATEA = vSubunitatea
              GROUP BY CMD.CODOBIECT
             )
    LOOP
      UPDATE  TMP_CMDTL TMP
      SET
      RESTA = COALESCE( TMP.RESTA, 0) - V.STINS,
      CANTC = COALESCE( TMP.CANTC, 0) + V.STINS
      WHERE TMP.CODOBIECT = V.CODOBIECT AND  TMP.USERID = VUSERID AND  TMP.TIP = 1;
    END LOOP;

    FOR V IN (
              SELECT CMD.CODOBIECT CODOBIECT, SUM( IL.CANT) STINS
              FROM IESPRODLINK IL
                  INNER JOIN CMDPRODMAT CMD ON  IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT
                  INNER JOIN LANSZ1     L1  ON  CMD.CODCOMANDA1  = L1.CODCMD1_SAMBATA
                  INNER JOIN LANSZ      L   ON  L1.CODLANSZ = L.CODLANSZ
              WHERE COALESCE( L.ANULAT, 0) = 0 AND  L.AN * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, L.An)) + l.saptamana = vAnSet AND  CMD.TIP = 1 AND  L.SUBUNITATEA = vSubunitatea
              GROUP BY CMD.CODOBIECT
             )
    LOOP
      UPDATE  TMP_CMDTL TMP
      SET
      RESTA = COALESCE( TMP.RESTA, 0) - V.STINS,
      CANTC = COALESCE( TMP.CANTC, 0) + V.STINS
      WHERE TMP.CODOBIECT = V.CODOBIECT AND  TMP.USERID = VUSERID AND  TMP.TIP = 1;
    END LOOP;

    FOR V IN (
              SELECT CMD.CODOBIECT CODOBIECT, SUM( IL.CANT) STINS
              FROM IESPRODLINK IL
                  INNER JOIN CMDPRODMAT CMD ON  IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT
                  INNER JOIN LANSZ1     L1  ON  CMD.CODCOMANDA1  = L1.CODCMD1_DUMINICA
                  INNER JOIN LANSZ      L   ON  L1.CODLANSZ = L.CODLANSZ
              WHERE COALESCE( L.ANULAT, 0) = 0 AND  L.AN * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, L.An)) + l.saptamana = vAnSet AND  CMD.TIP = 1 AND  L.SUBUNITATEA = vSubunitatea
              GROUP BY CMD.CODOBIECT
             )
    LOOP
      UPDATE  TMP_CMDTL TMP
      SET
      RESTA = COALESCE( TMP.RESTA, 0) - V.STINS,
      CANTC = COALESCE( TMP.CANTC, 0) + V.STINS
      WHERE TMP.CODOBIECT = V.CODOBIECT AND  TMP.USERID = VUSERID AND  TMP.TIP = 1;
    END LOOP;

    FOR V IN (
              SELECT PNOD.CODOBIECT CODOBIECT, SUM( PNOD.NECESAR) NECESAR
              FROM PLANIFNOD PNOD
                  INNER JOIN PLANIFPROD1 PP1 ON  PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                  INNER JOIN PLANIFPROD  PP  ON  PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
              WHERE PP.An * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, PP.An)) + PP.SAPTAMANA = vNextAnSet and  PP.OPERAT = 1 AND  PP.ANULAT = 0 AND  PP.BLOCAT = 0 and  PNOD.TIP = 3 AND  PP.SUBUNITATEA = vSubunitatea
              GROUP BY PNOD.CODOBIECT
             )
    LOOP
      UPDATE  TMP_CMDTL TMP
      SET RESTA = COALESCE( TMP.RESTA, 0) + V.NECESAR
      WHERE TMP.CODOBIECT = V.CODOBIECT and  TMP.USERID = VUSERID AND  TMP.TIP = 2;

      IF NOT FOUND THEN
        INSERT INTO TMP_CMDTL(CODOBIECT, RESTA, CANTA, USERID, CODCMDTL, TIP)
        VALUES (V.CODOBIECT, V.NECESAR, V.NECESAR, VUSERID, NEXTVAL('SEQ_CMDTL_CODCMDTL'), 2) ;
      END IF;
    END LOOP;

    FOR V IN (
              SELECT CMD.CODOBIECT CODOBIECT, sum( IL.CANT) STINS
              FROM IESPRODLINK IL
                  INNER JOIN CMDPRODMAT CMD ON  IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT
                  INNER JOIN LANSZ1     L1  ON  CMD.CODCOMANDA1  = L1.CODCMD1_LUNI
                  INNER JOIN LANSZ      L   ON  L1.CODLANSZ = L.CODLANSZ
              WHERE COALESCE( L.ANULAT, 0) = 0 AND  L.AN * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, L.An)) + l.saptamana = vNextAnSet AND  CMD.TIP = 1 AND  L.SUBUNITATEA = vSubunitatea
              GROUP BY CMD.CODOBIECT
             )
    LOOP
      UPDATE  TMP_CMDTL TMP
      SET
      RESTA = COALESCE( TMP.RESTA, 0) - V.STINS,
      CANTC = COALESCE( TMP.CANTC, 0) + V.STINS
      WHERE TMP.CODOBIECT = V.CODOBIECT AND  TMP.USERID = VUSERID AND  TMP.TIP = 2;
    END LOOP;

    FOR V IN (
              SELECT CMD.CODOBIECT CODOBIECT, SUM( IL.CANT) STINS
              FROM IESPRODLINK IL
                  INNER JOIN CMDPRODMAT CMD ON  IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT
                  INNER JOIN LANSZ1     L1  ON  CMD.CODCOMANDA1  = L1.CODCMD1_MARTI
                  INNER JOIN LANSZ      L   ON  L1.CODLANSZ = L.CODLANSZ
              WHERE COALESCE( L.ANULAT, 0) = 0 AND  L.AN * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, L.An)) + l.saptamana = vNextAnSet AND  CMD.TIP = 1 AND  L.SUBUNITATEA = vSubunitatea
              GROUP BY CMD.CODOBIECT
             )
    LOOP
      UPDATE  TMP_CMDTL TMP
      SET
      RESTA = COALESCE( TMP.RESTA, 0) - V.STINS,
      CANTC = COALESCE( TMP.CANTC, 0) + V.STINS
      WHERE TMP.CODOBIECT = V.CODOBIECT AND  TMP.USERID = VUSERID AND  TMP.TIP = 2;
    END LOOP;

    FOR V IN (
              SELECT CMD.CODOBIECT CODOBIECT, SUM( IL.CANT) STINS
              FROM IESPRODLINK IL
                  INNER JOIN CMDPRODMAT CMD ON  IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT
                  INNER JOIN LANSZ1     L1  ON  CMD.CODCOMANDA1  = L1.CODCMD1_MIERCURI
                  INNER JOIN LANSZ      L   ON  L1.CODLANSZ = L.CODLANSZ
              WHERE COALESCE( L.ANULAT, 0) = 0 AND  L.AN * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, L.An)) + l.saptamana = vNextAnSet AND  CMD.TIP = 1 AND  L.SUBUNITATEA = vSubunitatea
              GROUP BY CMD.CODOBIECT
             )
    LOOP
      UPDATE  TMP_CMDTL TMP
      SET
      RESTA = COALESCE( TMP.RESTA, 0) - V.STINS,
      CANTC = COALESCE( TMP.CANTC, 0) + V.STINS
      WHERE TMP.CODOBIECT = V.CODOBIECT AND  TMP.USERID = VUSERID AND  TMP.TIP = 2;
    END LOOP;

    FOR V IN (
              SELECT CMD.CODOBIECT CODOBIECT, SUM( IL.CANT) STINS
              FROM IESPRODLINK IL
                  INNER JOIN CMDPRODMAT CMD ON  IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT
                  INNER JOIN LANSZ1     L1  ON  CMD.CODCOMANDA1  = L1.CODCMD1_JOI
                  INNER JOIN LANSZ      L   ON  L1.CODLANSZ = L.CODLANSZ
              WHERE COALESCE( L.ANULAT, 0) = 0 AND  L.AN * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, L.An)) + l.saptamana = vNextAnSet AND  CMD.TIP = 1 AND  L.SUBUNITATEA = vSubunitatea
              GROUP BY CMD.CODOBIECT
             )
    LOOP
      UPDATE  TMP_CMDTL TMP
      SET
      RESTA = COALESCE( TMP.RESTA, 0) - V.STINS,
      CANTC = COALESCE( TMP.CANTC, 0) + V.STINS
      WHERE TMP.CODOBIECT = V.CODOBIECT AND  TMP.USERID = VUSERID AND  TMP.TIP = 2;
    END LOOP;

    FOR V IN (
              SELECT CMD.CODOBIECT CODOBIECT, SUM( IL.CANT) STINS
              FROM IESPRODLINK IL
                  INNER JOIN CMDPRODMAT CMD ON  IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT
                  INNER JOIN LANSZ1     L1  ON  CMD.CODCOMANDA1  = L1.CODCMD1_VINERI
                  INNER JOIN LANSZ      L   ON  L1.CODLANSZ = L.CODLANSZ
              WHERE COALESCE( L.ANULAT, 0) = 0 AND  L.AN * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, L.An)) + l.saptamana = vNextAnSet AND  CMD.TIP = 1 AND  L.SUBUNITATEA = vSubunitatea
              GROUP BY CMD.CODOBIECT
             )
    LOOP
      UPDATE  TMP_CMDTL TMP
      SET
      RESTA = COALESCE( TMP.RESTA, 0) - V.STINS,
      CANTC = COALESCE( TMP.CANTC, 0) + V.STINS
      WHERE TMP.CODOBIECT = V.CODOBIECT AND  TMP.USERID = VUSERID AND  TMP.TIP = 2;
    END LOOP;

    FOR V IN (
              SELECT CMD.CODOBIECT CODOBIECT, SUM( IL.CANT) STINS
              FROM IESPRODLINK IL
                  INNER JOIN CMDPRODMAT CMD ON  IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT
                  INNER JOIN LANSZ1     L1  ON  CMD.CODCOMANDA1  = L1.CODCMD1_SAMBATA
                  INNER JOIN LANSZ      L   ON  L1.CODLANSZ = L.CODLANSZ
              WHERE COALESCE( L.ANULAT, 0) = 0 AND  L.AN * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, L.An)) + l.saptamana = vNextAnSet AND  CMD.TIP = 1 AND  L.SUBUNITATEA = vSubunitatea
              GROUP BY CMD.CODOBIECT
             )
    LOOP
      UPDATE  TMP_CMDTL TMP
      SET
      RESTA = COALESCE( TMP.RESTA, 0) - V.STINS,
      CANTC = COALESCE( TMP.CANTC, 0) + V.STINS
      WHERE TMP.CODOBIECT = V.CODOBIECT AND  TMP.USERID = VUSERID AND  TMP.TIP = 2;
    END LOOP;

    FOR V IN (
              SELECT CMD.CODOBIECT CODOBIECT, SUM( IL.CANT) STINS
              FROM IESPRODLINK IL
                  INNER JOIN CMDPRODMAT CMD ON  IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT
                  INNER JOIN LANSZ1     L1  ON  CMD.CODCOMANDA1  = L1.CODCMD1_DUMINICA
                  INNER JOIN LANSZ      L   ON  L1.CODLANSZ = L.CODLANSZ
              WHERE COALESCE( L.ANULAT, 0) = 0 AND  L.AN * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, L.An)) + l.saptamana = vNextAnSet AND  CMD.TIP = 1 AND  L.SUBUNITATEA = vSubunitatea
              GROUP BY CMD.CODOBIECT
             )
    LOOP
      UPDATE  TMP_CMDTL TMP
      SET
      RESTA = COALESCE( TMP.RESTA, 0) - V.STINS,
      CANTC = COALESCE( TMP.CANTC, 0) + V.STINS
      WHERE TMP.CODOBIECT = V.CODOBIECT AND  TMP.USERID = VUSERID AND  TMP.TIP = 2;
    END LOOP;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_updatenecesarinstare</obj_name>
  <obj_hashval>2caee517a4d23e2015d578f0fee7945a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_updatenecesarinstare(acodstare1 numeric, anecesar numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  UPDATE stareestimari1     SET necesaracc = aNecesar WHERE codstare1 = aCodStare1;
  UPDATE tmp_stareestimari1 SET necesaracc = aNecesar WHERE codstare1 = aCodStare1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprod_sp_gotorecord</obj_name>
  <obj_hashval>0407c9e9398384679e626315a1143f1f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprod_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCount numeric;
BEGIN
  --Florin 30.12.2020 - user_triggers -&gt; INFORMATION_SCHEMA.TRIGGERS
  --Florin 16.11.2021 - fixat 52001
  perform pkg_planifprod_setct_monitor('MON_45');
  SELECT count(*) INTO aCount
  FROM INFORMATION_SCHEMA.TRIGGERS t INNER JOIN pg_trigger pt ON t.TRIGGER_NAME = pt.TGNAME
  WHERE pt.tgenabled = 'D';

  IF  aCount &gt; 0 THEN
    EXECUTE 'alter table planifnod  enable all triggers';
    EXECUTE 'alter table planifprod enable all triggers';
    EXECUTE 'alter table lansz1     enable all triggers';
  END IF;

  INSERT INTO TMP_PLANIFPROD(CODPLANIFPROD, CODLANSPROD, AN, LUNA, SUBUNITATEA, USERID, DATACREARE, OBS, ANULAT, BLOCAT, OPERAT, SAPTAMANA, DATASTART, DATASTOP, DEN_SUBUNIT, nrdoc, Datadoc, carnetdoc, seriadoc, INSAPTAMANA)
  SELECT P.CODPLANIFPROD, P.CODLANSPROD, P.AN, P.LUNA, P.SUBUNITATEA, P.USERID, P.DATACREARE, P.OBS, P.ANULAT, P.BLOCAT, P.OPERAT, P.SAPTAMANA,
         (SELECT iso_week_to_date.WME_RESULT FROM iso_week_to_date(NULL, p.an, p.saptamana)),
         (SELECT iso_week_to_date.WME_RESULT FROM iso_week_to_date(NULL, p.an, p.saptamana)) + 6,
         S.DEN_SUBUNIT, p.nrdoc, p.datadoc, p.carnetdoc, p.seriadoc, COALESCE( P.INSAPTAMANA, 1)
  FROM PLANIFPROD P INNER JOIN NSUBUNIT S ON  P.SUBUNITATEA = S.CODSUBUNIT
  WHERE P.CodPLANIFPROD = RecId;

  INSERT INTO TMP_PLANIFPROD1(CODPLANIFPROD1, CODPLANIFPROD, CODLANSPROD1, CODOBIECT, CODRETETA, OBS, NECESAR, CANT, DENUMIRE, CODEXTERN, DENUM, CUPROIECT, CODPROIECT, PROIECT, DEN_CLASEAS, DEN_IOART, CODINTERN)
  (
  SELECT P1.CODPLANIFPROD1, P1.CODPLANIFPROD, P1.CODLANSPROD1, P1.CODOBIECT, P1.CODRETETA, P1.OBS, P1.NECESAR, COALESCE( P1.CANT, L1.NECESAR), OBJ.DENUMIRE, OBJ.CODEXTERN, NUM.DEN_UM, COALESCE( P1.CUPROIECT, 0), COALESCE( P1.CODPROIECT, 0), P.VERSIUNE, CLS_AS.DEN_CLASEAS, IOA.DEN_IOART, OBJ.CODINTERN
  FROM PLANIFPROD1 P1
      INNER JOIN NARTOBJ       OBJ    ON  P1.CODOBIECT      = OBJ.CODOBIECT
      INNER JOIN NART          ART    ON  ART.CODARTICOL    = OBJ.CODARTICOL
      INNER JOIN NUM                  ON  ART.UM            = NUM.CODUM
      LEFT  JOIN NCLASEAS      CLS_AS ON  CLS_AS.CODCLASEAS = ART.CLASASTATIST
      LEFT  JOIN LANSPROD1     L1     ON  L1.CODLANSPROD1   = P1.CODLANSPROD1
      LEFT  JOIN PROIECT       P      ON  P.CODPROIECT      = P1.CODPROIECT AND  P1.CUPROIECT = 1
      LEFT  JOIN NARTIMPLICITE IMP    ON  ART.CODARTICOL    = IMP.CODARTICOL AND  IMP.CODSUBUNIT = (SELECT PKG_GLOBALS_GETSUBUNITATE_DOC.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE_DOC(NULL,NULL))
      LEFT  JOIN IOART         IOA    ON  IOA.CODIOART      = COALESCE( IMP.CONTIMPLICIT, 0)
  WHERE CodPLANIFPROD = RecId
  );

  INSERT INTO TMP_PLANIFNOD(CODPLANIFNOD, CODPLANIFPROD, CODPLANIFPROD1, CANT, NECESAR, NODORIGINAL, POZITIE, CODRETETA, TIP, CODOBIECT, DenUM, INDEXPARINTE, CodProdMat, DENUMIRE, OBS, IDENTIFICATOR, DATADOCUMENTATIE, ARHIVA, PROIECTANT, ordine, nivel, codproiectnod, versiune, reteta, CantProdReteta, CantMatReteta, retetaparinte)
  SELECT PN.CODPLANIFNOD, PN.CODPLANIFPROD, PN.CODPLANIFPROD1, PN.CANT, PN.NECESAR, PN.NODORIGINAL, PN.POZITIE, PN.CODRETETA, PN.TIP, PN.CODOBIECT, U.DEN_UM,
         PN.INDEXPARINTE, COALESCE( MAT.CODMAT, 0) CODPRODMAT, OBJ.DENUMIRE, PC.OBS, PC.IDENTIFICATOR, PC.DATADOCUMENTATIE, PC.ARHIVA, PC.PROIECTANT,
         COALESCE( pn.ordine, 0), PN.NIVEL, PN.COdProiectNod, pn.versiune,
         CASE WHEN  COALESCE( p1.cuproiect, 0) = 1 and  COALESCE( pnp.nodoriginal, 0) = 0 THEN p.versiune ELSE pc.obs END ,
         PN.CANTPRODRETETA, PN.CANTMATRETETA,
         CASE WHEN  p1.cuproiect = 1 THEN '' ELSE ' - ' || PCP.Obs || '(' || PCP.Codprodcomp || ')' END
  FROM PLANIFNOD PN
      INNER JOIN NARTOBJ     OBJ ON  PN.CODOBIECT      = OBJ.CODOBIECT
      INNER JOIN NART        A   ON  A.CODARTICOL      = OBJ.CODARTICOL
      INNER JOIN NUM         U   ON  U.CodUM           = A.UM
      INNER JOIN PLANIFPROD1 P1  ON  P1.CODPLANIFPROD1 = PN.CODPLANIFPROD1
      LEFT  JOIN PLANIFNOD   PNP ON  PNP.CODPLANIFNOD  = PN.NODORIGINAL
      LEFT  JOIN PRODCOMP    PC  ON  PN.CodReteta      = PC.CodProdComp
      LEFT  JOIN PRODCOMP    PCP ON  PNP.CodReteta     = PCP.CodProdComp
      LEFT  JOIN PRODMAT     MAT ON  MAT.CODMAT        = PN.CODPRODMAT
      LEFT  JOIN PROIECT     P   ON  P.CODPROIECT      = PN.CODRETETA
  WHERE PN.CODPLANIFPROD = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_umpletabele</obj_name>
  <obj_hashval>300f78f214c9e19875a36dc8ef4b5789</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_umpletabele()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V RECORD;
  vUserID numeric;
  vCurs double precision;
BEGIN
  --Florin current_timestamp -&gt; current_date::varchar
  --Bogdan 14.12.2020
  --Florin 22.01.2021 - fixat 41954
  vUserID := (SELECT PKG_GLOBALS_GETUSERID.WME_RESULT FROM PKG_GLOBALS_GETUSERID (NULL,NULL));
  vCurs   := (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT
              FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA (NULL, COALESCE (TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.vCodMoneda', true)) ,'999999999999999999') , 0) ,
                                                         (fnc_GetValConstantaLucru ('BancaSitV')) ::numeric, to_char (CURRENT_DATE,'dd.mm.yyyy')));
  DELETE FROM TMP_PLUNA WHERE userid = VUSERID;

  IF TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.vAllCls', true)) ,'999999999999999999') &lt;&gt; 1 THEN
    IF TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.vCodCatPret', true)) ,'999999999999999999') &gt; 0 THEN
      IF TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.vCodMoneda', true)) ,'999999999999999999') &gt; 0 THEN
        FOR V IN (SELECT OBJ.CODOBIECT CODOBIECT, PM.MONEDA CODMONEDA,
                         CASE WHEN PM.MONEDA = TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.vCodMoneda', true)) ,'999999999999999999') THEN COALESCE (PM.Valuta, 0)
                              ELSE CASE WHEN PM.LEI IS NULL THEN CASE WHEN vCurs = 0 THEN 0
                                                                      ELSE (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT
                                                                            FROM   PKG_LIST_BASE_UTILS_GETCURSREFERINTA (NULL, COALESCE (PM.moneda, 0) , (fnc_GetValConstantaLucru ('BancaSitV')) ::numeric, to_char (CURRENT_DATE,'dd.mm.yyyy'))
                                                                           ) * COALESCE (PM.VALUTA, 0) / vCurs
                                                                 END
                                        ELSE CASE WHEN vCurs = 0 THEN 0 ELSE PM.VALUTA / vCurs END
                                   END
                         END  PRET
                  FROM NARTOBJ                   OBJ
                    INNER JOIN NART              ART  ON ART.CODARTICOL = OBJ.CODARTICOL
                    INNER JOIN NCLASEA           CLS  ON CLS.CODCLASEA  = ART.CLASA
                    INNER JOIN NCLASEA           CLSA ON INSTRB (CLSA.CODIDENT, CLS.CODIDENT) = 1
                    INNER JOIN TMP_MANEVRA_LISTE      ON FILTRU = 'CODCLASEA' AND CLSA.CODCLASEA = VALOARE::numeric
                    LEFT  JOIN PRETM             PM   ON PM.CODOBIECT = OBJ.CODOBIECT AND PM.CODCATPRET = TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.vCodCatPret', true)) ,'999999999999999999')
                  WHERE OBJ.PRODUSPROPRIU = 2
                  union ALL
                  SELECT OBJ.CODOBIECT CODOBIECT, PM.MONEDA CODMONEDA,
                         CASE WHEN PM.MONEDA = TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.vCodMoneda', true)) ,'999999999999999999') THEN COALESCE (PM.Valuta, 0)
                              ELSE CASE WHEN PM.LEI IS NULL THEN CASE WHEN vCurs = 0 THEN 0
                                                                      ELSE (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT
                                                                            FROM   PKG_LIST_BASE_UTILS_GETCURSREFERINTA (NULL, COALESCE (PM.moneda, 0) , (fnc_GetValConstantaLucru ('BancaSitV')) ::numeric, to_char (CURRENT_DATE,'dd.mm.yyyy'))
                                                                           ) * COALESCE (PM.VALUTA, 0) / vCurs
                                                                 END
                                        ELSE CASE WHEN vCurs = 0 THEN 0 ELSE PM.VALUTA / vCurs END
                                   END
                         END  PRET
                  FROM NARTOBJ      OBJ
                    INNER JOIN NART ART ON ART.CODARTICOL = OBJ.CODARTICOL
                    LEFT JOIN PRETM PM  ON PM.CODOBIECT   = OBJ.CODOBIECT AND PM.CODCATPRET = TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.vCodCatPret', true)) ,'999999999999999999')
                  WHERE
                    OBJ.PRODUSPROPRIU = 2
                    AND COALESCE (ART.CLASA, 0) = 0
                    AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODCLASEA' AND 0 = VALOARE::numeric)
                 )
        LOOP
          INSERT INTO TMP_PLUNA (CODOBIECT, PRET, USERID, CODCMDPL, CODMONEDA)
            VALUES (V.CODOBIECT, V.PRET, VUSERID, NEXTVAL ('SEQ_TMP_PLUNA_CODPLUNA') , V.CODMONEDA);
        END LOOP;
      ELSE
        FOR V IN (SELECT OBJ.CODOBIECT  CODOBIECT, COALESCE (PM.Lei, 0) PRET, PM.MONEDA CODMONEDA
                  FROM NARTOBJ                   OBJ
                    INNER JOIN NART              ART  ON ART.CODARTICOL = OBJ.CODARTICOL
                    INNER JOIN NCLASEA           CLS  ON CLS.CODCLASEA  = ART.CLASA
                    INNER JOIN NCLASEA           CLSA ON INSTRB (CLSA.CODIDENT, CLS.CODIDENT) = 1
                    INNER JOIN TMP_MANEVRA_LISTE      ON FILTRU = 'CODCLASEA' AND CLSA.CODCLASEA = VALOARE::numeric
                    LEFT  JOIN PRETM             PM   ON PM.CODOBIECT = OBJ.CODOBIECT AND PM.CODCATPRET = TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.vCodCatPret', true)) ,'999999999999999999')
                  WHERE OBJ.PRODUSPROPRIU = 2
                  union ALL
                  SELECT OBJ.CODOBIECT CODOBIECT, COALESCE (PM.Lei, 0) PRET, PM.MONEDA CODMONEDA
                  FROM NARTOBJ       OBJ
                    INNER JOIN NART  ART ON ART.CODARTICOL = OBJ.CODARTICOL
                    LEFT JOIN PRETM  PM  ON PM.CODOBIECT   = OBJ.CODOBIECT AND PM.CODCATPRET = TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.vCodCatPret', true)) ,'999999999999999999')
                  WHERE
                    OBJ.PRODUSPROPRIU = 2
                    AND COALESCE (ART.CLASA, 0) = 0
                    AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODCLASEA' AND 0 = VALOARE::numeric))
        LOOP
          INSERT INTO TMP_PLUNA (CODOBIECT, PRET, USERID, CODCMDPL, CODMONEDA)
            VALUES (V.CODOBIECT, V.PRET, VUSERID, NEXTVAL ('SEQ_TMP_PLUNA_CODPLUNA') , V.CODMONEDA);
        END LOOP;
      END IF;
    ELSE
      IF TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.vCodMoneda', true)),'999999999999999999') &gt; 0 THEN
        FOR V IN (SELECT OBJ.CODOBIECT CODOBIECT, PM.MONEDA CODMONEDA,
                         CASE WHEN PM.MONEDA = TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.vCodMoneda', true)) ,'999999999999999999') THEN COALESCE (PM.Valuta, 0)
                              ELSE CASE WHEN PM.LEI IS NULL THEN CASE WHEN vCurs = 0 THEN 0
                                                                      ELSE (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT
                                                                            FROM   PKG_LIST_BASE_UTILS_GETCURSREFERINTA (NULL, COALESCE (PM.moneda, 0) , (fnc_GetValConstantaLucru ('BancaSitV')) ::numeric, to_char (CURRENT_DATE,'dd.mm.yyyy'))
                                                                           ) * COALESCE (PM.VALUTA, 0) / vCurs
                                                                 END
                                        ELSE CASE WHEN vCurs = 0 THEN 0 ELSE PM.VALUTA / vCurs END
                                   END
                         END  PRET
                  FROM NARTOBJ                   OBJ
                    INNER JOIN NART              ART  ON ART.CODARTICOL = OBJ.CODARTICOL
                    INNER JOIN NCLASEA           CLS  ON CLS.CODCLASEA  = ART.CLASA
                    INNER JOIN NCLASEA           CLSA ON INSTRB (CLSA.CODIDENT, CLS.CODIDENT) = 1
                    INNER JOIN TMP_MANEVRA_LISTE      ON FILTRU = 'CODCLASEA' AND CLSA.CODCLASEA = VALOARE::numeric
                    LEFT  JOIN PRETM             PM   ON PM.CODOBIECT = OBJ.CODOBIECT AND PM.IMPLICIT = 1
                  WHERE OBJ.PRODUSPROPRIU = 2
                  union ALL
                  SELECT OBJ.CODOBIECT CODOBIECT, COALESCE (PM.Lei, 0) PRET, PM.MONEDA CODMONEDA
                  FROM NARTOBJ       OBJ
                    INNER JOIN NART  ART ON ART.CODARTICOL = OBJ.CODARTICOL
                    LEFT  JOIN PRETM PM  ON PM.CODOBIECT   = OBJ.CODOBIECT AND PM.CODCATPRET = TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.vCodCatPret', true)) ,'999999999999999999')
                  WHERE
                    OBJ.PRODUSPROPRIU = 2
                    AND COALESCE (ART.CLASA, 0) = 0
                    AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODCLASEA' AND 0 = VALOARE::numeric)
                 )
        LOOP
          INSERT INTO TMP_PLUNA (CODOBIECT, PRET, USERID, CODCMDPL, CODMONEDA)
            VALUES (V.CODOBIECT, V.PRET, VUSERID, NEXTVAL ('SEQ_TMP_PLUNA_CODPLUNA') , V.CODMONEDA);
        END LOOP;
      ELSE
        FOR V IN (SELECT OBJ.CODOBIECT    CODOBIECT, COALESCE (PM.Lei, 0) PRET, PM.MONEDA CODMONEDA
                  FROM NARTOBJ                   OBJ
                    INNER JOIN NART              ART  ON ART.CODARTICOL = OBJ.CODARTICOL
                    INNER JOIN NCLASEA           CLS  ON CLS.CODCLASEA  = ART.CLASA
                    INNER JOIN NCLASEA           CLSA ON INSTRB (CLSA.CODIDENT, CLS.CODIDENT) = 1
                    INNER JOIN TMP_MANEVRA_LISTE      ON FILTRU = 'CODCLASEA' AND CLSA.CODCLASEA = VALOARE::numeric
                    LEFT  JOIN PRETM             PM   ON PM.CODOBIECT = OBJ.CODOBIECT AND PM.IMPLICIT = 1
                  WHERE OBJ.PRODUSPROPRIU = 2
                  union ALL
                  SELECT OBJ.CODOBIECT CODOBIECT, COALESCE (PM.Lei, 0) PRET, PM.MONEDA CODMONEDA
                  FROM NARTOBJ       OBJ
                    INNER JOIN NART  ART ON ART.CODARTICOL = OBJ.CODARTICOL
                    LEFT JOIN PRETM  PM  ON PM.CODOBIECT = OBJ.CODOBIECT AND PM.CODCATPRET = TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.vCodCatPret', true)) ,'999999999999999999')
                  WHERE
                    OBJ.PRODUSPROPRIU = 2
                    AND COALESCE (ART.CLASA, 0) = 0
                    AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODCLASEA' AND 0 = VALOARE::numeric)
                 )
        LOOP
          INSERT INTO TMP_PLUNA (CODOBIECT, PRET, USERID, CODCMDPL, CODMONEDA)
            VALUES (V.CODOBIECT, V.PRET, VUSERID, NEXTVAL ('SEQ_TMP_PLUNA_CODPLUNA') , V.CODMONEDA);
        END LOOP;
      END IF;
    END IF;
  ELSE
    IF TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.vCodCatPret', true)),'999999999999999999') &gt; 0 THEN
      IF TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.vCodMoneda', true)),'999999999999999999') &gt; 0 THEN
        FOR V IN (SELECT OBJ.CODOBIECT CODOBIECT, PM.MONEDA CODMONEDA,
                         CASE WHEN PM.MONEDA = TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.vCodMoneda', true)) ,'999999999999999999') THEN COALESCE (PM.Valuta, 0)
                              ELSE CASE WHEN PM.LEI IS NULL THEN CASE WHEN vCurs = 0 THEN 0
                                                                      ELSE (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT
                                                                            FROM   PKG_LIST_BASE_UTILS_GETCURSREFERINTA (NULL, COALESCE (PM.moneda, 0) , (fnc_GetValConstantaLucru ('BancaSitV')) ::numeric, to_char (CURRENT_DATE,'dd.mm.yyyy'))
                                                                           ) * COALESCE (PM.VALUTA, 0) / vCurs
                                                                 END
                                        ELSE CASE WHEN vCurs = 0 THEN 0 ELSE PM.VALUTA / vCurs END
                                   END
                         END  PRET
                  FROM NARTOBJ OBJ
                    LEFT JOIN PRETM PM ON PM.CODOBIECT = OBJ.CODOBIECT AND PM.CODCATPRET = TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.vCodCatPret', true)) ,'999999999999999999')
                  WHERE OBJ.PRODUSPROPRIU = 2
                 )
        LOOP
          INSERT INTO TMP_PLUNA (CODOBIECT, PRET, USERID, CODCMDPL, CODMONEDA)
            VALUES (V.CODOBIECT, V.PRET, VUSERID, NEXTVAL ('SEQ_TMP_PLUNA_CODPLUNA') , V.CODMONEDA);
        END LOOP;
      ELSE
        FOR V IN (SELECT OBJ.CODOBIECT CODOBIECT, COALESCE (PM.Lei, 0) PRET, PM.MONEDA CODMONEDA
                  FROM NARTOBJ OBJ
                      LEFT JOIN PRETM PM ON PM.CODOBIECT = OBJ.CODOBIECT AND PM.CODCATPRET = TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.vCodCatPret', true)) ,'999999999999999999')
                  WHERE OBJ.PRODUSPROPRIU = 2
                 )
        LOOP
          INSERT INTO TMP_PLUNA (CODOBIECT, PRET, USERID, CODCMDPL, CODMONEDA)
            VALUES (V.CODOBIECT, V.PRET, VUSERID, NEXTVAL ('SEQ_TMP_PLUNA_CODPLUNA') , V.CODMONEDA);
        END LOOP;
      END IF;
    ELSE
      IF TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.vCodMoneda', true)),'999999999999999999') &gt; 0 THEN
        FOR V IN (SELECT OBJ.CODOBIECT CODOBIECT, PM.MONEDA CODMONEDA,
                         CASE WHEN PM.MONEDA = TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.vCodMoneda', true)) ,'999999999999999999') THEN COALESCE (PM.Valuta, 0)
                              ELSE CASE WHEN PM.LEI IS NULL THEN CASE WHEN vCurs = 0 THEN 0
                                                                      ELSE (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT
                                                                            FROM   PKG_LIST_BASE_UTILS_GETCURSREFERINTA (NULL, COALESCE (PM.moneda, 0) , (fnc_GetValConstantaLucru ('BancaSitV')) ::numeric, to_char (CURRENT_DATE,'dd.mm.yyyy'))
                                                                           ) * COALESCE (PM.VALUTA, 0) / vCurs
                                                                 END
                                        ELSE CASE WHEN vCurs = 0 THEN 0 ELSE PM.VALUTA / vCurs END
                                   END
                         END PRET
                  FROM NARTOBJ OBJ LEFT JOIN PRETM PM ON PM.CODOBIECT = OBJ.CODOBIECT AND PM.IMPLICIT = 1
                  WHERE OBJ.PRODUSPROPRIU = 2
                 )
        LOOP
          INSERT INTO TMP_PLUNA (CODOBIECT, PRET, USERID, CODCMDPL, CODMONEDA)
            VALUES (V.CODOBIECT, V.PRET, VUSERID, NEXTVAL ('SEQ_TMP_PLUNA_CODPLUNA') , V.CODMONEDA);
        END LOOP;
      ELSE
        FOR V IN (SELECT OBJ.CODOBIECT CODOBIECT, COALESCE (PM.Lei, 0) PRET, PM.MONEDA CODMONEDA
                  FROM NARTOBJ OBJ LEFT JOIN PRETM PM ON PM.CODOBIECT = OBJ.CODOBIECT AND PM.IMPLICIT = 1
                  WHERE OBJ.PRODUSPROPRIU = 2)
        LOOP
          INSERT INTO TMP_PLUNA (CODOBIECT, PRET, USERID, CODCMDPL, CODMONEDA)
            VALUES (V.CODOBIECT, V.PRET, VUSERID, NEXTVAL ('SEQ_TMP_PLUNA_CODPLUNA') , V.CODMONEDA);
        END LOOP;
      END IF;
    END IF;
  END IF;

  FOR V IN (SELECT P.CODOBIECT CODOBIECT, SUM (NS.REST) REST
            FROM TMP_PLUNA              P
              INNER JOIN NIRSTOC        NS        ON NS.CODOBIECT = P.CODOBIECT
              INNER JOIN NIR                      ON NS.CODNIR    = NIR.CODNIR
              INNER JOIN NGEST          G         ON G.CODGEST    = NIR.GEST
              INNER JOIN TMP_IOART_LUNA IOLUNA    ON IOLUNA.CODIOART = NS.CODIOART
            WHERE
              NS.REST &gt; 0
              AND IOLUNA.MG &lt;&gt; 5
              AND (TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.VALLGEST', true)) ,'999999999999999999') = 1
                    OR
                   EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODGEST' AND VALOARE::numeric = NIR.GEST)
                  )
              AND (TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.VALLIOART', true)) ,'999999999999999999') = 1
                    OR
                   EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODIOART' AND VALOARE::numeric = IOLUNA.CODIOART)
                  )
              AND G.CODSUBUNIT = (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE (NULL,NULL))
              AND P.USERID = VUSERID
            GROUP BY P.CODOBIECT
            )
  LOOP
    UPDATE TMP_PLUNA SET STOC = V.REST WHERE CODOBIECT = V.CODOBIECT and USERID = VUSERID;
  END LOOP;

  PERFORM PKG_PLANIFPRODLUN_UMPLE_TMP_CMD();

  FOR V IN (SELECT P.CODOBIECT CODOBIECT, SUM (COALESCE (P.CANT3, 0)) CANTCC FROM TMP_CMD_PLUNA P
            WHERE P.TIP = 18 AND COALESCE (P.CANT3, 0) &gt; 0 AND P.USERID = VUSERID
            GROUP BY P.CODOBIECT)
  LOOP
    UPDATE TMP_PLUNA SET CANTCC = V.CANTCC WHERE CODOBIECT = V.CODOBIECT and USERID = VUSERID;
  END LOOP;

  FOR V IN (SELECT P.CODOBIECT CODOBIECT, SUM (P.CANT3) CANTCI FROM TMP_CMD_PLUNA P
            WHERE P.TIP = 53 AND P.CANT3 &gt; 0 AND P.USERID = VUSERID
            GROUP BY P.CODOBIECT)
  LOOP
    UPDATE TMP_PLUNA SET CANTCI = V.CANTCI WHERE CODOBIECT = V.CODOBIECT and USERID = VUSERID;
  END LOOP;

  FOR V IN (SELECT P.CODOBIECT CODOBIECT, SUM (P.CANT3) RESTCMDINT FROM TMP_CMD_PLUNA P
            WHERE P.TIP = 53 AND P.CANT3 &gt; 0 AND P.USERID = VUSERID AND P.CODCOMANDA1 &gt; 0
            GROUP BY P.CODOBIECT)
  LOOP
    UPDATE TMP_PLUNA SET RESTCMDINT = V.RESTCMDINT WHERE CODOBIECT = V.CODOBIECT and USERID = VUSERID;
  END LOOP;

  FOR V IN (SELECT P.CODOBIECT,
                   SUM (CASE WHEN P.WEEK = TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.VSAPTAMANA', true)) ,'999999999999999999')     THEN P.CANT3 ELSE 0 END) WEEK1,
                   SUM (CASE WHEN P.WEEK = TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.VSAPTAMANA', true)) ,'999999999999999999') + 1 THEN P.CANT3 ELSE 0 END) WEEK2,
                   SUM (CASE WHEN P.WEEK = TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.VSAPTAMANA', true)) ,'999999999999999999') + 2 THEN P.CANT3 ELSE 0 END) WEEK3,
                   SUM (CASE WHEN P.WEEK = TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.VSAPTAMANA', true)) ,'999999999999999999') + 3 THEN P.CANT3 ELSE 0 END) WEEK4,
                   SUM (CASE WHEN P.WEEK = TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.VSAPTAMANA', true)) ,'999999999999999999') + 4 THEN P.CANT3 ELSE 0 END) WEEK5,
                   SUM (CASE WHEN P.WEEK = TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.VSAPTAMANA', true)) ,'999999999999999999')     THEN P.CANT1 ELSE 0 END) PRWEEK1,
                   SUM (CASE WHEN P.WEEK = TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.VSAPTAMANA', true)) ,'999999999999999999') + 1 THEN P.CANT1 ELSE 0 END) PRWEEK2,
                   SUM (CASE WHEN P.WEEK = TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.VSAPTAMANA', true)) ,'999999999999999999') + 2 THEN P.CANT1 ELSE 0 END) PRWEEK3,
                   SUM (CASE WHEN P.WEEK = TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.VSAPTAMANA', true)) ,'999999999999999999') + 3 THEN P.CANT1 ELSE 0 END) PRWEEK4,
                   SUM (CASE WHEN P.WEEK = TO_NUMBER ( (current_setting ('PKG_PLANIFPRODLUN.VSAPTAMANA', true)) ,'999999999999999999') + 4 THEN P.CANT1 ELSE 0 END) PRWEEK5,
                   P.USERID
            FROM TMP_CMD_PLUNA P
            WHERE
              P.TIP = 53
              AND P.CANT3 &gt; 0
              AND P.USERID = VUSERID
              AND P.CODPROGRAMF1 &gt; 0
            GROUP BY
              P.CODOBIECT, P.USERID)
  LOOP
    UPDATE TMP_PLUNA
    SET
      WEEK1   = V.WEEK1,
      WEEK2   = V.WEEK2,
      WEEK3   = V.WEEK3,
      WEEK4   = V.WEEK4,
      WEEK5   = V.WEEK5,
      PRWEEK1 = V.PRWEEK1,
      PRWEEK2 = V.PRWEEK2,
      PRWEEK3 = V.PRWEEK3,
      PRWEEK4 = V.PRWEEK4,
      PRWEEK5 = V.PRWEEK5
    WHERE
      CODOBIECT = V.CODOBIECT and USERID = V.USERID;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_vallcls</obj_name>
  <obj_hashval>8fcd11a9d223398df5831d5894d3ad61</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_vallcls(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANIFPRODLUN.vAllCls', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_vallgest</obj_name>
  <obj_hashval>0f78f46eb50482ccfbd4b9689b6641f5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_vallgest(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANIFPRODLUN.vAllGest', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_vallioart</obj_name>
  <obj_hashval>2f334c9dcc118ba133771f8a373e64b1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_vallioart(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANIFPRODLUN.vAllIOArt', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plati_setcarnetdoc_i</obj_name>
  <obj_hashval>349d5f43cfcd2947a406af24dace1316</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plati_setcarnetdoc_i(acarnetdoc_i numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLATI.CARNETDOC_I',aCARNETDOC_I::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_g_pmp_valuta</obj_name>
  <obj_hashval>1c866395963c29cebe12d571fc694a9f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_g_pmp_valuta(INOUT wme_result double precision, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PMP.G_PMP_VALUTA', true)),'99999999999.9999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_get_pmp_last_from_var</obj_name>
  <obj_hashval>4a11da8719fa037d1fc5413f58858c00</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_get_pmp_last_from_var(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER((current_setting('PKG_PMP.G_PMP_LAST', true)),'99999999999.9999999');
RETURN;
perform set_config('PKG_PMP.G_PMP_LAST',to_char(-1,'99999999999.9999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_postcalcul_sp_gotorecord</obj_name>
  <obj_hashval>71dc7954cc19bd5c0b32d31ab08bcae6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_postcalcul_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  ANLUNA_START numeric;
  NR           numeric;
  Subunit      numeric;
  AnLuna       numeric;
  aAn          numeric;
  aLuna        numeric;
  TipValMatPC  numeric;
BEGIN
  --Florin 17.06.2025 - sinc. Oracle
  --Bogdan 29.04.2021 - 54055  Postcalcul - ambele tab-uri afisare codintern articole/cod extern articol
    --Florin 30.12.2021 - sinc. Oracle (29.12.2021)
  --Bogdan 16.02.2021
  --Florin 19.01.2021 - inlocuit rownum
  PERFORM PKG_STOC_GENERARE_FACTURI_MAKE_CONFIG_LUNA();
  INSERT INTO TMP_PCALCUL (CODPC, AN, LUNA, SUBUNITATEA, CUMULAT, operat, VARIANTA, DATADOC, TIPPUNCT, OBSERVATII, TipAloc, ValF)
  SELECT CODPC, AN, LUNA, SUBUNITATEA, CUMULAT, operat, VARIANTA, DATADOC, TIPPUNCT, OBSERVATII, COALESCE (TipAloc, 0) , ValF
  FROM PCALCUL WHERE CODPC = RECID;

  SELECT AN * 12 + LUNA, SUBUNITATEA, An, Luna
  INTO AnLuna, Subunit, aAn, aLuna
  FROM PCALCUL WHERE CODPC = RECID;

  TipValMatPC := (fnc_GetValConstantaLucru ('TipValMatPC'))::numeric;

  INSERT INTO TMP_PCGEST (CODPCGEST, CODPC, CODGEST, MANS, PUNCTE, VALi, VALA, ValG, ValC, VALMAT, VALMAN, ValPUNCT, COEFMAN, DENGEST, ValD, ValS, TOTAL, ValMatN)
  SELECT PCG.CODPCGEST, PCG.CODPC, PCG.CODGEST, PCG.ManS, PCG.Puncte, PCG.VALi, PCG.VALa, PCG.ValG, PCG.ValC, PCG.VALMAT, PCG.VALMAN,
         CASE COALESCE (PCG.Puncte, 0) WHEN 0 THEN 0
           ELSE COALESCE ( (COALESCE (PCG.VALi, 0) + COALESCE (PCG.VALA, 0) + COALESCE (PCG.ValG, 0) + COALESCE (PCG.ValC, 0)) , 0) / PCG.Puncte
         END ,
         CASE COALESCE (PCG.MANS, 0) WHEN 0 THEN 0 ELSE COALESCE (PCG.VALMAN, 0) / COALESCE (PCG.MANS, 0) END ,
         CASE PCG.CODGEST WHEN 0 THEN '.TOTAL' ELSE Substr (G.DEN_GEST, 1, 30) END ,
         COALESCE (PCG.VALMAT, 0) + COALESCE (PCG.VALMAN, 0) ,
         COALESCE (PCG.VALi, 0) + COALESCE (PCG.VALA, 0) + COALESCE (PCG.ValG, 0) + COALESCE (PCG.ValC, 0) ,
         COALESCE (PCG.VALMAT, 0) + COALESCE (PCG.VALMAN, 0) + COALESCE (PCG.VALi, 0) + COALESCE (PCG.VALA, 0) + COALESCE (PCG.ValG, 0) + COALESCE (PCG.ValC, 0) ,
         PCG.Valmatn
  FROM PCGEST PCG LEFT JOIN NGEST G ON G.CODGEST = PCG.CODGEST
  WHERE PCG.CODPC = RECID;

  SELECT AN * 12 + LUNA INTO ANLUNA_START FROM TMP_PCALCUL;

  INSERT INTO TMP_PCART (CODPCART, CODPC, CODCMD1, Comanda, DataCmd, CODIOART, CANT, CANTTOT, VAL, VALS, VALi, VALa, ValG, ValC, MAT, CODGEST,
                         CODFORMATIE, COEF, MAN, VALMAN, CODCC, REST, ANLUNA, PUCALC, PretMat, CODOBIECT, PUNCTE, CENTRU,
                         DENOBIECT, DENIOART, DENUM, PRETREFERINTA, PRETRETETA, TIPPRET, OBJ_CODEXTERN, OBJ_CODINTERN,
                         CODCMDPRODMAT, VALLINIE, VALTOT, CONSUM)
  SELECT PCA.CODPCART, PCA.CODPC, PCA.CODCMD1, coalesce (C.Seriadoc,'') || coalesce (C.Nrdoc::varchar ,'') , C.DataDoc, PCA.CODIOART, COALESCE (PCA.CANT, 0) ,
         COALESCE (PCA.CANTTOT, 0) , PCA.VAL, PCA.VALS, PCA.VALi, PCA.VALa, PCA.ValG, ValC, PCA.MAT, PCA.CODGEST, PCA.CODFORMATIE, PCA.COEF, PCA.MAN,
         PCA.VALMAN, PCA.CODCC, MAT.REST, ANLUNA_START - (C.AN * 12 + C.LUNA) ,
         Round ( (CASE WHEN COALESCE (PCA.CANT, 0) = 0 THEN 0
                       ELSE CASE WHEN TipValMatPC = 2 THEN (COALESCE (PCA.MAT, 0) + COALESCE (PCA.MAN, 0) + COALESCE (PCA.VALS, 0)) / COALESCE (PCA.CANT, 0)
                                 ELSE (COALESCE (PCA.VAL, 0) + COALESCE (PCA.MAN, 0) + COALESCE (PCA.VALS, 0)) / COALESCE (PCA.CANT, 0)
                            END
                  END)::numeric, 5),
         Round ( (CASE WHEN COALESCE (PCA.CANT, 0) = 0 THEN 0 ELSE COALESCE (PCA.MAT, 0) / COALESCE (PCA.CANT, 0) END)::numeric, 5),
       C1.CODOBIECT, PCA.PUNCTE, CC.Simbol, OBJ.DENUMIRE, Substr (IOA.DEN_IOART, 1, 50) , Substr (UM.DEN_UM, 1, 15) , OBJ1.PRETREFERINTA, PC.PRET, OBJ1.TIPPRET,
       OBJ.CODEXTERN, OBJ.CODINTERN,
       PCA.CODCMDPRODMAT,
       PCA.VALLINIE,
       PCA.VALTOT,
       C1.CONSUM
  FROM PCART PCA
       LEFT JOIN CMDPRODMAT MAT ON MAT.CODCMDPRODMAT = PCA.CODCMDPRODMAT
       LEFT JOIN COMANDA1 C1 ON MAT.CODCOMANDA1 = C1.CODCOMANDA1
       LEFT JOIN COMANDA  C  ON C.CODCOMANDA = C1.CODCOMANDA
       INNER JOIN PCALCUL PCC ON PCC.CODPC = PCA.CODPC
       LEFT JOIN NGEST G ON G.CODGEST = PCA.CODGEST
       LEFT JOIN CENTRECOST CC ON CC.CODCENTRU = PCA.CODCC
       LEFT JOIN PRODCOMP PC ON PC.CODPRODCOMP = C1.CODRETETA
       LEFT JOIN NARTOBJ OBJ ON OBJ.CODOBIECT = MAT.CODOBIECT
       LEFT JOIN NARTOBJ1 OBJ1 ON OBJ1.CODOBIECT = OBJ.CODOBIECT
       LEFT JOIN NART    ART ON OBJ.CODARTICOL = ART.CODARTICOL
       LEFT JOIN NUM UM ON UM.CODUM = ART.UM
       LEFT JOIN IOART IOA ON PCA.CODIOART = IOA.CODIOART
  WHERE PCA.CODPC = RECID AND PCC.AN*12+PCC.LUNA BETWEEN obj1.alstart AND obj1.alstop
        and (MAT.TIP = 0 and c1.consum = 1 or MAT.tip = 2 and c1.consum = 2);

  INSERT INTO TMP_PCDIR (CODPCDIR, CODPC, CODNEST, CODCMD1, VAL, CODD, CODC, CODCC, CODGEST, CENTRU, DEBIT, CREDIT)
  SELECT PCD.CODPCDIR, PCD.CODPC, PCD.CODNEST, PCD.CODCMD1, PCD.VAL, DEBIT.CODCONT, CREDIT.CODCONT, CC.CODCENTRU,
         NS.CODGEST, CC.Simbol, Substr (DEBIT.SIMBOL, 1, 20) , Substr (CREDIT.SIMBOL, 1, 20)
  FROM PCDIR             PCD
    LEFT JOIN NESTJURNAL NS     ON PCD.CODNEST  = NS.CODNESTJURNAL
    LEFT JOIN NGEST      G      ON G.CODGEST    = NS.CODGEST
    LEFT JOIN CENTRECOST CC     ON CC.CODCENTRU = NS.CODCENTRU
    LEFT JOIN NCONT      DEBIT  ON NS.CODCONTD  = DEBIT.CODCONT
    LEFT JOIN NCONT      CREDIT ON NS.CODCONTC  = CREDIT.CODCONT
  WHERE
    PCD.CODPC = RECID;

  INSERT INTO TMP_PCSECTII (CODPCSECTII, CODPC, CODNEST, VAL, FAZA, CODD, CODC, CODCC, CODGEST, DENGEST, CENTRU, DEBIT, CREDIT)
  SELECT PCS.CODPCSECTII, PCS.CODPC, PCS.CODNEST, PCS.VAL, PCS.FAZA, debit.codcont, CREDIT.CODCONT, NS.CODCENTRU,
         NS.CODGEST, Substr (G.DEN_GEST, 1, 30) , CC.Simbol, Substr (DEBIT.SIMBOL, 1, 20) , Substr (CREDIT.SIMBOL, 1, 20)
  FROM PCSECTII          PCS
    LEFT JOIN NESTJURNAL NS     ON PCS.CODNEST  = NS.CODNESTJURNAL
    LEFT JOIN NGEST      G      ON G.CODGEST    = NS.CODGEST
    LEFT JOIN CENTRECOST CC     ON CC.CODCENTRU = NS.CODCENTRU
    LEFT JOIN NCONT      DEBIT  ON NS.CODCONTD  = DEBIT.CODCONT
    LEFT JOIN NCONT      CREDIT ON NS.CODCONTC  = CREDIT.CODCONT
  WHERE
    PCS.CODPC = RECID and PCS.FAZA = 0;

  INSERT INTO TMP_PCSECTII2 (CODPCSECTII2, CODPC, CODNEST, VAL, FAZA, CODD, CODC, CODCC, CODGEST, DENGEST, CENTRU, DEBIT, CREDIT)
  SELECT PCS.CODPCSECTII, PCS.CODPC, PCS.CODNEST, PCS.VAL, PCS.FAZA, debit.codcont, CREDIT.CODCONT, NS.CODCENTRU,
         NS.CODGEST, Substr (G.DEN_GEST, 1, 30) , CC.Simbol, Substr (DEBIT.SIMBOL, 1, 20) , Substr (CREDIT.SIMBOL, 1, 20)
  FROM PCSECTII          PCS
    LEFT JOIN NESTJURNAL NS     ON PCS.CODNEST  = NS.CODNESTJURNAL
    LEFT JOIN NGEST      G      ON G.CODGEST    = NS.CODGEST
    LEFT JOIN CENTRECOST CC     ON CC.CODCENTRU = NS.CODCENTRU
    LEFT JOIN NCONT      DEBIT  ON NS.CODCONTD  = DEBIT.CODCONT
    LEFT JOIN NCONT      CREDIT ON NS.CODCONTC  = CREDIT.CODCONT
  WHERE
    PCS.CODPC = RECID and PCS.FAZA = 2;

  INSERT INTO TMP_PCSECTII3 (CODPCSECTII3, CODPC, CODNEST, VAL, FAZA, CODD, CODC, CODCC, CODGEST, DENGEST, CENTRU, DEBIT, CREDIT)
  SELECT PCS.CODPCSECTII, PCS.CODPC, PCS.CODNEST, PCS.VAL, PCS.FAZA, debit.codcont, CREDIT.CODCONT, NS.CODCENTRU,
         NS.CODGEST, Substr (G.DEN_GEST, 1, 30) , CC.Simbol, Substr (DEBIT.SIMBOL, 1, 20) , Substr (CREDIT.SIMBOL, 1, 20)
  FROM PCSECTII          PCS
    LEFT JOIN NESTJURNAL NS     ON PCS.CODNEST  = NS.CODNESTJURNAL
    LEFT JOIN NGEST      G      ON G.CODGEST    = NS.CODGEST
    LEFT JOIN CENTRECOST CC     ON CC.CODCENTRU = NS.CODCENTRU
    LEFT JOIN NCONT      DEBIT  ON NS.CODCONTD  = DEBIT.CODCONT
    LEFT JOIN NCONT      CREDIT ON NS.CODCONTC  = CREDIT.CODCONT
  WHERE
    PCS.CODPC = RECID and PCS.FAZA = 3;

  INSERT INTO TMP_PCSECTII4 (CODPCSECTII4, CODPC, CODNEST, VAL, FAZA, CODD, CODC, CODCC, CODGEST, DENGEST, CENTRU, DEBIT, CREDIT)
  SELECT PCS.CODPCSECTII, PCS.CODPC, PCS.CODNEST, PCS.VAL, PCS.FAZA, debit.codcont, CREDIT.CODCONT, NS.CODCENTRU,
         NS.CODGEST, Substr (G.DEN_GEST, 1, 30) , CC.Simbol, Substr (DEBIT.SIMBOL, 1, 20) , Substr (CREDIT.SIMBOL, 1, 20)
  FROM PCSECTII          PCS
    LEFT JOIN NESTJURNAL NS     ON PCS.CODNEST  = NS.CODNESTJURNAL
    LEFT JOIN NGEST      G      ON G.CODGEST    = NS.CODGEST
    LEFT JOIN CENTRECOST CC     ON CC.CODCENTRU = NS.CODCENTRU
    LEFT JOIN NCONT      DEBIT  ON NS.CODCONTD  = DEBIT.CODCONT
    LEFT JOIN NCONT      CREDIT ON NS.CODCONTC  = CREDIT.CODCONT
  WHERE
    PCS.CODPC = RECID and PCS.FAZA = 4;

  INSERT INTO TMP_PCSECTII5 (CODPCSECTII5, CODPC, CODNEST, VAL, FAZA, CODD, CODC, CODCC, CODGEST, DENGEST, CENTRU, DEBIT, CREDIT)
  SELECT PCS.CODPCSECTII, PCS.CODPC, PCS.CODNEST, PCS.VAL, PCS.FAZA, debit.codcont, CREDIT.CODCONT, NS.CODCENTRU,
         NS.CODGEST, Substr (G.DEN_GEST, 1, 30) , CC.Simbol, Substr (DEBIT.SIMBOL, 1, 20) , Substr (CREDIT.SIMBOL, 1, 20)
  FROM PCSECTII          PCS
    LEFT JOIN NESTJURNAL NS     ON PCS.CODNEST  = NS.CODNESTJURNAL
    LEFT JOIN NGEST      G      ON G.CODGEST    = NS.CODGEST
    LEFT JOIN CENTRECOST CC     ON CC.CODCENTRU = NS.CODCENTRU
    LEFT JOIN NCONT      DEBIT  ON NS.CODCONTD  = DEBIT.CODCONT
    LEFT JOIN NCONT      CREDIT ON NS.CODCONTC  = CREDIT.CODCONT
  WHERE
    PCS.CODPC = RECID and PCS.FAZA = 5;

  DELETE FROM TMP_PCFIRMA_BUF;

  INSERT INTO TMP_PCFIRMA_BUF (Codnest, Val)
  SELECT CodNest, Val
  FROM (SELECT Toate.CodNest, Sum (Toate.Val) VAL
        FROM (SELECT (SELECT PKG_Jurnal_GetCodNestJurnal.WME_RESULT
                      FROM PKG_Jurnal_GetCodNestJurnal (NULL,
                                                        (SELECT PKG_JURNAL_GETCONTFORJURNAL.WME_RESULT FROM PKG_JURNAL_GETCONTFORJURNAL (NULL,J.CODDESCRD, J.ICONTD, J.TIPCONTD, '', aAn, aLuna)) ,
                                                        (SELECT PKG_JURNAL_GETCONTFORJURNAL.WME_RESULT FROM PKG_JURNAL_GETCONTFORJURNAL (NULL,J.CODDESCRC, J.ICONTC, J.TIPCONTC, '', aAn, aLuna)) ,
                                                        J.CodGest, J.CodCC)
                     ) CODNEST, J.VAL
              FROM (SELECT x.CodCmd1, x.CODGEST, x.CODCC, x.CODDESCRD, x.ICONTD, x.TIPCONTD, x.CODDESCRC, x.ICONTC, x.TIPCONTC, Sum (x.VAL)  VAL
                    FROM ( (SELECT I.CODBAZAD CODCMD1, I.GEST CODGEST, I.CODCENTRU CODCC, I.CODDESCRD, I.ICONTD, I.TIPCONTD, I.CODDESCRC, I.ICONTC,
                                   I.TIPCONTC, Sum (I.VALOARE * COALESCE (I.IContBazaD, 1)) VAL
                            FROM JURNAL1 I
                            WHERE I.TIPBAZAD = 1200 AND TipDOC &lt;&gt; 71 AND TipDOC &lt;&gt; 72 AND I.An * 12 + I.Luna = AnLuna AND I.SUBUNITATEA = Subunit
                            GROUP BY I.CODBAZAD, I.GEST, I.CODCENTRU, I.CODDESCRD, I.ICONTD, I.TIPCONTD, I.CODDESCRC, I.ICONTC, I.TIPCONTC
                           )
                           union ALL
                           (SELECT I.CODBAZAD CODCMD1, I.GEST CODGEST, I.CODCENTRU CODCC, I.CODDESCRD, I.ICONTD, I.TIPCONTD, I.CODDESCRC, I.ICONTC, I.TIPCONTC, - Sum (I.VALOARE) VAL
                            FROM JURNAL1 I
                            WHERE I.TIPBAZAD = 1200 AND TipDOC = 71 and CODDOC &gt; 0 AND I.An * 12 + I.Luna = AnLuna AND I.SUBUNITATEA = Subunit
                            GROUP BY I.CODBAZAD, I.GEST, I.CODCENTRU, I.CODDESCRD, I.ICONTD, I.TIPCONTD, I.CODDESCRC, I.ICONTC, I.TIPCONTC
                           )
                           union ALL
                           (SELECT I.CODBAZAD CODCMD1, I.GEST CODGEST, I.CODCENTRU CODCC, I.CODDESCRD, I.ICONTD, I.TIPCONTD, I.CODDESCRC, I.ICONTC, I.TIPCONTC, Sum (I.VALOARE) VAL
                            FROM JURNAL1                    I
                            WHERE I.TIPBAZAD = 1200 AND TipDOC = 71 and CODDOC &gt; 0 AND I.An * 12 + I.Luna = AnLuna - 1 AND I.SUBUNITATEA = Subunit
                            GROUP BY I.CODBAZAD, I.GEST, I.CODCENTRU, I.CODDESCRD, I.ICONTD, I.TIPCONTD, I.CODDESCRC, I.ICONTC, I.TIPCONTC
                           )
                           union ALL
                           (SELECT CodCmd1, CODGEST, CODCC, ICODDESCRD CODDESCRD, IICONTD ICONTD, ITIPCONTD TIPCONTD, ICODDESCRC CODDESCRC, IICONTC ICONTC, ITIPCONTC TIPCONTC, VAL
                            FROM (SELECT I.CODBAZAC CODCMD1, I.GEST CODGEST, I.CODCENTRU CODCC, I.CODDESCRD ICODDESCRC,
                                         I.ICONTD IICONTC, I.TIPCONTD ITIPCONTC, I.CODDESCRC ICODDESCRD, I.ICONTC IICONTD,
                                         I.TIPCONTC ITIPCONTD, - Sum (I.VALOARE) VAL
                                  FROM JURNAL1 I
                                  WHERE I.TIPBAZAC = 1200 AND TipDOC = 76 AND I.An * 12 + I.Luna = AnLuna AND I.SUBUNITATEA = Subunit
                                  GROUP BY I.CODBAZAC, I.GEST, I.CODCENTRU, I.CODDESCRD, I.ICONTD, I.TIPCONTD, I.CODDESCRC, I.ICONTC, I.TIPCONTC
                                 ) A_PG
                           )
                         ) x
                    GROUP BY x.CodCmd1, x.CODGEST, x.CODCC, x.CODDESCRD, x.ICONTD, x.TIPCONTD, x.CODDESCRC, x.ICONTC, x.TIPCONTC
                   )   J
                   INNER JOIN Centrecost CC ON CC.CodCentru = J.CodCC
              WHERE COALESCE (CC.TipAloc, 0) = 0
              union ALL
              SELECT Z.CodNest, - Z.Val FROM TMP_PCDir Z     INNER JOIN TMP_PCGEST G ON G.CodGest = Z.CodGest
              union ALL
              SELECT Z.CodNest, - Z.Val FROM TMP_PCSECTII Z  INNER JOIN TMP_PCGEST G ON G.CodGest = Z.CodGest
              union ALL
              SELECT Z.CodNest, - Z.Val FROM TMP_PCSECTII2 Z INNER JOIN TMP_PCGEST G ON G.CodGest = Z.CodGest
              union ALL
              SELECT Z.CodNest, - Z.Val FROM TMP_PCSECTII3 Z INNER JOIN TMP_PCGEST G ON G.CodGest = Z.CodGest
              union ALL
              SELECT Z.CodNest, - Z.Val FROM TMP_PCSECTII5 Z INNER JOIN TMP_PCGEST G ON G.CodGest = Z.CodGest
             ) Toate
      GROUP BY Toate.CodNest) B_PG
  WHERE
    Val &lt;&gt; 0;

  INSERT INTO TMP_PCFIRMA (CODPCFIRMA, VAL, CODCC, CODGEST, DENGEST, CENTRU)
  SELECT row_number() over(), Cen.Val, Cen.CODCENTRU, Cen.CODGEST, Substr (G.DEN_GEST, 1, 30) , CC.Simbol
  FROM (SELECT NS.CODCENTRU, NS.CODGEST, Sum (PCF.VAL) VAL
        FROM TMP_PCFIRMA_BUF PCF LEFT JOIN NESTJURNAL NS ON PCF.CODNEST = NS.CODNESTJURNAL
        GROUP BY NS.CODCENTRU, NS.CODGEST
       ) Cen
    LEFT JOIN NGEST      G  ON G.CODGEST    = Cen.CODGEST
    LEFT JOIN CENTRECOST CC ON CC.CODCENTRU = Cen.CODCENTRU
  WHERE
    Cen.Val &lt;&gt; 0;

  PERFORM pkg_postcalcul_get_pcsectii_1 (ANLuna, Subunit);

  INSERT INTO TMP_JURNAL (SELECT * FROM JURNAL WHERE TIPDOC = 72 AND CODDOC = RECID);

  INSERT INTO TMP_JURNAL1 (SELECT * FROM JURNAL1 WHERE TIPDOC = 72 AND CODDOC = RECID);

  DELETE FROM TMP_RULAJ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_postcalcul_sp_lockrecord</obj_name>
  <obj_hashval>7c2d38774a2d766165c79454fdbda196</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_postcalcul_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodPC INTO Tmp FROM PCALCUL WHERE CODPC = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_postretail_updatepuncteretail</obj_name>
  <obj_hashval>6a8f74f4606e70632691e525ce1396a7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_postretail_updatepuncteretail(acodpart numeric, acodpostretail numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM TOTALPUNCTE WHERE CODPOSTRETAIL = aCODPOSTRETAIL AND  CODPART = aCODPART;
  INSERT INTO TOTALPUNCTE (COD, CODPART, CODPUNCTAJ, PUNCTE, VALOARE, CODPOSTRETAIL)
  SELECT NEXTVAL('SEQ_TOTALPUNCTE_COD'), CODPART, CODPUNCTAJ, PUNCTE, VALOARE, CODPOSTRETAIL FROM TMP_TOTALPUNCTE;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_precomanda_carnetdoc_i</obj_name>
  <obj_hashval>495901ee8aa54515f59cc6948bc172ed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_precomanda_carnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PRECOMANDA.CARNETDOC_I', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_precomanda_sp_insertrecord</obj_name>
  <obj_hashval>34d96b0848a5444d4eba95781a2a6fa3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_precomanda_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_COMANDA(CodComanda) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_predariplus_update_ua</obj_name>
  <obj_hashval>7cdc4b8f387341549d6034b25af21d00</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_predariplus_update_ua(aidinreg numeric, aua character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  UPDATE PREDARIPLUS SET UA = AUA WHERE IDINREG = AIDINREG;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prestatii_sp_deleterecord</obj_name>
  <obj_hashval>b6b764927cbfc11f61b41ae6cba495d0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prestatii_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  PERFORM pkg_prestatii_SP_LOCKRECORD(RecId);
  DELETE FROM PRESTATII WHERE CODPRESTATIE = RecId;
  PERFORM NotifyModif(2, RecId, 'PRESTATII');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prestatii_sp_gotorecord</obj_name>
  <obj_hashval>1945f25852052b7e3d5f2a356328b63a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prestatii_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_PRESTATII
    (
     CODPRESTATIE,
     COD,
     DENUMIRE
     )
  SELECT
     CODPRESTATIE,
     COD,
     DENUMIRE
  FROM PRESTATII
  WHERE CODPRESTATIE = RecId;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_getdatecursorluna</obj_name>
  <obj_hashval>e36f5e0f8db33affb91b86b71fa54644</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_getdatecursorluna()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  PERFORM PKG_PRETPROD_Get_DifPretProdAllSubunit();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_setdirtystructura</obj_name>
  <obj_hashval>22c77f98485f7a2debd33a2bdc570265</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_setdirtystructura()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  aCount numeric;
begin
  SELECT count(*) INTO aCount FROM tmp_manevra;

  DELETE FROM TMP_MANEVRA2;

  WHILE  aCount &gt; 0 LOOP
    FOR v_rec IN (SELECT codunic CODNIRSTOC FROM tmp_manevra) LOOP
      PERFORM PKG_PRETPROD_SetDirtyNirStoc1(v_rec.codnirstoc);
      SELECT count(*) INTO aCount FROM tmp_manevra;
    END LOOP;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_updatenirstoc1inluna</obj_name>
  <obj_hashval>30f9fb78042e31a0643ea26671cf0f14</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_updatenirstoc1inluna()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  Rez numeric;
  Nr  numeric;
BEGIN
  --Adina 14 septembrie 2020 - aranjat
  PERFORM PKG_PRETPROD_GetDateCursorLuna();
  SELECT count(*) INTO nr FROM tmp_balanta_stoc;
  Rez := (SELECT PKG_PRETPROD_UpdatePretNS1Partial.WME_RESULT FROM PKG_PRETPROD_UpdatePretNS1Partial(NULL,nr));
  RETURN Rez;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_updatepreturibycodcomanda1</obj_name>
  <obj_hashval>0e110376d8ebd2a92f5e0f3e414edfd4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_updatepreturibycodcomanda1(acodcomanda1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aPret numeric;
  aFlag boolean;
begin
  DELETE FROM tmp_manevra;
  aFlag := False;
  FOR v_rec IN (SELECT ns1.codnirstocorig, prod.rest
                FROM nirstoc1 ns1 INNER JOIN cmdprodmat prod ON  prod.codcomanda1 = ns1.codcomanda1 and  COALESCE(prod.tip, 0) = 0
                WHERE ns1.codcomanda1 = aCodComanda1
               )
  LOOP
    IF  NOT aFlag THEN
      aFlag := True;
      aPret := (SELECT PKG_PRETPROD_GetPretNirStoc1Mat.WME_RESULT FROM PKG_PRETPROD_GetPretNirStoc1Mat(NULL,v_rec.codnirstocorig,NULL));
    ELSE
      EXIT ;
    END IF;
  END LOOP;

  UPDATE nirstoc1
  SET
  dirty   = 0,
  PretMat = aPret
  WHERE codcomanda1 = aCodComanda1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proc_act_date_setjob</obj_name>
  <obj_hashval>746913a5ed75225fd7a6510c09078791</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proc_act_date_setjob(acodproc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
null;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proc_act_date_sp_deleterecord</obj_name>
  <obj_hashval>c122c5771d97901a17c184e0973c69bd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proc_act_date_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
null;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proc_act_date_sp_gotorecord</obj_name>
  <obj_hashval>d08b66d0cc2c4929c0bb529a58e40da6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proc_act_date_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
null;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_actualizeazapret</obj_name>
  <obj_hashval>ff0f7ce2babb650bf0f68f15ba59e3d9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_actualizeazapret(INOUT wme_result numeric, INOUT acodprodcomp numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
  DECLARE
    V_XXX RECORD;
    V_TMP RECORD;
    V_REC RECORD;
    V_REZ RECORD;
    vPret        numeric;
    aCant        numeric;
    vValMat      numeric;
    vValMan      numeric;
    vValRegie    numeric;
    vValRegieMan numeric;
    mat          numeric;
    man          numeric;
    aCountI      numeric;
    PreturiZero  boolean;
    DinManevra   boolean;
  BEGIN
    --Florin 14.03.2023 - sinc. Oracle (13.03.2023)
    --Laura 26.01.2022 - sinc. Oracle (28.12.2021)
    PERFORM pkg_stoc_generare_facturi_make_config_luna();
    SELECT count(*) INTO aCountI FROM tmp_manevra_liste WHERE filtru = 'CODPRODCOMP';

    DinManevra := aCountI &gt; 0;
    PERFORM PKG_PRODCOMP_ArmeazaTmps (aCodProdComp, DinManevra);
    perform set_config ('PKG_PRODCOMP.KTipPret'         , (fnc_GetValConstantaLucru ('TipEvaluarePret' )) ::varchar, false);
    perform set_config ('PKG_PRODCOMP.KTipCoefIndirecte', (fnc_GetValConstantaLucru ('TipCoefIndirecte')) ::varchar, false);
    perform set_config ('PKG_PRODCOMP.KRegieAntecalcul' , (fnc_GetValConstantaLucru ('RegieAntecalcul' )) ::varchar, false);

    PreturiZero := False;
    IF aCodProdComp = 0 THEN
      FOR v_xxx IN (SELECT pc.codprodcomp, pc.codobiect, COALESCE (pc.tippret, COALESCE (Tmp.tippret, 1)) TIPPRET, obj.denumire,
                           pc.cant, COALESCE (pc.CoefIndirecte, 0) COEFINDIRECTE, pc.tipreteta, tmpp.pret PRETPRODUS
        FROM prodcomp_clona              pcc
          INNER JOIN prodcomp            pc   ON pc.codprodcomp = pcc.codprodcomp
          INNER JOIN nartobj             obj  ON pc.codobiect   = obj.codobiect
          INNER JOIN tmp_nartobj_luna    tmp  ON pc.codobiect   = tmp.codobiect
          LEFT  JOIN tmp_manevra_preturi tmpp ON tmpp.codobiect = pc.codobiect)
      LOOP
        IF v_xxx.tipreteta = 2 THEN
          FOR v_tmp IN (SELECT pm.tu, t1.tarif, pm.codman, CASE WHEN COALESCE (pm.bps, 1) = 0 THEN 1 ELSE COALESCE (pm.bps, 1) END BPS
                        FROM PRODMAN PM
                             LEFT JOIN TARIFEMAN1 T1 ON t1.codtarif = pm.codtarif AND getANLUNALUCRU() BETWEEN T1.ALStart AND T1.ALStop
                        WHERE PM.codprodcomp = v_xxx.CodProdComp
                       )
          LOOP
            UPDATE prodman_clona
            SET valoare_n = round ( ( (v_tmp.tarif * v_tmp.tu) / 60) ::numeric, 7) / v_tmp.BPS
            WHERE
              codman = v_tmp.codman;
          END LOOP;

          DELETE FROM tmp_manevra_liste;

          INSERT INTO tmp_manevra_liste (valoare)
          SELECT codobiect FROM prodcomp WHERE codprodcomp = v_xxx.codprodcomp;

          FOR v_tmp IN (SELECT mat.codmat, mat.codobiect, COALESCE (mat.pret, 0) PRET, COALESCE (mat.tip, 3) TIP, obj.denumire
                        FROM prodmat mat INNER JOIN nartobj obj ON mat.codobiect = obj.codobiect
                        WHERE mat.codprodcomp = v_xxx.codprodcomp
                       )
          LOOP
            INSERT INTO tmp_manevra_liste (valoare)
            SELECT codobiect FROM prodcomp WHERE codprodcomp = v_xxx.codprodcomp;

            IF v_tmp.tip IN (3, 4, 5) THEN
              vValMat   := 0;
              vValMan   := 0;
              vValRegie := 0;
              vPret     := (SELECT PKG_PRODCOMP_GetPretFromStoc.WME_RESULT FROM PKG_PRODCOMP_GetPretFromStoc (NULL,v_tmp.codobiect));
            ELSE
              vValMan   := (SELECT PKG_PRODCOMP_GetValoareMan.WME_RESULT FROM PKG_PRODCOMP_GetValoareMan (NULL,v_tmp.codobiect, current_setting ('PKG_PRODCOMP.KTipPret', true) ::numeric));
              vValMat   := (SELECT PKG_PRODCOMP_GetValoareMat.WME_RESULT FROM PKG_PRODCOMP_GetValoareMat (NULL,v_tmp.codobiect, current_setting ('PKG_PRODCOMP.KTipPret', true) ::numeric));
              vValregie := (SELECT PKG_PRODCOMP_GetRegie.WME_RESULT FROM PKG_PRODCOMP_GetRegie (NULL,v_tmp.codobiect, current_setting ('PKG_PRODCOMP.KTipPret', true) ::numeric));
              vPret     := (SELECT PKG_PRODCOMP_GetPretMaterialCompus.WME_RESULT FROM PKG_PRODCOMP_GetPretMaterialCompus (NULL,v_tmp.codobiect, v_tmp.pret, current_setting ('PKG_PRODCOMP.KTipPret', true) ::numeric));
            END IF;

            UPDATE prodmat_clona
            SET pret_n = vPret, valmat = vValMat, valman = vValMan, valregie = vValRegie
            WHERE
              codmat = v_tmp.codmat;
          END LOOP;

          SELECT cant INTO aCant FROM prodcomp WHERE codprodcomp = v_xxx.CodProdComp;

          vValMat      := v_xxx.cant * COALESCE (v_xxx.pretprodus, 0);
          vValMan      := 0;
          vValRegie    := 0;
          vValRegieMan := 0;
          vPret        := 0;

          FOR v_rec IN (SELECT codprodgest FROM prodgest WHERE codprodcomp = v_xxx.codprodcomp) LOOP
            FOR v_tmp IN (SELECT COALESCE (pg.coefman, COALESCE (ng.coefcheltman, 0)) COEFCHELTMAN, round ( ( (t1.tarif * man.tu) / 60 /
                                 CASE WHEN COALESCE (man.bps, 1) = 0 THEN 1 ELSE COALESCE (man.bps, 1) END) ::numeric, 7)  VALOARE
                          FROM prodman  man
                               INNER JOIN prodgest pg ON man.codprodgest = pg.codprodgest
                               LEFT  JOIN TARIFEMAN1 T1 ON t1.codtarif = man.codtarif AND getANLUNALUCRU() BETWEEN T1.ALStart AND T1.ALStop
                               LEFT  JOIN ngest ng ON ng.codgest = pg.codgest
                          WHERE man.codprodcomp = v_xxx.codprodcomp and pg.codprodgest = v_rec.codprodgest
                         )
            LOOP
              vValMan := vValMan + v_tmp.valoare;
              IF NOT (current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
                  and current_setting ('PKG_PRODCOMP.KRegieAntecalcul' , true) ::numeric = 2)
              THEN
                vValRegie    := vValRegie    + v_tmp.valoare * v_tmp.coefcheltman;
                vValRegieMan := vValRegieMan + v_tmp.valoare * v_tmp.coefcheltman;
              END IF;
            END LOOP;

            FOR v_tmp IN (SELECT mat.codobiect, mat.cant, COALESCE (mat.tip, 3) TIP
                          FROM prodmat          mat
                            INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                            LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                          WHERE
                            mat.codprodcomp = v_xxx.codprodcomp
                            and pg.codprodgest = v_rec.codprodgest
                            and COALESCE (mat.tip, 3) &lt; 3)
            LOOP
              vValMan := vValMan + v_tmp.cant / aCant * (SELECT PKG_PRODCOMP_GetValoareMan.WME_RESULT
                                                         FROM   PKG_PRODCOMP_GetValoareMan (NULL,v_tmp.codobiect, current_setting ('PKG_PRODCOMP.KTipPret', true) ::numeric));
            END LOOP;

            FOR v_tmp IN (SELECT mat.codobiect, COALESCE (pg.coefmat, COALESCE (ng.coefcheltmat, 0)) COEFCHELTMAT, mat.cant, tmpp.pret, COALESCE (mat.tip, 3) TIP
                          FROM prodmat                     mat
                            INNER JOIN prodgest            pg   ON mat.codprodgest = pg.codprodgest
                            LEFT  JOIN tmp_manevra_preturi tmpp ON tmpp.codobiect  = mat.codobiect
                            LEFT  JOIN ngest               ng   ON ng.codgest      = pg.codgest
                          WHERE
                            mat.codprodcomp = v_xxx.codprodcomp
                            and pg.codprodgest = v_rec.codprodgest)
            LOOP
              IF v_tmp.tip IN (3, 4, 5) THEN
                vValMat := vValMat + v_tmp.cant * COALESCE (v_tmp.pret, 0);
                IF NOT (current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
                    and current_setting ('PKG_PRODCOMP.KRegieAntecalcul' , true) ::numeric = 2)
                THEN
                  vValRegie := vValRegie + v_tmp.cant * COALESCE (v_tmp.pret, 0) / acant * v_tmp.coefcheltmat;
                END IF;
              ELSE
                vValMat := vValMat + v_tmp.cant * (SELECT pkg_prodcomp_GetValoareMat.WME_RESULT
                                                   FROM   pkg_prodcomp_GetValoareMat (NULL,v_tmp.codobiect, current_setting ('PKG_PRODCOMP.KTipPret', true) ::numeric));
              END IF;
            END LOOP;

            FOR v_tmp IN (SELECT mat.codobiect, mat.cant, COALESCE (mat.tip, 3) TIP
                          FROM prodmat          mat
                            INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                            LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                          WHERE
                            mat.codprodcomp = v_xxx.codprodcomp
                            and pg.codprodgest = v_rec.codprodgest
                            and COALESCE (mat.tip, 3) &lt; 3)
            LOOP
              vValRegie := vValRegie + v_tmp.cant / aCant * (SELECT pkg_prodcomp_GetRegie.WME_RESULT
                                                             FROM   pkg_prodcomp_GetRegie (NULL,v_tmp.codobiect, current_setting ('PKG_PRODCOMP.KTipPret', true) ::numeric));
            END LOOP;
            vValMat := vValMat / aCant;
          END LOOP;

          IF current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
            and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2 THEN
            vValRegie := vValRegie + v_xxx.CoefIndirecte;
          END IF;

          IF v_xxx.tippret = 1 THEN
            vPret := vPret + vValMat + vValMan + vValRegie;
          ELSE
            vPret := vPret + vValMat;
          END IF;

          FOR v_rez IN (SELECT rez.codrez, rez.cant, totrez.cant TOTAL
                        FROM prodrez rez
                          INNER JOIN (SELECT sum (cant) CANT, codprodcomp FROM prodrez GROUP BY codprodcomp) totrez ON totrez.codprodcomp = rez.codprodcomp
                        WHERE
                          rez.codprodcomp = v_xxx.codprodcomp)
          LOOP
            UPDATE prodrez_clona SET pret_n = vPret / v_rez.total WHERE codrez = v_rez.CodRez;
          END LOOP;

          UPDATE prodcomp_clona
          SET pret_n = v_xxx.pretprodus, valmat = vValMat, valman = vValMan, valregie = vValRegie
          WHERE
            codprodcomp = v_xxx.Codprodcomp;
        ELSE
          FOR v_tmp IN (SELECT pm.tu, t1.tarif, pm.codman, CASE WHEN COALESCE (pm.bps, 1) = 0 THEN 1 ELSE COALESCE (pm.bps, 1) END BPS
                        FROM PRODMAN PM
                             LEFT JOIN TARIFEMAN1 T1 ON t1.codtarif = pm.codtarif AND getANLUNALUCRU() BETWEEN T1.ALStart AND T1.ALStop
                        WHERE PM.codprodcomp = v_xxx.CodProdComp)
          LOOP
            UPDATE prodman_clona
            SET valoare_n = round ( ( (v_tmp.tarif * v_tmp.tu) / 60) ::numeric, 7) / v_tmp.BPS
            WHERE
              codman = v_tmp.codman;
          END LOOP;

          DELETE FROM tmp_manevra_liste;

          INSERT INTO tmp_manevra_liste (valoare)
          SELECT codobiect FROM prodcomp WHERE codprodcomp = v_xxx.codprodcomp;

          FOR v_tmp IN (SELECT mat.codmat, mat.codobiect, COALESCE (mat.pret, 0) PRET, COALESCE (mat.tip, 3) TIP, obj.denumire
                        FROM prodmat mat INNER JOIN nartobj obj ON mat.codobiect = obj.codobiect
                        WHERE mat.codprodcomp = v_xxx.codprodcomp)
          LOOP
            INSERT INTO tmp_manevra_liste (valoare)
            SELECT codobiect FROM prodcomp WHERE codprodcomp = v_xxx.codprodcomp;

            IF v_tmp.tip IN (3, 4, 5) THEN
              vValMat   := 0;
              vValMan   := 0;
              vValRegie := 0;
              vPret     := (SELECT PKG_PRODCOMP_GetPretFromStoc.WME_RESULT FROM PKG_PRODCOMP_GetPretFromStoc (NULL,v_tmp.codobiect));
            ELSE
              vValMan   := (SELECT PKG_PRODCOMP_GetValoareMan.WME_RESULT FROM PKG_PRODCOMP_GetValoareMan (NULL,v_tmp.codobiect, current_setting ('PKG_PRODCOMP.KTipPret', true) ::numeric));
              vValMat   := (SELECT PKG_PRODCOMP_GetValoareMat.WME_RESULT FROM PKG_PRODCOMP_GetValoareMat (NULL,v_tmp.codobiect, current_setting ('PKG_PRODCOMP.KTipPret', true) ::numeric));
              vValregie := (SELECT PKG_PRODCOMP_GetRegie.WME_RESULT FROM PKG_PRODCOMP_GetRegie (NULL,v_tmp.codobiect, current_setting ('PKG_PRODCOMP.KTipPret', true) ::numeric));
              vPret     := (SELECT PKG_PRODCOMP_GetPretMaterialCompus.WME_RESULT FROM PKG_PRODCOMP_GetPretMaterialCompus (NULL,v_tmp.codobiect, v_tmp.pret, current_setting ('PKG_PRODCOMP.KTipPret', true) ::numeric));
            END IF;

            UPDATE prodmat_clona
            SET pret_n = vPret, valmat = vValMat, valman = vValMan, valregie = vValRegie
            WHERE
              codmat = v_tmp.codmat;
          END LOOP;

          SELECT cant INTO aCant FROM prodcomp WHERE codprodcomp = v_xxx.CodProdComp;

          vValMat      := 0;
          vValMan      := 0;
          vValRegie    := 0;
          vValRegieMan := 0;
          vPret        := 0;

          FOR v_rec IN (SELECT codprodgest FROM prodgest WHERE codprodcomp = v_xxx.codprodcomp) LOOP
            FOR v_tmp IN (SELECT COALESCE (pg.coefman, COALESCE (ng.coefcheltman, 0)) COEFCHELTMAN, round ( ( (t1.tarif * man.tu) / 60 /
                                 CASE WHEN COALESCE (man.bps, 1) = 0 THEN 1 ELSE COALESCE (man.bps, 1) END) ::numeric, 7)  VALOARE
                          FROM prodman man
                               INNER JOIN prodgest pg ON man.codprodgest = pg.codprodgest
                               LEFT  JOIN TARIFEMAN1 T1 ON t1.codtarif = man.codtarif AND getANLUNALUCRU() BETWEEN T1.ALStart AND T1.ALStop
                               LEFT  JOIN ngest ng ON ng.codgest = pg.codgest
                          WHERE man.codprodcomp = v_xxx.codprodcomp and pg.codprodgest = v_rec.codprodgest)
            LOOP
              vValMan := vValMan + v_tmp.valoare;
              IF NOT (current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
                  and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2)
              THEN
                vValRegie    := vValRegie    + v_tmp.valoare * v_tmp.coefcheltman;
                vValRegieMan := vValRegieMan + v_tmp.valoare * v_tmp.coefcheltman;
              END IF;
            END LOOP;

            FOR v_tmp IN (SELECT mat.codobiect, mat.cant, COALESCE (mat.tip, 3) TIP
                          FROM prodmat          mat
                            INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                            LEFT JOIN ngest     ng ON ng.codgest = pg.codgest
                          WHERE
                            mat.codprodcomp = v_xxx.codprodcomp
                            and pg.codprodgest = v_rec.codprodgest
                            and COALESCE (mat.tip, 3) &lt; 3)
            LOOP
              vValMan := vValMan + v_tmp.cant / aCant * (SELECT PKG_PRODCOMP_GetValoareMan.WME_RESULT
                                                         FROM   PKG_PRODCOMP_GetValoareMan (NULL,v_tmp.codobiect, current_setting ('PKG_PRODCOMP.KTipPret', true) ::numeric));
            END LOOP;

            FOR v_tmp IN (SELECT mat.codobiect, COALESCE (pg.coefmat, COALESCE (ng.coefcheltmat, 0)) COEFCHELTMAT, mat.cant, tmpp.pret, COALESCE (mat.tip, 3) TIP
                          FROM prodmat                     mat
                            INNER JOIN prodgest            pg   ON mat.codprodgest = pg.codprodgest
                            LEFT  JOIN tmp_manevra_preturi tmpp ON tmpp.codobiect = mat.codobiect
                            LEFT  JOIN ngest               ng   ON ng.codgest = pg.codgest
                          WHERE mat.codprodcomp = v_xxx.codprodcomp and pg.codprodgest = v_rec.codprodgest)
            LOOP
              IF v_tmp.tip IN (3, 4, 5) THEN
                vValMat := vValMat + v_tmp.cant * COALESCE(v_tmp.pret, 0);
                IF NOT (current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
                    and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2)
                THEN
                  vValRegie := vValRegie + v_tmp.cant * v_tmp.pret / acant * v_tmp.coefcheltmat;
                END IF;
              ELSE
                vValMat := vValMat + v_tmp.cant * (SELECT pkg_prodcomp_GetValoareMat.WME_RESULT
                                                   FROM   pkg_prodcomp_GetValoareMat (NULL,v_tmp.codobiect, current_setting ('PKG_PRODCOMP.KTipPret', true) ::numeric));
              END IF;
            END LOOP;

            FOR v_tmp IN (SELECT mat.codobiect, mat.cant, COALESCE (mat.tip, 3) TIP
                          FROM prodmat          mat
                            INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                            LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                          WHERE
                            mat.codprodcomp = v_xxx.codprodcomp
                            and pg.codprodgest = v_rec.codprodgest
                            and COALESCE (mat.tip, 3) &lt; 3)
            LOOP
              vValRegie := vValRegie + v_tmp.cant / aCant * (SELECT pkg_prodcomp_GetRegie.WME_RESULT
                                                             FROM   pkg_prodcomp_GetRegie (NULL,v_tmp.codobiect, current_setting ('PKG_PRODCOMP.KTipPret', true) ::numeric));
            END LOOP;
            vValMat := vValMat / aCant;
          END LOOP;

          IF current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
            and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2 THEN
            vValRegie := vValRegie + v_xxx.CoefIndirecte;
          END IF;

          IF v_xxx.tippret = 1 THEN
            vPret := vPret + vValMat + vValMan + vValRegie;
          ELSE
            vPret := vPret + vValMat;
          END IF;

          UPDATE prodcomp_clona
          SET pret_n = vPret, valmat = vValMat, valman = vValMan, valregie = vValRegie,
            valregieman = vValRegieMan
          WHERE
            codprodcomp = v_xxx.Codprodcomp;
        END IF;
      END LOOP;
    ELSE
      FOR v_xxx IN (SELECT pc.codprodcomp, pc.codobiect, COALESCE (pc.tippret, COALESCE (Tmp.tippret, 1)) TIPPRET, pc.cant,
                           COALESCE (pc.CoefIndirecte, 0) COEFINDIRECTE, pc.tipreteta, tmpp.pret PRETPRODUS
                    FROM prodcomp                    pc
                      INNER JOIN tmp_nartobj_luna    tmp  ON pc.codobiect = tmp.codobiect
                      LEFT  JOIN tmp_manevra_preturi tmpp ON tmpp.codobiect = pc.codobiect
                    WHERE pc.CodProdComp = aCodProdComp)
      LOOP
        IF v_xxx.tipreteta = 2 THEN
          FOR v_tmp IN (SELECT pm.tu, t1.tarif, pm.codman, CASE WHEN COALESCE (pm.bps, 1) = 0 THEN 1 ELSE COALESCE (pm.bps, 1) END BPS
                        FROM PRODMAN PM
                             LEFT JOIN TARIFEMAN1 T1 ON t1.codtarif = pm.codtarif AND getANLUNALUCRU() BETWEEN T1.ALStart AND T1.ALStop
                        WHERE PM.codprodcomp = v_xxx.CodProdComp)
          LOOP
            UPDATE prodman_clona
            SET valoare_n = round ( ( (v_tmp.tarif * v_tmp.tu) / 60) ::numeric, 7) / v_tmp.BPS
            WHERE
              codman = v_tmp.codman;
          END LOOP;

          vPret := 0;
          DELETE FROM tmp_manevra_liste;

          INSERT INTO tmp_manevra_liste (valoare)
          SELECT codobiect FROM prodcomp WHERE codprodcomp = v_xxx.codprodcomp;

          FOR v_tmp IN (SELECT mat.codmat, mat.codobiect, COALESCE (mat.pret, 0) PRET, mat.tip FROM prodmat mat WHERE mat.codprodcomp = v_xxx.codprodcomp) LOOP
            INSERT INTO tmp_manevra_liste (valoare)
            SELECT codobiect FROM prodcomp WHERE codprodcomp = v_xxx.codprodcomp;

            mat       := 0;
            man       := 0;
            vValRegie := 0;

            IF v_tmp.tip IN (3, 4, 5) THEN
              IF v_tmp.tip = 4 THEN
                vPret := 0;
              ELSE
                vPret := (SELECT pkg_prodcomp_GetPretFromStoc.WME_RESULT FROM pkg_prodcomp_GetPretFromStoc (NULL,v_tmp.codobiect));
              END IF;
            ELSE
              IF NOT PreturiZero THEN
                SELECT count (codprodcomp) INTO aCountI
                FROM prodcomp
                WHERE
                  codobiect = v_tmp.codobiect
                  and COALESCE (invizibila, 0) = 0
                  and COALESCE (inactiv, 0) = 0
                  and COALESCE (cant, 0) &gt; 0
                  and COALESCE (pret, 0) = 0;

                IF aCountI &gt; 0 THEN
                  PreturiZero := True;
                END IF;
              END IF;

              SELECT count (codprodcomp) INTO aCountI
              FROM prodcomp
              WHERE
                codobiect = v_tmp.codobiect
                and generic = 1
                and COALESCE (invizibila, 0) = 0
                and COALESCE (inactiv, 0) = 0
                and COALESCE (cant, 0) &gt; 0;

              IF aCountI &gt; 0 THEN
                SELECT sum (pret) / aCountI, sum (valmat) / aCountI, sum (valman) / aCountI, sum (valregie) / aCountI
                INTO vPret, mat, man, vValRegie
                FROM prodcomp
                WHERE
                  codobiect = v_tmp.codobiect
                  and generic = 1
                  and COALESCE (inactiv, 0) = 0
                  and COALESCE (cant, 0) &gt; 0
                  and COALESCE (invizibila, 0) = 0;
              ELSE
                SELECT count (codprodcomp) INTO aCountI
                FROM prodcomp
                WHERE
                  codobiect = v_tmp.codobiect
                  and COALESCE (inactiv, 0) = 0
                  and COALESCE (cant, 0) &gt; 0
                  and COALESCE (invizibila, 0) = 0;

                IF aCountI &gt; 0 THEN
                  SELECT sum (pret) / aCountI, sum (valmat) / aCountI, sum (valman) / aCountI, sum (valregie) / aCountI
                  INTO vPret, mat, man, vValRegie
                  FROM prodcomp
                  WHERE
                    codobiect = v_tmp.codobiect
                    and COALESCE (invizibila, 0) = 0
                    and COALESCE (inactiv, 0) = 0
                    and COALESCE (cant, 0) &gt; 0;
                ELSE
                  vPret := (SELECT pkg_prodcomp_GetPretFromStoc.WME_RESULT FROM pkg_prodcomp_GetPretFromStoc (NULL,v_tmp.codobiect));
                  mat       := 0;
                  man       := 0;
                  vValRegie := 0;
                END IF;
              END IF;
            END IF;

            UPDATE prodmat_clona
            SET pret_n = vPret, valmat = mat, valman = man, valregie = vValRegie
            WHERE
              codmat = v_tmp.codmat;
          END LOOP;

          DELETE FROM tmp_manevra_liste;

          INSERT INTO tmp_manevra_liste (valoare)
          SELECT codobiect FROM prodcomp WHERE codprodcomp = v_xxx.codprodcomp;

          SELECT cant INTO aCant FROM prodcomp WHERE codprodcomp = v_xxx.CodProdComp;

          vValMat   := v_xxx.cant * COALESCE (v_xxx.pretprodus, 0);
          vValMan   := 0;
          vValRegie := 0;
          vPret     := 0;

          FOR v_rec IN (SELECT codprodgest FROM prodgest WHERE codprodcomp = v_xxx.codprodcomp) LOOP
            FOR v_tmp IN (SELECT COALESCE (pg.coefman, COALESCE (ng.coefcheltman, 0)) COEFCHELTMAN,
                                 round ( ( (t1.tarif * man.tu) / 60 / CASE WHEN COALESCE (man.bps, 1) = 0 THEN 1 ELSE COALESCE (man.bps, 1) END) ::numeric, 7)  VALOARE
                          FROM prodman man
                             INNER JOIN prodgest pg ON man.codprodgest = pg.codprodgest
                             LEFT  JOIN TARIFEMAN1 T1 ON t1.codtarif = man.codtarif AND getANLUNALUCRU() BETWEEN T1.ALStart AND T1.ALStop
                             LEFT  JOIN ngest ng ON ng.codgest = pg.codgest
                          WHERE man.codprodcomp = v_xxx.codprodcomp and pg.codprodgest = v_rec.codprodgest)
            LOOP
              vValMan := vValMan + v_tmp.valoare;
              IF NOT (current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
                  and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2)
              THEN
                vValRegie := vValRegie + v_tmp.valoare * v_tmp.coefcheltman;
              END IF;
            END LOOP;

            FOR v_tmp IN (SELECT mat.codobiect, mat.cant, COALESCE (mat.tip, 3) TIP, COALESCE (clona.valman, 0) VALMAN
                          FROM prodmat               mat
                            INNER JOIN prodmat_clona clona ON clona.codmat = mat.codmat
                            INNER JOIN prodgest      pg    ON mat.codprodgest = pg.codprodgest
                            LEFT  JOIN ngest         ng    ON ng.codgest = pg.codgest
                          WHERE
                            mat.codprodcomp = v_xxx.codprodcomp
                            and pg.codprodgest = v_rec.codprodgest
                            and COALESCE (mat.tip, 3) &lt; 3)
            LOOP
              vValMan := vValMan + v_tmp.cant / aCant * v_tmp.valman;
            END LOOP;

            FOR v_tmp IN (SELECT mat.codobiect, COALESCE (pg.coefmat, COALESCE (ng.coefcheltmat, 0)) COEFCHELTMAT, mat.cant, tmpp.pret,
                                 COALESCE (mat.tip, 3) TIP, COALESCE (clona.valmat, 0) VALMAT
                          FROM prodmat                     mat
                            INNER JOIN prodmat_clona       clona ON clona.codmat = mat.codmat
                            INNER JOIN prodgest            pg    ON mat.codprodgest = pg.codprodgest
                            LEFT  JOIN tmp_manevra_preturi tmpp  ON tmpp.codobiect = mat.codobiect
                            LEFT  JOIN ngest               ng    ON ng.codgest = pg.codgest
                          WHERE
                            mat.codprodcomp = v_xxx.codprodcomp
                            and pg.codprodgest = v_rec.codprodgest)
            LOOP
              IF v_tmp.tip IN (3, 4, 5) THEN
                vValMat := vValMat + v_tmp.cant * COALESCE (v_tmp.pret, 0);
                IF NOT (current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
                    and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2)
                THEN
                  vValRegie := vValRegie + v_tmp.cant * COALESCE (v_tmp.pret, 0) / acant * v_tmp.coefcheltmat;
                END IF;
              ELSE
                vValMat := vValMat + v_tmp.cant * v_tmp.valmat;
              END IF;
            END LOOP;

            FOR v_tmp IN (SELECT mat.codobiect, mat.cant, COALESCE (mat.tip, 3) TIP, COALESCE (clona.valregie, 0) VALREGIE
                          FROM prodmat               mat
                            INNER JOIN prodmat_clona clona ON clona.codmat = mat.codmat
                            INNER JOIN prodgest      pg    ON mat.codprodgest = pg.codprodgest
                            LEFT  JOIN ngest         ng    ON ng.codgest = pg.codgest
                          WHERE
                            mat.codprodcomp = v_xxx.codprodcomp
                            and pg.codprodgest = v_rec.codprodgest
                            and COALESCE (mat.tip, 3) &lt; 3)
            LOOP
              vValRegie := vValRegie + v_tmp.cant / acant * v_tmp.valregie;
            END LOOP;
          END LOOP;

          IF current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
            and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2 THEN
            vValRegie := vValRegie + v_xxx.CoefIndirecte;
          END IF;

          IF v_xxx.tippret = 1 THEN
            vPret := vPret + vValMat + vValMan + vValRegie;
          ELSE
            vPret := vPret + vValMat;
          END IF;

          FOR v_rez IN (SELECT rez.codrez, rez.cant, totrez.cant TOTAL
                        FROM prodrez rez
                          INNER JOIN (SELECT sum (cant) CANT, codprodcomp FROM prodrez GROUP BY codprodcomp) totrez ON totrez.codprodcomp = rez.codprodcomp
                        WHERE rez.codprodcomp = v_xxx.codprodcomp)
          LOOP
            UPDATE prodrez_clona
            SET pret_n = vPret / v_rez.total
            WHERE
              codrez = v_rez.CodRez;
          END LOOP;

          UPDATE prodcomp_clona
          SET pret_n = v_xxx.pretprodus, valmat = vValMat, valman = vValMan, valregie = vValRegie
          WHERE
            codprodcomp = v_xxx.Codprodcomp;
        ELSE
          FOR v_tmp IN (SELECT pm.tu, t1.tarif, pm.codman, CASE WHEN COALESCE (pm.bps, 1) = 0 THEN 1 ELSE COALESCE (pm.bps, 1) END BPS
                        FROM PRODMAN PM
                           LEFT JOIN TARIFEMAN1 T1 ON t1.codtarif = pm.codtarif AND getANLUNALUCRU() BETWEEN T1.ALStart AND T1.ALStop
                        WHERE PM.codprodcomp = v_xxx.CodProdComp)
          LOOP
            UPDATE prodman_clona
            SET valoare_n = round ( ( (v_tmp.tarif * v_tmp.tu) / 60) ::numeric, 7) / v_tmp.BPS
            WHERE
              codman = v_tmp.codman;
          END LOOP;

          vPret := 0;
          DELETE FROM tmp_manevra_liste;

          INSERT INTO tmp_manevra_liste (valoare)
          SELECT codobiect FROM prodcomp WHERE codprodcomp = v_xxx.codprodcomp;

          FOR v_tmp IN (SELECT mat.codmat, mat.codobiect, COALESCE (mat.pret, 0) PRET, mat.tip FROM prodmat mat WHERE mat.codprodcomp = v_xxx.codprodcomp) LOOP
            INSERT INTO tmp_manevra_liste (valoare)
            SELECT codobiect FROM prodcomp WHERE codprodcomp = v_xxx.codprodcomp;

            mat       := 0;
            man       := 0;
            vValRegie := 0;

            IF v_tmp.tip IN (3, 4, 5) THEN
              IF v_tmp.tip = 4 THEN
                vPret := 0;
              ELSE
                vPret := (SELECT pkg_prodcomp_GetPretFromStoc.WME_RESULT FROM pkg_prodcomp_GetPretFromStoc (NULL,v_tmp.codobiect));
              END IF;
            ELSE
              IF NOT PreturiZero THEN
                SELECT count (codprodcomp)
                INTO aCountI
                FROM prodcomp
                WHERE
                  codobiect = v_tmp.codobiect
                  and COALESCE (invizibila, 0) = 0
                  and COALESCE (inactiv, 0) = 0
                  and COALESCE (cant, 0) &gt; 0
                  and COALESCE (pret, 0) = 0;

                IF aCountI &gt; 0 THEN
                  PreturiZero := True;
                END IF;
              END IF;

              SELECT count (codprodcomp)
              INTO aCountI
              FROM prodcomp
              WHERE
                codobiect = v_tmp.codobiect
                and generic = 1
                and COALESCE (invizibila, 0) = 0
                and COALESCE (inactiv, 0) = 0
                and COALESCE (cant, 0) &gt; 0;

              IF aCountI &gt; 0 THEN
                SELECT sum (pret) / aCountI, sum (valmat) / aCountI, sum (valman) / aCountI, sum (valregie) / aCountI
                INTO vPret, mat, man, vValRegie
                FROM prodcomp
                WHERE
                  codobiect = v_tmp.codobiect
                  and generic = 1
                  and COALESCE (inactiv, 0) = 0
                  and COALESCE (cant, 0) &gt; 0
                  and COALESCE (invizibila, 0) = 0;
              ELSE
                SELECT count (codprodcomp)
                INTO aCountI
                FROM prodcomp
                WHERE
                  codobiect = v_tmp.codobiect
                  and COALESCE (inactiv, 0) = 0
                  and COALESCE (cant, 0) &gt; 0
                  and COALESCE (invizibila, 0) = 0;

                IF aCountI &gt; 0 THEN
                  SELECT sum (pret) / aCountI, sum (valmat) / aCountI, sum (valman) / aCountI, sum (valregie) / aCountI
                  INTO vPret, mat, man, vValRegie
                  FROM prodcomp
                  WHERE
                    codobiect = v_tmp.codobiect
                    and COALESCE (invizibila, 0) = 0
                    and COALESCE (inactiv, 0) = 0
                    and COALESCE (cant, 0) &gt; 0;
                ELSE
                  vPret := (SELECT pkg_prodcomp_GetPretFromStoc.WME_RESULT FROM pkg_prodcomp_GetPretFromStoc (NULL,v_tmp.codobiect));
                  mat       := 0;
                  man       := 0;
                  vValRegie := 0;
                END IF;
              END IF;
            END IF;

            UPDATE prodmat_clona
            SET pret_n = vPret, valmat = mat, valman = man, valregie = vValRegie
            WHERE
              codmat = v_tmp.codmat;
          END LOOP;

          DELETE FROM tmp_manevra_liste;

          INSERT INTO tmp_manevra_liste (valoare)
          SELECT codobiect FROM prodcomp WHERE codprodcomp = v_xxx.codprodcomp;

          SELECT cant INTO aCant FROM prodcomp WHERE codprodcomp = v_xxx.CodProdComp;

          vValMat      := 0;
          vValMan      := 0;
          vValRegie    := 0;
          vValRegieMan := 0;
          vPret        := 0;

          FOR v_rec IN (SELECT codprodgest FROM prodgest WHERE codprodcomp = v_xxx.codprodcomp) LOOP
            FOR v_tmp IN (SELECT COALESCE (pg.coefman, COALESCE (ng.coefcheltman, 0)) COEFCHELTMAN,
                                 round ( ( (t1.tarif * man.tu) / 60 / CASE WHEN COALESCE (man.bps, 1) = 0 THEN 1 ELSE COALESCE (man.bps, 1) END) ::numeric, 7)  VALOARE
                          FROM prodman man
                             INNER JOIN prodgest pg ON man.codprodgest = pg.codprodgest
                             LEFT  JOIN TARIFEMAN1 T1 ON t1.codtarif = man.codtarif AND getANLUNALUCRU() BETWEEN T1.ALStart AND T1.ALStop
                             LEFT  JOIN ngest ng ON ng.codgest = pg.codgest
                          WHERE man.codprodcomp = v_xxx.codprodcomp and pg.codprodgest = v_rec.codprodgest)
            LOOP
              vValMan := vValMan + v_tmp.valoare;
              IF NOT (current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
                  and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2)
              THEN
                vValRegie    := vValRegie    + v_tmp.valoare * v_tmp.coefcheltman;
                vValRegieMan := vValRegieMan + v_tmp.valoare * v_tmp.coefcheltman;
              END IF;
            END LOOP;

            FOR v_tmp IN (SELECT mat.codobiect, mat.cant, COALESCE (mat.tip, 3) TIP, COALESCE (clona.valman, 0) VALMAN
                          FROM prodmat               mat
                            INNER JOIN prodmat_clona clona ON clona.codmat = mat.codmat
                            INNER JOIN prodgest      pg    ON mat.codprodgest = pg.codprodgest
                            LEFT  JOIN ngest         ng    ON ng.codgest = pg.codgest
                          WHERE
                            mat.codprodcomp = v_xxx.codprodcomp
                            and pg.codprodgest = v_rec.codprodgest
                            and COALESCE (mat.tip, 3) &lt; 3)
            LOOP
              vValMan := vValMan + v_tmp.cant / aCant * v_tmp.valman;
            END LOOP;

            FOR v_tmp IN (SELECT mat.codobiect, COALESCE (pg.coefmat, COALESCE (ng.coefcheltmat, 0)) COEFCHELTMAT, mat.cant, tmpp.pret,
                                 COALESCE (mat.tip, 3) TIP, COALESCE (clona.valmat, 0) VALMAT
                          FROM prodmat                      mat
                            INNER JOIN prodmat_clona        clona ON clona.codmat = mat.codmat
                            INNER JOIN prodgest             pg    ON mat.codprodgest = pg.codprodgest
                            LEFT  JOIN tmp_manevra_preturi  tmpp  ON tmpp.codobiect = mat.codobiect
                            LEFT  JOIN ngest                ng    ON ng.codgest = pg.codgest
                          WHERE
                            mat.codprodcomp = v_xxx.codprodcomp
                            and pg.codprodgest = v_rec.codprodgest)
            LOOP
              IF v_tmp.tip IN (3, 4, 5) THEN
                vValMat := vValMat + v_tmp.cant * v_tmp.pret;
                IF NOT (current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
                    and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2)
                THEN
                  vValRegie := vValRegie + v_tmp.cant * v_tmp.pret / acant * v_tmp.coefcheltmat;
                END IF;
              ELSE
                vValMat := vValMat + v_tmp.cant * v_tmp.valmat;
              END IF;
            END LOOP;

            FOR v_tmp IN (SELECT mat.codobiect, mat.cant, COALESCE (mat.tip, 3) TIP, COALESCE (clona.valregie, 0) VALREGIE
                          FROM prodmat               mat
                            INNER JOIN prodmat_clona clona ON clona.codmat = mat.codmat
                            INNER JOIN prodgest      pg    ON mat.codprodgest = pg.codprodgest
                            LEFT  JOIN ngest         ng    ON ng.codgest = pg.codgest
                          WHERE
                            mat.codprodcomp = v_xxx.codprodcomp
                            and pg.codprodgest = v_rec.codprodgest
                            and COALESCE (mat.tip, 3) &lt; 3)
            LOOP
              vValRegie := vValRegie + v_tmp.cant / acant * v_tmp.valregie;
            END LOOP;
            vValMat := vValMat / aCant;
          END LOOP;

          IF current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
            and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2 THEN
            vValRegie := vValRegie + v_xxx.CoefIndirecte;
          END IF;

          IF v_xxx.tippret = 1 THEN
            vPret := vPret + vValMat + vValMan + vValRegie;
          ELSE
            vPret := vPret + vValMat;
          END IF;

          UPDATE prodcomp_clona
          SET pret_n = vPret, valmat = vValMat, valman = vValMan, valregie = vValRegie,
            valregieman = vValRegieMan
          WHERE
            codprodcomp = v_xxx.Codprodcomp;
        END IF;
      END LOOP;
    END IF;

    IF current_setting ('PKG_PRODCOMP.DoCommit', true) THEN
    END IF;

    IF PreturiZero THEN
      WME_Result := 1;
      RETURN;
    ELSE
      WME_Result := 0;
      RETURN;
    END IF;
  end;
  $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_ct_monitor</obj_name>
  <obj_hashval>70d8dd5b3bb59c342029d54aadb0cd9f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PRODCOMP.CT_MONITOR', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_37';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getregie</obj_name>
  <obj_hashval>8dc4c28a8fefe32ad8e364da88b670c9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getregie(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT tippret numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC1 RECORD;
  V_TMP  RECORD;
  aCount    numeric;
  aCount1   numeric;
  aCount2   numeric;
  aRegie    numeric;
  vValregie numeric;
  RegieMax  numeric;
  RegieMin  numeric;
begin
  --Laura 26.01.2022 - sinc. Oracle (28.12.2021)
  SELECT count (pc.codprodcomp) INTO aCount
  FROM prodcomp_clona pcc INNER JOIN prodcomp pc ON pc.codprodcomp = pcc.codprodcomp
  WHERE pc.codobiect = aCodObiect;

  IF aCount = 0 THEN
    WME_Result := 0;
    RETURN;
  END IF;

  SELECT count (valoare) INTO aCount1 FROM tmp_manevra_liste WHERE valoare::numeric = aCodObiect;

  IF aCount1 = 0 THEN
    INSERT INTO tmp_manevra_liste (valoare) VALUES (aCodObiect);
  ELSE
    aregie := (SELECT PKG_PRODCOMP_GetRegieFromCompusi.WME_RESULT FROM PKG_PRODCOMP_GetRegieFromCompusi (NULL,aCodObiect));
    IF aRegie &gt; 0 THEN
      WME_Result := aregie;
      RETURN;
    END IF;
  END IF;

  SELECT count (pc.codprodcomp) INTO aCount2
  FROM prodcomp_clona pcc INNER JOIN prodcomp pc ON pcc.codprodcomp = pc.codprodcomp
  WHERE pc.codobiect = aCodObiect and pc.generic = 1;

  IF aCount2 &gt; 0 THEN
    aregie := 0;
    FOR v_rec1 IN (SELECT pc.codprodcomp, pc.cant, COALESCE (pc.coefindirecte, 0) COEFINDIRECTE
                   FROM prodcomp_clona pcc INNER JOIN prodcomp pc ON pcc.codprodcomp = pc.codprodcomp
                   WHERE pc.codobiect = aCodObiect and pc.generic = 1)
    LOOP
      vValregie := 0;
      IF NOT (current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
          and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2)
       THEN
        FOR v_tmp IN (SELECT COALESCE (pg.coefman, COALESCE (ng.coefcheltman, 0)) COEFCHELTMAN,
                             round ( ( (t1.tarif * man.tu) / 60 / CASE WHEN COALESCE (man.bps, 1) = 0 THEN 1 ELSE COALESCE (man.bps, 1) END) ::numeric, 7)  VALOARE
          FROM prodman man
            INNER JOIN prodgest pg ON man.codprodgest = pg.codprodgest
            LEFT  JOIN TARIFEMAN1 T1 ON t1.codtarif = man.codtarif AND getANLUNALUCRU() BETWEEN T1.ALStart AND T1.ALStop
            LEFT  JOIN ngest ng ON ng.codgest = pg.codgest
          WHERE
            man.codprodcomp = v_rec1.codprodcomp)
        LOOP
          vValregie := vValregie + v_tmp.valoare * v_tmp.coefcheltman;
        END LOOP;
      END IF;

      IF NOT (current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
          and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2)
       THEN
        FOR v_tmp IN (SELECT mat.codobiect, COALESCE (pg.coefmat, COALESCE (ng.coefcheltmat, 0)) COEFCHELTMAT, mat.cant, COALESCE (tmpp.pret, 0) PRET,
                             COALESCE (mat.tip, 3) TIP
                      FROM prodmat                     mat
                        INNER JOIN prodgest            pg   ON mat.codprodgest = pg.codprodgest
                        LEFT  JOIN tmp_manevra_preturi tmpp ON tmpp.codobiect = mat.codobiect
                        LEFT  JOIN ngest               ng   ON ng.codgest = pg.codgest
                      WHERE
                        mat.codprodcomp = v_rec1.codprodcomp
                        and COALESCE (mat.tip, 3) IN (3, 5))
        LOOP
          vValregie := vValregie + v_tmp.cant * v_tmp.pret / v_rec1.cant * v_tmp.coefcheltmat;
        END LOOP;
      END IF;

      FOR v_tmp IN (SELECT mat.codobiect, mat.cant, COALESCE (mat.tip, 3) TIP
                    FROM prodmat          mat
                      INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                      LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                    WHERE
                      mat.codprodcomp = v_rec1.codprodcomp
                      and COALESCE (mat.tip, 3) &lt; 3)
      LOOP
        vValregie := vValregie + v_tmp.cant / v_Rec1.cant * (SELECT ProcInner.WME_RESULT FROM pkg_prodcomp_GetRegie (NULL,v_tmp.codobiect, TipPret) as ProcInner);
      END LOOP;

      IF current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
        and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2 THEN
        vValregie := vValregie + v_rec1.coefindirecte;
      END IF;
      aregie := aregie + vValregie;
    END LOOP;

    UPDATE tmp_manevra_compusi SET regie = aregie / aCount2 WHERE codobiect = aCodObiect;

    WME_Result := aregie / aCount2;
    RETURN;
  ELSE
    aregie := 0;
    IF TipPret = 1 THEN
      RegieMax := 0;
      FOR v_rec1 IN (SELECT pc.codprodcomp, pc.cant, COALESCE (pc.coefindirecte, 0) COEFINDIRECTE
                     FROM prodcomp pc INNER JOIN prodcomp pcc ON pc.codprodcomp = pcc.codprodcomp
                     WHERE pc.codobiect = aCodObiect)
      LOOP
        vValregie := 0;
        IF NOT (current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
            and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2)
        THEN
          FOR v_tmp IN (SELECT COALESCE (pg.coefman, COALESCE (ng.coefcheltman, 0)) COEFCHELTMAN,
                               round ( ( (t1.tarif * man.tu) / 60 / CASE WHEN COALESCE (man.bps, 1) = 0 THEN 1 ELSE COALESCE (man.bps, 1) END) ::numeric, 7)  VALOARE
                        FROM prodman man
                          INNER JOIN prodgest pg ON man.codprodgest = pg.codprodgest
                          LEFT  JOIN TARIFEMAN1 T1 ON t1.codtarif = man.codtarif AND getANLUNALUCRU() BETWEEN T1.ALStart AND T1.ALStop
                          LEFT  JOIN ngest ng ON ng.codgest = pg.codgest
                        WHERE
                          man.codprodcomp = v_rec1.codprodcomp)
          LOOP
            vValregie := vValregie + v_tmp.valoare * v_tmp.coefcheltman;
          END LOOP;
        END IF;

        IF NOT (current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
            and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2)
        THEN
          FOR v_tmp IN (SELECT mat.codobiect, COALESCE (pg.coefmat, COALESCE (ng.coefcheltmat, 0)) COEFCHELTMAT, mat.cant, COALESCE (tmpp.pret, 0) PRET,
                               COALESCE (mat.tip, 3) TIP
                        FROM prodmat                     mat
                          INNER JOIN prodgest            pg   ON mat.codprodgest = pg.codprodgest
                          LEFT  JOIN tmp_manevra_preturi tmpp ON tmpp.codobiect = mat.codobiect
                          LEFT  JOIN ngest               ng   ON ng.codgest = pg.codgest
                        WHERE
                          mat.codprodcomp = v_rec1.codprodcomp and COALESCE (mat.tip, 3) IN (3, 5))
          LOOP
            vValregie := vValregie + v_tmp.cant * v_tmp.pret / v_rec1.cant * v_tmp.coefcheltmat;
          END LOOP;
        END IF;

        FOR v_tmp IN (SELECT mat.codobiect, mat.cant, COALESCE (mat.tip, 3) TIP
                      FROM prodmat          mat
                        INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                        LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                      WHERE
                        mat.codprodcomp = v_rec1.codprodcomp and COALESCE (mat.tip, 3) &lt; 3)
        LOOP
          vValregie := vValregie + v_tmp.cant / v_Rec1.cant * (SELECT ProcInner.WME_RESULT FROM pkg_prodcomp_GetRegie (NULL,v_tmp.codobiect, TipPret) as ProcInner);
        END LOOP;

        IF current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
          and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2 THEN
          vValregie := vValregie + v_rec1.coefindirecte;
        END IF;
        aregie := vValregie;
        IF aregie &gt; RegieMax THEN
          RegieMax := aregie;
        END IF;
      END LOOP;

      UPDATE tmp_manevra_compusi SET Regie = RegieMax WHERE codobiect = aCodObiect;

      WME_Result := RegieMax;
      RETURN;
    ELSE
      IF TipPret = 3 THEN
        RegieMin := 0;
        FOR v_rec1 IN (SELECT pc.codprodcomp, pc.cant, COALESCE (pc.coefindirecte, 0) COEFINDIRECTE
                       FROM prodcomp pc INNER JOIN prodcomp pcc ON pc.codprodcomp = pcc.codprodcomp
                       WHERE pc.codobiect = aCodObiect)
        LOOP
          vValregie := 0;
          IF NOT (current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
              and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2)
          THEN
            FOR v_tmp IN (SELECT COALESCE (pg.coefman, COALESCE (ng.coefcheltman, 0)) COEFCHELTMAN,
                                 round ( ( (t1.tarif * man.tu) / 60 / CASE WHEN COALESCE (man.bps, 1) = 0 THEN 1 ELSE COALESCE (man.bps, 1) END) ::numeric, 7)  VALOARE
                          FROM prodman man
                            INNER JOIN prodgest pg ON man.codprodgest = pg.codprodgest
                            LEFT  JOIN TARIFEMAN1 T1 ON t1.codtarif = man.codtarif AND getANLUNALUCRU() BETWEEN T1.ALStart AND T1.ALStop
                            LEFT  JOIN ngest ng ON ng.codgest = pg.codgest
                          WHERE
                            man.codprodcomp = v_rec1.codprodcomp)
            LOOP
              vValregie := vValregie + v_tmp.valoare * v_tmp.coefcheltman;
            END LOOP;
          END IF;

          IF NOT (current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
              and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2)
          THEN
            FOR v_tmp IN (SELECT mat.codobiect, COALESCE (pg.coefmat, COALESCE (ng.coefcheltmat, 0)) COEFCHELTMAT, mat.cant, COALESCE (tmpp.pret, 0) PRET,
                                 COALESCE (mat.tip, 3) TIP
                          FROM prodmat                     mat
                            INNER JOIN prodgest            pg   ON mat.codprodgest = pg.codprodgest
                            LEFT  JOIN tmp_manevra_preturi tmpp ON tmpp.codobiect = mat.codobiect
                            LEFT  JOIN ngest               ng   ON ng.codgest = pg.codgest
                          WHERE
                            mat.codprodcomp = v_rec1.codprodcomp and COALESCE (mat.tip, 3) IN (3, 5))
            LOOP
              vValregie := vValregie + v_tmp.cant * v_tmp.pret / v_Rec1.cant * v_tmp.coefcheltmat;
            END LOOP;
          END IF;

          FOR v_tmp IN (SELECT mat.codobiect, mat.cant, COALESCE (mat.tip, 3) TIP
                        FROM prodmat          mat
                          INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                          LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                        WHERE
                          mat.codprodcomp = v_rec1.codprodcomp and COALESCE (mat.tip, 3) &lt; 3)
          LOOP
            vValregie := vValregie + v_tmp.cant / v_rec1.cant * (SELECT ProcInner.WME_RESULT FROM pkg_prodcomp_GetRegie (NULL,v_tmp.codobiect, TipPret) as ProcInner);
          END LOOP;

          aregie := vValregie;
          IF current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
            and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2 THEN
            vValregie := vValregie + v_rec1.coefindirecte;
          END IF;
          IF aregie &lt; RegieMin THEN
            RegieMin := aregie;
          END IF;
        END LOOP;

        UPDATE tmp_manevra_compusi SET Regie = RegieMin WHERE codobiect = aCodObiect;

        WME_Result := RegieMin;
        RETURN;
      ELSE
        aregie := 0;
        FOR v_rec1 IN (SELECT pc.codprodcomp, pc.cant, COALESCE (pc.coefindirecte, 0) COEFINDIRECTE
                       FROM prodcomp_clona pcc INNER JOIN prodcomp pc ON pcc.codprodcomp = pc.codprodcomp
                       WHERE pc.codobiect = aCodObiect)
        LOOP
          vValregie := 0;
          IF NOT (current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
              and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2)
          THEN
            FOR v_tmp IN (SELECT COALESCE (pg.coefman, COALESCE (ng.coefcheltman, 0)) COEFCHELTMAN,
                                 round ( ( (t1.tarif * man.tu) / 60 / CASE WHEN COALESCE (man.bps, 1) = 0 THEN 1 ELSE COALESCE (man.bps, 1) END) ::numeric, 7)  VALOARE
                          FROM prodman  man
                            INNER JOIN prodgest pg ON man.codprodgest = pg.codprodgest
                            LEFT  JOIN TARIFEMAN1 T1 ON t1.codtarif = man.codtarif AND getANLUNALUCRU() BETWEEN T1.ALStart AND T1.ALStop
                            LEFT  JOIN ngest ng ON ng.codgest = pg.codgest
                          WHERE
                            man.codprodcomp = v_rec1.codprodcomp)
            LOOP
              vValregie := vValregie + v_tmp.valoare * v_tmp.coefcheltman;
            END LOOP;
          END IF;

          IF NOT (current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
              and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2)
          THEN
            FOR v_tmp IN (SELECT mat.codobiect, COALESCE (pg.coefmat, COALESCE (ng.coefcheltmat, 0)) COEFCHELTMAT, mat.cant, COALESCE (tmpp.pret, 0) PRET,
                                 COALESCE (mat.tip, 3) TIP
                          FROM prodmat                     mat
                            INNER JOIN prodgest            pg   ON mat.codprodgest = pg.codprodgest
                            LEFT  JOIN tmp_manevra_preturi tmpp ON tmpp.codobiect = mat.codobiect
                            LEFT  JOIN ngest               ng   ON ng.codgest = pg.codgest
                          WHERE
                            mat.codprodcomp = v_rec1.codprodcomp and COALESCE (mat.tip, 3) IN (3, 5))
            LOOP
              vValregie := vValregie + v_tmp.cant * v_tmp.pret / v_Rec1.cant * v_tmp.coefcheltmat;
            END LOOP;
          END IF;

          FOR v_tmp IN (SELECT mat.codobiect, mat.cant, COALESCE (mat.tip, 3) TIP
                        FROM prodmat          mat
                          INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                          LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                        WHERE
                          mat.codprodcomp = v_rec1.codprodcomp and COALESCE (mat.tip, 3) &lt; 3)
          LOOP
            vValregie := vValregie + v_tmp.cant / v_Rec1.cant * (SELECT ProcInner.WME_RESULT FROM pkg_prodcomp_GetRegie (NULL,v_tmp.codobiect, TipPret) as ProcInner);
          END LOOP;

          IF current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
            and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2 THEN
            vValregie := vValregie + v_rec1.coefindirecte;
          END IF;
          aregie := aregie + vValregie;
        END LOOP;

        UPDATE tmp_manevra_compusi SET regie = aregie / aCount WHERE codobiect = aCodObiect;

        WME_Result := aregie / aCount;
        RETURN;
      END IF;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getvallret</obj_name>
  <obj_hashval>aa0a604af3716b64ed62df5ebce74985</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getvallret(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PRODCOMP.vAllRet', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getvcodmat</obj_name>
  <obj_hashval>1c57c60805f85260f5b9c56fed64babb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getvcodmat(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PRODCOMP.vCodMat', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_setkregieantecalcul</obj_name>
  <obj_hashval>8d2d31a4b6912d4d676324f8c8e692d9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_setkregieantecalcul(akregieantecalcul numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PRODCOMP.KRegieAntecalcul',aKRegieAntecalcul::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_setktipcoefindirecte</obj_name>
  <obj_hashval>3ddf4d7f9ac83d8dcfca47bd5cb2d2d1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_setktipcoefindirecte(aktipcoefindirecte numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PRODCOMP.KTipCoefIndirecte',aKTipCoefIndirecte::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_setktippret</obj_name>
  <obj_hashval>38b2342c0746479183311e38c981f48b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_setktippret(aktippret numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PRODCOMP.KTipPret',aKTipPret::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_sp_gotorecord</obj_name>
  <obj_hashval>e9ac389f794308b323fc7fcdd5bf8dfd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  V_TMP        RECORD;
  V_TMP1       RECORD;
  aCount       numeric;
  aCodGest     numeric;
  TIPPREFIX    varchar;
  Blocare      numeric;
  aValRegieMan numeric;
  aBanca       character varying;
  aDur         numeric;
  aPrecI       numeric;
  aPrecF       numeric;
  aDurPrec     numeric;
  aLotOptim    numeric;
  aCodMan      numeric;
BEGIN
  --Florin 20.09.2023 - sinc. Oracle
  --Florin 18.08.2023 - sinc. Oracle
  --Florin 14.03.2023 - sinc. Oracle (13.03.2023)
  --Florin 10.11.2022 - sinc. Oracle
  --Laura 26.01.2022 - sinc. Oracle (28.12.2021)
  --Laura 02.12.2021 - sinc Oracle (01.12.2021)
  --Adina 02.07.2021 - sinc.Oracle din 02.07.2021
  --Adina 12.06.2021 - sinc.Oracle din 10.06.2021
  --Adina 07.06.2021 - sinc.Oracle din 02.06.2021
  --Adina 31.05.2021 - sinc.Oracle din 31.05.2021
  --Adina 29.05.2021 - sinc.Oracle din 27.05.2021
  --Florin rezolvat tichet #38162 (current_timestamp -&gt; current_date::varchar, aBanca::numeric)
  --Florin 16.11.2021 - fixat 52001
  perform pkg_prodcomp_setct_monitor('MON_37');
  aBanca := fnc_GetValConstantaLucru('BancaProdV');
  IF  fnc_GetValConstantaLucru('BancaProdV') = '0' THEN
    aBanca := fnc_GetValConstantaLucru('BancaSitV');
  END IF;

  BEGIN
    SELECT (fnc_GetValConstantaLucru('BlocareModifReteta'))::numeric INTO Blocare;
  EXCEPTION WHEN OTHERS THEN
    Blocare := 2;
  END;

  BEGIN
    SELECT sum(CASE WHEN  COALESCE(man.bps, 0) = 0 THEN COALESCE(t1.tarif, 0) * COALESCE(man.tu, 0) / 60 * COALESCE(pg.coefman, COALESCE(g.coefcheltman, 0))
                    ELSE COALESCE(t1.tarif, 0) * COALESCE(man.tu, 0) / 60 / COALESCE(man.bps, 0) * COALESCE(pg.coefman, COALESCE(g.coefcheltman, 0))
               END )
    INTO aValRegieMan
    FROM prodcomp pc
      INNER JOIN prodman    man ON  man.codprodcomp = pc.codprodcomp
      INNER JOIN prodgest   pg  ON  pg.codprodcomp  = pc.codprodcomp and  man.codprodgest = pg.codprodgest
      LEFT  JOIN ngest      g   ON  g.codgest       = pg.codgest
      LEFT  JOIN TARIFEMAN1 T1  ON  t1.codtarif     = man.codtarif AND getANLUNALUCRU() BETWEEN T1.ALStart AND T1.ALStop
    WHERE pc.codprodcomp = RecId;
  EXCEPTION WHEN others THEN
    aValRegieMan := 0;
  END;

  begin
    select cant into aLotOptim from prodcomp where codprodcomp = recid;
  exception when others then aLotOptim := 1;
  end;

  INSERT INTO TMP_PRODCOMP(CodProdComp, CODOBIECT, OBS, DATA, ANULAT, BLOCAT, OPERAT, CANT, D1, D2, D3, TIPRETETA,
                           CantUM1, RELATIEUM1, DEN_OBIECT, DEN_UM, Den_UmSpec, UM, UM1, COEFINDIRECTE, PRET,
                           IMPLICIT, descriere, inactiv, Gest, HFactor, IDENTIFICATOR, DATADOCUMENTATIE, ARHIVA,
                           OBSERVATII, PROIECTANT, CodClasaProd, Invizibila, Generic, durata, totalmat, totalman,
                           totalrez, totalprod, TipPret, codproiect, valmat, valman, valregie, genericold,
                           inactivold, implicitold, Obs1, Obs2, Obs3, Obs4, Obs5, Obs6, CodMoneda, PretValuta, AG,
                           ValAG, Profit, ValProfit, PretFinal, VALPROFITV, PRETFINALV, TOTPRETCOEF, TOTPRETFIX,
                           TOTPRETCOEFV, TOTPRETFIXV, valregieman, NOHFACTOR)
  (SELECT P.CodProdComp, P.CODOBIECT, P.OBS, P.DATA, P.ANULAT, P.BLOCAT, P.OPERAT, P.Cant, P.D1, P.D2, P.D3,
          P.TIPRETETA, P.CantUM1, ART.RELATIEUM1, OBJ.Denumire, U.Den_Um, U1.Den_Um, Art.UM, U1.CodUM,
          P.COEFINDIRECTE, P.PRET, P.Implicit, P.Descriere, P.Inactiv, P.Gest, P.HFactor, P.IDENTIFICATOR,
          P.DATADOCUMENTATIE, P.ARHIVA, P.OBSERVATII, P.PROIECTANT, P.CodClasaProd, P.Invizibila, P.Generic, P.durata,
          COALESCE((SELECT sum(COALESCE(cant, 0) * COALESCE(pret, 0)) FROM prodmat WHERE codprodcomp = recid), 0),
          COALESCE((SELECT sum(COALESCE(valoare, 0))                  FROM prodman WHERE codprodcomp = recid), 0),
          COALESCE((SELECT sum(COALESCE(cant, 0) * COALESCE(pret, 0)) FROM prodrez WHERE codprodcomp = recid), 0),
          COALESCE((SELECT sum(COALESCE(cant, 0) * COALESCE(pret, 0)) FROM prodmat WHERE codprodcomp = recid), 0)
           + COALESCE((SELECT sum(COALESCE(valoare, 0))                  FROM prodman WHERE codprodcomp = recid), 0)
           - COALESCE((SELECT sum(COALESCE(cant, 0) * COALESCE(pret, 0)) FROM prodrez WHERE codprodcomp = recid), 0),
          P.TipPret, P.CodProiect, P.Valmat, p.valman, p.valregie, p.generic, p.inactiv, p.implicit,
          P.Obs1, P.Obs2, P.Obs3, P.Obs4, P.Obs5, P.Obs6, P.CodMoneda, P.PretValuta, P.AG, P.ValAG, P.Profit,
          P.ValProfit, P.PretFinal, P.VALPROFITV, P.PRETFINALV, COALESCE(P.TOTPRETCOEF,
          COALESCE(P.pret, 0) * (1 + COALESCE(P.COEFINDIRECTE, 0)) ), COALESCE(P.TOTPRETFIX,
          COALESCE(P.pret, 0) + COALESCE(P.COEFINDIRECTE, 0)),
          COALESCE(P.TOTPRETCOEFV, P.TOTPRETCOEF / (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL,P.codmoneda, aBanca::numeric, CURRENT_DATE::varchar))),
          COALESCE(P.TOTPRETFIXV , P.TOTPRETFIX  / (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL,P.codmoneda, aBanca::numeric, CURRENT_DATE::varchar))),
          COALESCE(P.ValRegieMan, aValRegieMan), COALESCE(P.NOHFACTOR, 0)
   FROM PRODCOMP P
      LEFT JOIN NARTOBJ OBJ ON  P.CODOBIECT    = OBJ.CODOBIECT
      LEFT JOIN NART    ART ON  OBJ.CODARTICOL = ART.CODARTICOL
      LEFT JOIN NUM     U   ON  ART.UM  = U.CODUM
      LEFT JOIN NUM     U1  ON  ART.UM1 = U1.CODUM
   WHERE P.CodProdComp = RecId
  );

  UPDATE tmp_prodcomp SET valtotal = COALESCE(valmat, 0) + COALESCE(valman, 0) + COALESCE(valregie, 0);

  IF  Blocare = 1 THEN
    UPDATE tmp_prodcomp SET nrcmd = (SELECT count(*) FROM comanda1 WHERE codreteta = RecId);
  END IF;

  UPDATE tmp_prodcomp SET durataafis = durata;

  IF  fnc_GetValConstantaLucru('AfisareDurata') = '2' THEN
    UPDATE tmp_prodcomp SET durataafis = COALESCE(durata, 0) / 60;
  END IF;

  BEGIN
    SELECT COALESCE(Gest, 0) INTO aCodGest FROM TMP_ProdComp;
  EXCEPTION WHEN others THEN
    aCodGest := 0;
  END;

  --inainte de PRODMAT
  INSERT INTO TMP_PRODMAN(CODMAN, CODPRODCOMP, NROP, CODOP, CODLOC, CODTARIF, TU, VALOARE, DEN_OPERATIE, DEN_LOCMUNCA,
                          DIFICULTATE, TARIF, CODPRODGEST, DSV, BPS, TPI, Obs, Detalii, Fix, Nivel, TUH, TPIH, CODEXTERN, DECALAJ, BARA, INCEPERE, VALOARELEI)
  (
    SELECT PM.CODMAN, PM.CODPRODCOMP, PM.NROP, PM.CODOP, PM.CODLOC, PM.CODTARIF, PM.TU, PM.VALOARE, O.DENUMIRE, LM.DENUMIRE,
           T.Denumire, COALESCE(T1.TARIF, PM.VALOARE/PM.TU*60), COALESCE(PM.CodProdGest, 0), PM.DSV, PM.Bps, PM.Tpi, PM.obs, PM.Detalii, Fix,
           Nivel, COALESCE(PM.TU, 0) / 60, COALESCE(PM.Tpi, 0) / 60, O.CODEXTERN,
           case when coalesce(PM.DECALAJ,0) = 0 then 1 else PM.DECALAJ end,
           '...' BARA, PM.INCEPERE,
           PM.VALOARE *
           PKG_LIST_BASE_UTILS_GETCURSREFERINTA(
           coalesce(PC.codmoneda,0),
           (CASE WHEN fnc_getvalconstantalucru('BancaProdV') = '0' THEN fnc_getvalconstantalucru('BancaSitV')::numeric
           ELSE fnc_getvalconstantalucru('BancaProdV')::numeric end),
           current_date::varchar)
    FROM PRODMAN PM
                             INNER JOIN PRODCOMP PC ON PC.CODPRODCOMP = PM.CODPRODCOMP
    LEFT JOIN NOPER      O  ON  PM.CODOP    = O.CODOP
    LEFT JOIN LOCMUNCA   LM ON  PM.CODLOC   = LM.CODLOC
    LEFT JOIN TARIFEMAN1 T1 ON  t1.codtarif = pm.codtarif AND getANLUNALUCRU() BETWEEN T1.ALStart AND T1.ALStop
    left join TARIFEMAN  T  ON  t.codtarif  = pm.codtarif
    WHERE PM.CodProdComp = RecId
  );

  FOR v_Rec IN
  (
    SELECT PM.CODMAT, PM.CODPRODCOMP, PM.CODOBIECT, PM.CANT, PM.PRET, PM.PRETV, PM.D1, PM.D2, PM.D3, PM.CopyD1, PM.CopyD2, PM.CopyD3, PM.Indexlocal, PM.CantUM1,
           ART.RelatieUM1, OBJ.DENUMIRE, ART.UM, ART.UM1, ART.CODARTICOL, COALESCE(PM.CodProdGest, 0) CODPRODGEST, PM.Tip, COALESCE(PM.Codatribut, 0) CODATRIBUT,
           pm.Obs, 1 PARITATE, NUM.DEN_UM, pm.valmat, pm.valman, pm.valregie, obj.codintern, obj.codextern,
           ROW_NUMBER() OVER(ORDER BY pm.indexlocal) ORDINE, PM.Adddim, PM.Adddim_Transp, PM.Pretorig, PROD.DEN_PART, COALESCE(PM.ProcReal, 100) PROCREAL,
           round((PM.Cant * 100 / CASE WHEN  COALESCE(PM.ProcReal, 100)=0 THEN 100 ELSE  COALESCE(PM.ProcReal, 100) END )::numeric, 7) CANTT,
           COALESCE(PM.Valoare, PM.Cant * PM.Pret) VALOARE, PM.CodReteta,
           CASE WHEN  PC.CODPRODCOMP &gt; 0 THEN PC.OBS ELSE NULL END  RETETA,
           PM.CodMan, MAN.NROP, MAN.DEN_OPERATIE, PM.ETAPA, PRINCIPAL, PM.CONSUM
    FROM PRODMAT PM
        LEFT JOIN NARTOBJ     OBJ  ON  PM.CODOBIECT   = OBJ.Codobiect
        LEFT JOIN NPART       PROD ON  PROD.CODPART   = OBJ.CODPRODUCATOR
        LEFT JOIN NART        ART  ON  OBJ.CODARTICOL = ART.CODARTICOL
        LEFT JOIN NUM              ON  ART.UM         = NUM.CODUM
        LEFT JOIN PRODCOMP    PC   ON  PC.CODPRODCOMP = PM.CODRETETA
        LEFT JOIN TMP_PRODMAN MAN  ON  MAN.CODMAN     = PM.CODMAN
    WHERE PM.CodProdComp = RecId
    ORDER BY pm.indexlocal
  )
  LOOP
    INSERT INTO TMP_PRODMAT(CODMAT, CODPRODCOMP, CODOBIECT, CANT, PRET, PRETV, D1, D2, D3, CopyD1, CopyD2, CopyD3, IndexLocal, CantUM1, RelatieUM1, DEN_OBIECT,
                            CODUM, CODUMSPEC, CODARTICOL, CodProdGest, Tip, codatribut, Obs, Paritate, denum, valmat, valman, Valregie, CodIntern, CodExtern,
                            ADDDIM, ADDDIM_TRANSP, PRETORIG, PRODUCATOR, Procreal, Cantt, Valoare, Codreteta, RETETA, CodMan, NrOp, OPER, ETAPA, PRINCIPAL, CONSUM)
    VALUES(v_rec.CODMAT, v_rec.CODPRODCOMP, v_rec.CODOBIECT, v_rec.CANT, v_rec.PRET, v_rec.PRETV, v_rec.D1, v_rec.D2, v_rec.D3, v_rec.CopyD1, v_rec.CopyD2, v_rec.CopyD3,
           v_rec.IndexLocal, v_rec.CantUM1, v_rec.RelatieUM1, v_rec.DENUMIRE, v_rec.UM, v_rec.UM1, v_rec.CODARTICOL, v_rec.CodProdGest, v_rec.Tip, v_rec.Codatribut,
           v_rec.Obs, v_rec.Paritate, v_rec.DEN_UM, v_rec.valmat, v_rec.valman, v_rec.valregie, v_rec.codintern, v_rec.codextern, V_REC.ADDDIM, V_REC.ADDDIM_TRANSP,
           COALESCE(V_REC.PRETORIG, V_REC.PRET), V_REC.DEN_PART, v_rec.ProcReal, v_rec.CantT, v_rec.valoare, v_rec.codreteta, V_REC.RETETA, v_rec.CodMan, v_rec.nrop,
           V_REC.DEN_OPERATIE, V_REC.ETAPA, V_REC.PRINCIPAL, V_REC.CONSUM);
  END LOOP;

  INSERT INTO TMP_PRODREZ(CODREZ, CODPRODCOMP, CODOBIECT, CANT, PRET, D1, D2, D3, IndexLocal, REZIDUU, CantUM1, RelatieUM1,
                          DEN_OBIECT, CODUM, CODUMSPEC, CODARTICOL, CodProdGest, Paritate, CodIntern, CodExtern, DENUM, Obs)
  SELECT PR.CODREZ, PR.CODPRODCOMP, PR.CODOBIECT, PR.CANT, PR.PRET, PR.D1, PR.D2, PR.D3, PR.IndexLocal, PR.REZIDUU, PR.CantUM1,
         ART.RelatieUM1, OBJ.DENUMIRE, ART.UM, ART.UM1, ART.CODARTICOL, COALESCE(PR.CodProdGest, 0), 1, obj.codintern, obj.codextern, NUM.DEN_UM, PR.Obs
  FROM PRODREZ PR
      LEFT JOIN NARTOBJ OBJ ON  PR.CODOBIECT   = OBJ.Codobiect
      LEFT JOIN NART    ART ON  OBJ.CODARTICOL = ART.CODARTICOL
      LEFT JOIN NUM         ON  ART.UM         = NUM.CODUM
  WHERE PR.CodProdComp = RecId
  ORDER BY Indexlocal ;

  INSERT INTO TMP_PRODGEST(CODPRODGEST, CODPRODCOMP, INDEXLOCAL, CODGEST, CoefMat, CoefMan, TimpEst)
  SELECT CODPRODGEST, CODPRODCOMP, INDEXLOCAL, pg.CODGEST, COALESCE(pg.CoefMat, g.CoefCheltMat), COALESCE(pg.CoefMan, g.CoefCheltMan), pg.TimpEst
  FROM PRODGEST pg LEFT JOIN ngest g ON  g.codgest = pg.codgest
  WHERE CODPRODCOMP = RecId;

  INSERT INTO TMP_PRODNORME(CODNORMA, CODPRODCOMP, NORMA, INDEXLOCAL, IMPLICIT, ACTIV, DATAACTIV, DATAINACTIV)
  SELECT CODNORMA, CODPRODCOMP, NORMA, INDEXLOCAL, COALESCE(IMPLICIT, 0), COALESCE(ACTIV, 0), DATAACTIV, DATAINACTIV
  FROM PRODNORME WHERE CODPRODCOMP = RECID;
  SELECT count(*) INTO aCount FROM tmp_prodgest;
  IF  aCount = 0 THEN
    INSERT INTO TMP_PRODGEST(CODPRODGEST, CODPRODCOMP, INDEXLOCAL, CODGEST)
    VALUES(0, RecId, 1, aCodGest);

    BEGIN
      SELECT count(codprodgest) INTO aCount FROM tmp_prodmat;
      IF  aCount = 1 THEN
        UPDATE tmp_prodgest SET codprodgest = (SELECT  DISTINCT codprodgest FROM tmp_prodmat);
      END IF;
    EXCEPTION WHEN others THEN
      UPDATE tmp_prodgest SET codprodgest = 0;
    END;
  END IF;

  INSERT INTO tmp_prodmas(codprodmas, codprodcomp, descriere, frecventa, metoda, codobiect, indexlocal, denumire)
  SELECT pm.codprodmas, pm.codprodcomp, pm.descriere, pm.frecventa, pm.metoda, pm.codobiect, pm.indexlocal, obj.denumire
  FROM prodmas PM LEFT JOIN nartobj obj ON  pm.codobiect = obj.codobiect
  WHERE codprodcomp = RecId;

  INSERT INTO TMP_PRODSDV(CODPRODSDV, CODPRODMAN, INDEXLOCAL, CODSDV, CODGENERIC, CANT, PRET, CODPRODCOMP, DENUMIRE, CODUM, CODARTICOL, DENUM)
  SELECT SDV.CODPRODSDV, SDV.CODPRODMAN, SDV.INDEXLOCAL, SDV.CODSDV, SDV.CODGENERIC, SDV.CANT, SDV.PRET, SDV.CODPRODCOMP, OBJ.DENUMIRE, ART.UM, OBJ.CODARTICOL, NUM.DEN_UM
  FROM PRODSDV SDV
      LEFT JOIN NARTOBJ OBJ ON  SDV.CODSDV     = OBJ.CODOBIECT
      LEFT JOIN NART    ART ON  OBJ.CODARTICOL = ART.CODARTICOL
      LEFT JOIN NUM         ON  ART.UM         = NUM.CODUM
  WHERE CODPRODCOMP = RecId;

  INSERT INTO TMP_NORMEMAT(CODNORMEMAT, CODNORMA, CODPRODCOMP, CODOBIECT, CANT, PRET, CODMAT, D1, D2, D3, INDEXLOCAL, CANTUM1, DEN_OBIECT, RELATIEUM1, DENUM, PARITATE, CODUM, CODUMSPEC)
  SELECT NMAT.CODNORMEMAT, NMAT.CODNORMA, NMAT.CODPRODCOMP, NMAT.CODOBIECT, NMAT.CANT, NMAT.PRET, NMAT.CODMAT, NMAT.D1, NMAT.D2, NMAT.D3, NMAT.INDEXLOCAL, NMAT.CANTUM1, OBJ.DENUMIRE, ART.RELATIEUM1, NUM.DEN_UM, 1, ART.UM, ART.UM1
  FROM NORMEMAT NMAT
      INNER JOIN PRODNORME N   ON  N.CODNORMA     = NMAT.CODNORMA
      INNER JOIN NARTOBJ   OBJ ON  OBJ.CODOBIECT  = NMAT.CODOBIECT
      INNER JOIN NART      ART ON  ART.CODARTICOL = OBJ.CODARTICOL
      INNER JOIN NUM           ON  ART.UM         = NUM.CODUM
  WHERE NMAT.CODPRODCOMP = RECID;

  INSERT INTO tmp_prodmatechiv(codmatechiv, codprodcomp, codmat, codobiect, paritate, ordine, denumire, UM, den_UM)
  SELECT e.codmatechiv, e.codprodcomp, e.codmat, e.codobiect, e.paritate, e.ordine, obj.denumire, a.um, num.den_um
  FROM prodmatechiv e
      INNER JOIN nartobj obj ON  e.codobiect    = obj.codobiect
      INNER JOIN nart    a   ON  obj.codarticol = a.codarticol
      INNER JOIN num         ON  num.codum      = a.um
  WHERE codprodcomp = RecId;

  INSERT INTO TMP_PROIECTE(CODPROIECT, VERSIUNE, DURATA, DATAPROIECT, INACTIV, FINALIZAT, BLOCAT, GENERIC, IMPLICIT, OBS1, OBS2, OBS3, OBS4, OBS5, OBS6)
  SELECT P.CODPROIECT, P.VERSIUNE, P.DURATA, P.DATAPROIECT, mod(P.ACTIV + 1, 2), COALESCE(P.FINALIZAT, 0), COALESCE(P.BLOCAT, 0), COALESCE(P.GENERIC, 0), COALESCE(P.IMPLICIT, 0), P.OBS1, P.OBS2, P.OBS3, P.OBS4, P.OBS5, P.OBS6
  FROM TMP_PRODCOMP PC
      INNER JOIN PROIECTNOD PN ON  PN.CODOBIECT  = PC.CODOBIECT AND  COALESCE(PN.NODORIGINAL, 0) = 0
      INNER JOIN PROIECT    P  ON  PN.CODPROIECT = P.CODPROIECT;

  SELECT count(*) INTO aCount FROM tmp_prodgest WHERE COALESCE(indexlocal, 0) &gt; 0;
  IF  aCount = 0 THEN
    FOR v_rec IN (SELECT codprodgest FROM tmp_prodgest ORDER BY codprodgest) LOOP
      aCount := aCount + 1;
      UPDATE tmp_prodgest SET indexlocal = aCount WHERE codprodgest = v_rec.codprodgest;
    END LOOP;
  END IF;

  SELECT count(*) INTO aCount FROM tmp_prodmat WHERE COALESCE(indexlocal, 0) &gt; 0;
  IF  aCount = 0 THEN
    FOR v_rec IN (SELECT codprodgest FROM tmp_prodgest) LOOP
      aCount := 0;
      FOR v_tmp IN (SELECT * FROM tmp_prodmat WHERE codprodgest = v_Rec.codprodgest ORDER BY codmat) LOOP
        aCount := aCount + 1;
        UPDATE tmp_prodmat SET indexlocal = aCount WHERE codmat = v_tmp.codmat;
      END LOOP;
    END LOOP;
  END IF;

  SELECT count(*) INTO aCount FROM tmp_prodrez WHERE COALESCE(indexlocal, 0) &gt; 0;
  IF  aCount = 0 THEN
    FOR v_rec IN (SELECT codprodgest FROM tmp_prodgest) LOOP
      aCount := 0;
      FOR v_tmp IN (SELECT * FROM tmp_prodrez WHERE codprodgest = v_Rec.codprodgest ORDER BY codrez) LOOP
        aCount := aCount + 1;
        UPDATE tmp_prodrez SET indexlocal = aCount WHERE codrez = v_tmp.codrez;
      END LOOP;
    END LOOP;
  END IF;

  SELECT count(*) INTO aCount FROM tmp_prodman WHERE COALESCE(indexlocal, 0) &gt; 0;
  IF  aCount = 0 THEN
    FOR v_rec IN (SELECT codprodgest FROM tmp_prodgest) LOOP
      aCount := 0;
      FOR v_tmp IN (SELECT * FROM tmp_prodman WHERE codprodgest = v_Rec.codprodgest ORDER BY codman) LOOP
        aCount := aCount + 1;
        UPDATE tmp_prodman SET indexlocal = aCount WHERE codman = v_tmp.codman;
      END LOOP;
    END LOOP;
  END IF;

  SELECT count(*) INTO aCount FROM tmp_prodsdv WHERE COALESCE(indexlocal, 0) &gt; 0;
  IF  aCount = 0 THEN
    FOR v_rec IN (SELECT codprodgest FROM tmp_prodgest) LOOP
      FOR v_tmp IN (SELECT * FROM tmp_prodman WHERE codprodgest = v_Rec.codprodgest ORDER BY codman) LOOP
        aCount := 0;
        FOR v_tmp1 IN (SELECT * FROM tmp_prodsdv WHERE codprodman = v_tmp.codman ORDER BY codsdv) LOOP
          aCount := aCount + 1;
          UPDATE tmp_prodsdv SET indexlocal = aCount WHERE codsdv = v_tmp1.codsdv;
        END LOOP;
      END LOOP;
    END LOOP;
  END IF;

  BEGIN
    SELECT fnc_GetValConstantaLucru('TipPrefixDenObiect') INTO TIPPREFIX;
  EXCEPTION WHEN OTHERS THEN
    TIPPREFIX := '1';
  END;

  IF  TIPPREFIX = '2' THEN
    UPDATE TMP_PRODMAT MAT
    SET
    DEN_OBIECT = COALESCE((SELECT CODEXTERN FROM NARTOBJ O WHERE O.CODOBIECT = MAT.CODOBIECT), '') || ';' || coalesce(DEN_OBIECT,'');

    UPDATE TMP_PRODREZ REZ
    SET
    DEN_OBIECT = COALESCE((  SELECT CODEXTERN FROM NARTOBJ O WHERE O.CODOBIECT = REZ.CODOBIECT), '') || ';' || coalesce(DEN_OBIECT,'');
  ELSE
    IF  TIPPREFIX = '3' THEN
      UPDATE TMP_PRODMAT MAT
      SET
      DEN_OBIECT = COALESCE((SELECT CODINTERN FROM NARTOBJ O WHERE O.CODOBIECT = MAT.CODOBIECT), '') || ';' || coalesce(DEN_OBIECT,'');

      UPDATE TMP_PRODREZ REZ
      SET
      DEN_OBIECT = COALESCE((SELECT CODINTERN FROM NARTOBJ O WHERE O.CODOBIECT = REZ.CODOBIECT), '') || ';' || coalesce(DEN_OBIECT,'');
    END IF;
  END IF;

/*
  for v_rec in (select tu, codman from tmp_prodman order by nrop, detalii) loop
    aDur     := v_rec.tu;
    aDurPrec := aDur;
    aPrecI   := 0;
    aPrecF   := v_rec.tu;
    aCodMan  := v_rec.codman;
    Exit;
  end loop;

  for v_rec in (select codman, tu, coalesce(decalaj,4) decalaj, nrop, detalii from tmp_prodman where codman &lt;&gt; aCodMan order by nrop, detalii) loop
    if v_rec.decalaj in (0,1,4) then
      if aDur - aPrecI - aDurPrec &lt; v_Rec.tu * aLotOptim then
        aDur := aPrecF + v_Rec.tu * aLotOptim;
      else
        aDur := aDur + v_Rec.tu * aLotOptim;
        update tmp_prodman set incepere = aPrecF where codman = v_rec.codman;
      end if;

      update tmp_prodman set incepere = aPrecF where codman = v_rec.codman;
      aPrecI := aPrecI + aDurPrec;
      aPrecF := aPrecF + v_Rec.tu * aLotOptim;
    else
      if v_Rec.decalaj = 2 then
        update tmp_prodman set incepere = aPrecI where codman = v_rec.codman;
        if aDurPrec &lt; v_rec.TU * aLotOptim then
          aDur := aDur - aDurPrec + v_rec.TU * aLotOptim;
        end if;
        aPrecF := aPrecI + v_rec.TU * aLotOptim;
      else
        if v_rec.decalaj = 3 then
          if aDur &lt; v_rec.TU * aLotOptim then
            update tmp_prodman set incepere = incepere + v_rec.TU * aLotOptim - aDur where nrop &lt; v_rec.nrop;
            update tmp_prodman set incepere = incepere + v_rec.TU * aLotOptim - aDur where nrop = v_rec.nrop and detalii &lt; v_rec.detalii;
            aDur   := v_rec.TU * aLotOptim;
            aPrecI := 0;
            aPrecF := v_rec.TU * aLotOptim;
          else
            aPrecI := aDur - v_rec.TU * aLotOptim;
            update tmp_prodman set incepere = aPrecI where codman = v_rec.codman;
          end if;
        end if;
      end if;
    end if;
    aDurPrec := v_Rec.tu * aLotOptim;
  end loop;
*/
  perform PKG_CFGTABLES_EXT_GOTORECORD(504);
  IF current_setting('PKG_PRODCOMP.DoCommit', true) THEN
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_sp_postrecords</obj_name>
  <obj_hashval>7e737043ad3b7105e224b68cd22ac673</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  V_REC         RECORD;
  V_XXX         RECORD;
  V_TMP         RECORD;
  vCodProdMan   numeric;
  vCodProdGest  numeric;
  vCodMat       numeric;
  vCod          numeric;
  aDataDoc      date;
  aDoc          varchar;
  aCant         numeric;
  aCantIni      numeric;
  aCodObiect    numeric;
  aTip          numeric;
  OldGeneric    numeric;
  NewGeneric    numeric;
  aCodProiect   numeric;
  aCount        numeric;
  aCount1       numeric;
  aClonare      numeric;
  aCodUtilizare numeric;
  aCodObjNou    numeric;
  aCodObjVechi  numeric;
  aGenPrj       numeric(10);
BEGIN
  --Florin 03/09.04.2025 - fixat 65265
  --Florin 04.10.2024 - fixat 63593
  --Florin 05.12.2023 - sinc. Oracle
  --Florin 18.08.2023 - sinc. Oracle
  --Florin 01.06.2023 - monitor
  --Florin 03.05.2023 - fixat 58105
  --Florin 31.01.2023 - fixat 56934
  --Florin 10.11.2022 - sinc. Oracle
  --Florin 28.03.2022 - sinc. Oracle
  --Florin 09.03.2022 - sinc. Oracle (07.03.2022)
  --Bogdan 09.02.2022 - sinc Oracle 52988
  --Laura 02.12.2021 - sinc Oracle (01.12.2021)
  --Florin 22.11.2021 - fixat 52094
  --Adina 09.07.2021 - sinc.Oracle din 08.07.2021
  --Adina 01.07.2021 - sinc.Oracle din 01.07.2021
  --Adina 29.06.2021 - sinc.Oracle din 28.06.2021 si 29.06.2021
  --Adina 12.06.2021 - sinc.Oracle din 10.06.2021
  --Adina 01.06.2021 - sinc.Oracle din 31.05.2021
  --Adina 29.05.2021 - sinc.Oracle din 27.05.2021
  --Florin 23.10.2020 - inlocuit ROWNUM cu ROW_NUMBER() OVER()
  --Florin 23.03.2021  pkg_userfirme_postlogcucommit
  perform pkg_prodcomp_setct_monitor('MON_37');
  aGenPrj := CASE WHEN fnc_getvalconstanta('ImpRetGenPrj', getanlucru(), getlunalucru()) = '' THEN 0 ELSE fnc_getvalconstanta('ImpRetGenPrj', getanlucru(), getlunalucru())::NUMERIC END;
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT(504);
  if Operation &lt;&gt; 0 and current_setting('PKG_PRODCOMP.VFROMIMPORT', true)::NUMERIC &gt; 0 THEN
    if aGenPrj = 1 THEN
      insert into tmp_manevra_liste(filtru, valoare, filtru1)
      select 'CODMAT', TO_CHAR(CODMAT), RETETA
      FROM TMP_PRODMAT
      WHERE LENGTH(TRIM(RETETA)) &gt; 0;
    END IF;
    select count(*) into aCount from tmp_prodmat;
    for v_rec in (
      select pc.codprodcomp
      from prodcomp pc
           inner join tmp_prodcomp t on t.codobiect = pc.codobiect and pc.cant = t.cant
    ) loop
      select count(*) into aCount1
      from prodmat m
           inner join tmp_prodmat tm on tm.codobiect = m.codobiect and tm.cant = m.cant
      where m.codprodcomp = v_rec.codprodcomp;
      if aCount = aCount1 then
        RecID := v_rec.codprodcomp;
        Exit;
      end if;
    end loop;
    if RecID &gt; 0 then return; end if;
  end if;

  SELECT data, 'OBJ:' || coalesce(DEN_OBIECT, '') || ' VER:' || coalesce(OBS, '') || ' (' || coalesce(CODPRODCOMP::varchar , '') || ')'
  INTO aDATADOC, ADOC
  FROM TMP_PRODCOMP;

  if Operation = 0 then
    SELECT CodProdComp, Cant, CodObiect INTO RecId, aCant, aCodObjNou FROM Tmp_ProdComp;

    aClonare := (SELECT PKG_PRODCOMP_PrjFExists.WME_RESULT FROM PKG_PRODCOMP_PrjFExists(null, RecID));

    if aClonare &gt; 0 and fnc_GetValConstantaLucru('RetPrjModif') &lt;&gt; '1' then
      UPDATE prodcomp
      SET
        ascuns   = 1,
        implicit = 0,
        generic  = 0
      WHERE codprodcomp = RecID ;

      aCodUtilizare := RecID;

      SELECT CodObiect INTO aCodObjVechi FROM prodcomp WHERE codprodcomp = RecID;
    end if;

    SELECT cant INTO aCantIni FROM prodcomp WHERE codprodcomp = recid;
    PERFORM pkg_prodcomp_CheckRetCentr(RecID);
  end if;

  if aClonare &gt; 0 and fnc_GetValConstantaLucru('RetPrjModif') = '1' then
    aClonare := 0;
  end if;

  IF Operation = 0 and ( aClonare = 0) THEN
    SELECT cant INTO aCantIni FROM prodcomp WHERE codprodcomp = recid;

    if aCant &lt;&gt; aCantIni then
      UPDATE proiectnod SET cant = aCant WHERE codreteta = RecId ;
    end if;

    SELECT generic INTO NewGeneric FROM tmp_prodcomp;
    SELECT generic INTO OldGeneric FROM prodcomp WHERE CodProdComp = RecId;

    if NewGeneric = 1 and OldGeneric = 0 then
      SELECT coalesce(CodProiect, 0) INTO aCodProiect FROM tmp_prodcomp;

      if aCodProiect &gt; 0 then
        UPDATE proiect SET generic = 1 WHERE CodProiect = aCodProiect ;
      end if;
    end if;

    if (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT
        FROM   PKG_USERFIRME_ValidPostLog(null,
                                          current_setting('PKG_GLOBALS.USERID', true)::numeric,
                                          current_setting('PKG_PRODCOMP.CT_MONITOR', true)))
    then
            perform pkg_userfirme_postlogcucommit('PRODCOMP'::varchar,
                                            current_setting('PKG_GLOBALS.USERNAME', true),
                                            'M'::varchar,
                                            RECID,
                                            current_setting('PKG_GLOBALS.FIRMANAME', true),
                                            current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric,
                                            aDataDoc,
                                            aDoc,
                                            null::varchar,
                                            current_setting('PKG_GLOBALS.EXE_VERSION', true));
    end if;

    UPDATE prodcomp
    SET
      (CODOBIECT,
      HFactor,
      OBS,
      data,
      ANULAT,
      BLOCAT,
      OPERAT,
      CANT,
      D1,
      D2,
      D3,
      TIPRETETA,
      CANTUM1,
      COEFINDIRECTE,
      PRET,
      implicit,
      DESCRIERE,
      INACTIV,
      GEST,
      IDENTIFICATOR,
      DATADOCUMENTATIE,
      ARHIVA,
      OBSERVATII,
      PROIECTANT,
      CodClasaProd,
      INVIZIBILA,
      GENERIC,
      TipPret,
      durata,
      valmat,
      valman,
      valregie,
      codproiect,
      Obs1,
      Obs2,
      Obs3,
      Obs4,
      Obs5,
      Obs6,
      CodMoneda,
      PretValuta,
      AG,
      ValAG,
      Profit,
      ValProfit,
      PretFinal,
      VALPROFITV,
      PRETFINALV,
      TOTPRETCOEF,
      TOTPRETFIX,
      TOTPRETCOEFV,
      TOTPRETFIXV,
      valregieman,
      nohfactor) = (
      select
        CODOBIECT,
        HFactor,
        OBS,
        data,
        ANULAT,
        BLOCAT,
        OPERAT,
        CANT,
        D1,
        D2,
        D3,
        TIPRETETA,
        CANTUM1,
        COEFINDIRECTE,
        PRET,
        implicit,
        DESCRIERE,
        INACTIV,
        GEST,
        IDENTIFICATOR,
        DATADOCUMENTATIE,
        ARHIVA,
        OBSERVATII,
        PROIECTANT,
        CodClasaProd,
        Invizibila,
        GENERIC,
        TipPret,
        durata,
        valmat,
        valman,
        valregie,
        codproiect,
        Obs1,
        Obs2,
        Obs3,
        Obs4,
        Obs5,
        Obs6,
        CodMoneda,
        PretValuta,
        AG,
        ValAG,
        Profit,
        ValProfit,
        PretFinal,
        VALPROFITV,
        PRETFINALV,
        TOTPRETCOEF,
        TOTPRETFIX,
        TOTPRETCOEFV,
        TOTPRETFIXV,
        valregieman,
        nohfactor
      FROM tmp_prodcomp )
    WHERE
      codprodcomp = RecId ;

    for v_rec in (select pg.codprodgest,
      (select min(pg.codprodgest) from prodgest p where p.codprodcomp = pg.codprodcomp
        and exists (select pm.codmat from prodmat pm where pm.codprodgest = p.codprodgest)
        ) codprodgestnou
        from prodgest pg
        where pg.codprodcomp = RecId and not exists (select tmp_PG.codprodgest from tmp_prodgest tmp_pg where tmp_pg.codprodgest = pg.codprodgest) GROUP BY pg.codprodgest
    ) LOOP
      update prodmat set codprodgest = v_rec.codprodgestnou where codprodgest = v_rec.codprodgest;
      delete FROM prodgest where codprodgest = v_rec.codprodgest;
    end loop;

    DELETE FROM prodgest pg
    WHERE pg.codprodcomp = RecId and not exists (SELECT tmp_PG.codprodgest FROM tmp_prodgest tmp_pg WHERE tmp_pg.codprodgest = pg.codprodgest );

    for v_Rec in (SELECT * FROM tmp_prodgest ) loop
      if v_Rec.Codprodgest &gt; 0 then
        UPDATE prodgest
        SET
          IndexLocal = v_Rec.Indexlocal,
          CodGest    = v_Rec.Codgest,
          CoefMat    = v_rec.coefmat,
          CoefMan    = v_rec.coefman,
          TimpEst    = v_rec.Timpest
        WHERE
          codprodgest = v_Rec.Codprodgest ;
      else
        SELECT nextval('SEQ_PRODGEST_CODPRODGEST') INTO vCodProdGest;

        INSERT INTO prodgest ( codprodgest, codprodcomp, IndexLocal, codgest, CoefMat, CoefMan, TimpEst )
        values ( vCodProdGest, v_Rec.Codprodcomp, v_Rec.IndexLocal, v_Rec.Codgest, v_rec.coefmat, v_rec.coefman, v_rec.TimpEst );

        UPDATE tmp_prodmat SET codprodgest = vCodProdGest WHERE codprodgest = v_rec.codprodgest ;
        UPDATE tmp_prodman SET codprodgest = vCodProdGest WHERE codprodgest = v_rec.codprodgest ;
        UPDATE tmp_prodrez SET codprodgest = vCodProdGest WHERE codprodgest = v_rec.codprodgest ;
      end if;
    end loop;

    DELETE FROM prodman pm
    WHERE pm.codprodcomp = RecId and not exists (SELECT tmp_pm.codman FROM tmp_prodman tmp_pm WHERE tmp_pm.codman = pm.codman );

    for v_rec in (SELECT * FROM tmp_prodman order BY nrop ) loop
      if v_Rec.codman &gt; 0 then
        UPDATE prodman
        SET
          nrop        = v_rec.nrop,
          codop       = v_Rec.codop,
          codloc      = v_rec.codloc,
          codtarif    = v_rec.codtarif,
          tu          = v_rec.tu,
          valoare     = coalesce(v_Rec.valoare, 0),
          CodProdGest = v_Rec.codprodgest,
          DSV         = v_Rec.DSV,
          BPS         = v_Rec.BPS,
          TPI         = coalesce(v_rec.TPI, 0),
          Obs         = v_rec.obs,
          Detalii     = v_rec.Detalii,
          Fix         = v_rec.Fix,
          Nivel       = v_rec.nrop,
          decalaj     = v_rec.decalaj,
          incepere    = v_rec.incepere
        WHERE
          codman = v_Rec.codman ;
      else
        SELECT nextval('SEQ_PRODMAN_CODMAN') INTO vCodProdMan;

        INSERT INTO prodman ( codman, codprodcomp, nrop, codop, codloc, codtarif, tu, valoare, CodProdGest, DSV, BPS, TPI, Obs, Detalii, Fix, Nivel, Decalaj, Incepere )
        values ( vCodProdMan, RecId, v_rec.nrop, v_rec.codop, v_Rec.codloc, v_Rec.codtarif, v_Rec.tu, v_Rec.valoare, v_Rec.CodProdGest, v_Rec.DSV, v_Rec.BPS,
                 v_Rec.TPI, v_Rec.Obs, v_rec.Detalii, v_rec.Fix, v_rec.nrop, v_rec.decalaj, v_rec.Incepere);

        UPDATE tmp_prodsdv SET codprodman = vCodProdMan WHERE codprodman = v_rec.codman ;
        UPDATE tmp_prodmat SET codman     = vCodProdMan WHERE codman     = v_rec.codman ;
      end if;
    end loop;

    for v_rec in (SELECT * FROM prodmat pm
                  WHERE pm.codprodcomp = RecId and not exists (SELECT tmp_PM.codmat FROM tmp_prodmat tmp_pm WHERE tmp_pm.codmat = pm.codmat )
                 )
    loop
      DELETE FROM prodmat pm WHERE pm.codmat = v_rec.codmat;

      for v_xxx in (SELECT indexparinte, codproiect FROM proiectnod WHERE codprodmat = v_rec.codmat ) loop
        DELETE FROM nodechiv ne
        WHERE exists (SELECT pn.codproiectnod FROM proiectnod pn
                      WHERE instr(pn.indexparinte, v_xxx.IndexParinte) &gt; 0
                        and pn.CodProiect = v_xxx.CodProiect
                        and ne.codproiectnod = pn.codproiectnod );

        DELETE FROM proiectnod pn WHERE instr(pn.indexparinte, v_xxx.IndexParinte) &gt; 0 and CodProiect = v_xxx.CodProiect;
      end loop;
    end loop;

    for v_rec in (SELECT * FROM tmp_prodmat ) loop
      if v_Rec.Codmat &gt; 0 then
        begin
          SELECT CASE WHEN COALESCE(cant, 0) = 0 THEN 1 ELSE cant END, codobiect, tip INTO STRICT aCant, aCodObiect, aTip FROM prodmat WHERE codmat = v_rec.codmat;
        exception
          when others then
            aCant      := v_rec.cant;
            aCodObiect := v_rec.CodObiect;
            aTip       := v_rec.tip;
        end;

        if not ( round((aCant)::numeric, 7) &lt;&gt; round((v_rec.Cant)::numeric, 7)
                 and aCodObiect = v_rec.CodObiect
                 and aTip = v_rec.tip
               )
        then
          if not ( round((aCant)::numeric, 7) = round((v_rec.Cant)::numeric, 7)
                   and aCodObiect = v_rec.CodObiect
                   and aTip = v_rec.tip
                 )
          then
            for v_xxx in (SELECT indexparinte, codproiect FROM proiectnod WHERE codprodmat = v_rec.codmat ) loop
              if v_rec.Tip in (3, 4, 5) then
                DELETE FROM nodechiv ne
                WHERE exists (SELECT pn.codproiectnod FROM proiectnod pn
                              WHERE instr(pn.indexparinte, v_xxx.IndexParinte) &gt; 0
                                and pn.CodProiect = v_xxx.CodProiect
                                and ne.codproiectnod = pn.codproiectnod
                             );

                DELETE FROM proiectnod pn
                WHERE instr(pn.indexparinte, v_xxx.IndexParinte) &gt; 0
                  and CodProiect = v_xxx.CodProiect
                  and CodProdMat &lt;&gt; v_rec.codmat;
              end if;
            end loop;
          end if;
        else
          for v_xxx in (SELECT indexparinte, codproiect FROM proiectnod WHERE codprodmat = v_rec.codmat ) loop
            if v_rec.Tip in (3, 4, 5) then
              DELETE FROM proiectnod pn
              WHERE instr(pn.indexparinte, v_xxx.IndexParinte) &gt; 0
                and CodProiect = v_xxx.CodProiect
                and CodProdMat &lt;&gt; v_rec.codmat;
            end if;
          end loop;
        end if;

        UPDATE prodmat
        SET
          CODOBIECT     = v_rec.CODOBIECT,
          CANT          = v_rec.cant,
          PRET          = v_rec.pret,
          PRETV         = v_rec.pretv,
          D1            = v_rec.d1,
          D2            = v_rec.d2,
          D3            = v_rec.d3,
          CopyD1        = v_rec.Copyd1,
          CopyD2        = v_rec.Copyd2,
          CopyD3        = v_rec.Copyd3,
          IndexLocal    = v_rec.indexlocal,
          CantUM1       = v_rec.CantUM1,
          CodProdGest   = v_rec.codprodgest,
          Tip           = v_rec.tip,
          Obs           = v_rec.Obs,
          CodAtribut    = v_rec.codatribut,
          AddDim        = v_rec.AddDim,
          AddDim_Transp = v_rec.AddDim_transp,
          PretOrig      = v_rec.pretorig,
          ProcReal      = v_rec.ProcReal,
          Valoare       = v_rec.Valoare,
          CodReteta     = v_rec.CodReteta,
          CodMan        = v_rec.CodMan,
          ETAPA         = V_REC.ETAPA,
          PRINCIPAL     = V_REC.PRINCIPAL,
          CONSUM        = V_REC.CONSUM
        WHERE
          codmat = v_rec.codmat ;

        UPDATE proiectnod
        SET
          Cant      = v_rec.Cant / aCant * Cant,
          CodObiect = v_rec.CodObiect,
          Tip       = CASE when v_rec.tip in (3, 4) then 3
                           when v_rec.tip = 5 then 5
                           else 1
                      END
          WHERE
            codprodmat = v_rec.CodMat ;

        perform PKG_PRODCOMP_PropagaParitateCantInAdancime(v_rec.CodMat, v_rec.Cant);
      else
        vCodMat := nextval('SEQ_PRODMAT_CODMAT');

        UPDATE tmp_prodmatechiv SET codmat = vCodMat WHERE CodMat = v_rec.codmat ;
        UPDATE tmp_normemat     SET codmat = vCodMat WHERE CodMat = v_rec.codmat ;
        if aGenPrj = 1 THEN
          update tmp_manevra_liste set valoare = vCodMat::varchar where filtru = 'CODMAT' and valoare = v_rec.codmat::varchar;
        end if;

        INSERT INTO prodmat ( CODMAT, CODPRODCOMP, CODOBIECT, CANT, PRET, PRETV, D1, D2, D3, CopyD1, CopyD2, CopyD3,
                              Indexlocal, CantUM1, CodProdGest, Tip, Obs, codatribut, adddim, adddim_transp,
                              pretorig, ProcReal, Valoare, CodReteta, CodMan, ETAPA, PRINCIPAL, CONSUM)
        values (vCodMat, RecId, v_rec.CODOBIECT, v_rec.CANT, v_Rec.PRET, v_Rec.PRETV, v_Rec.D1, v_Rec.D2, v_Rec.D3,
                v_Rec.CopyD1, v_Rec.CopyD2, v_Rec.CopyD3, v_rec.IndexLocal, v_rec.CantUM1, v_rec.CodProdGest,
                v_Rec.Tip, v_rec.Obs, v_rec.codatribut, v_rec.adddim, v_rec.adddim_transp, v_rec.pretorig,
                v_rec.ProcReal, v_rec.Valoare, v_rec.CodReteta, v_rec.CodMan, V_REC.ETAPA, V_REC.PRINCIPAL, V_REC.CONSUM);

        for v_tmp in (SELECT pn.CODPROIECTNOD, pn.CODPROIECT, pn.CANT, pn.NODORIGINAL, pn.POZITIE, pn.CODRETETA, pn.TIP,
                             pn.CODOBIECT, pn.INDEXPARINTE, pn.CODPRODMAT, pn.NIVEL, pn.ORDINE, coalesce(pnm.maxpoz, 1) MAXPOZ
                      FROM proiectnod pn
                         left join (SELECT max(pozitie) + 1 MAXPOZ, nodoriginal FROM proiectnod group BY nodoriginal
                                   ) pnm ON pnm.nodoriginal = pn.codproiectnod
                      WHERE pn.codreteta = recid
                     )
        loop
          SELECT cant INTO aCant FROM tmp_prodcomp;

          INSERT INTO proiectnod ( codproiectnod, codproiect, cant, nodoriginal, pozitie, codreteta, tip, codobiect,
                                   indexparinte, codprodmat, nivel, ordine )
          values ( nextval('SEQ_PROIECTNOD_CODPROIECTNOD'), v_tmp.codproiect, v_tmp.cant / aCant * v_rec.cant,
                   v_tmp.codproiectnod, v_tmp.maxpoz, 0,
                   CASE when v_rec.tip in (3, 4) then 3
                        when v_rec.tip = 5 then 5
                        else 1
                   END ,
                   v_rec.codobiect,
                   trim(coalesce(v_tmp.indexparinte, ''))||'.'||COALESCE(lpad(to_char(v_tmp.maxpoz), 2,'0'), ''),
                   vCodMat, v_tmp.nivel + 1, 0 );
        end loop;
      end if;
    end loop;

    DELETE FROM prodmatechiv pe
    WHERE pe.codprodcomp = RecId and not exists (SELECT tmp.CodMatEchiv FROM tmp_prodmatechiv tmp WHERE tmp.codmatechiv = pe.codmatechiv );

    for v_rec in (SELECT * FROM tmp_prodmatechiv ) loop
      if v_Rec.codmatechiv &gt; 0 then
        UPDATE prodmatechiv
        SET
          codobiect = v_Rec.Codobiect,
          paritate  = v_Rec.paritate,
          ordine    = v_rec.ordine
        WHERE
          codmatechiv = v_Rec.codmatechiv ;
      else
        INSERT INTO prodmatechiv ( codmatechiv, codprodcomp, codmat, codobiect, paritate, ordine )
        values ( nextval('SEQ_PRODMATECHIV_CODMATECHIV'), RecId, v_rec.CodMat, v_rec.CodObiect, v_Rec.Paritate, v_Rec.Ordine );
      end if;
    end loop;

    DELETE FROM prodrez pr
    WHERE pr.codprodcomp = RecId and not exists (SELECT tmp_Pr.codrez FROM tmp_prodrez tmp_pr WHERE tmp_pr.codrez = pr.codrez );

    for v_rec in (SELECT * FROM tmp_prodrez ) loop
      if v_Rec.Codrez &gt; 0 then
        UPDATE prodrez
        SET
          CODOBIECT   = v_rec.CODOBIECT,
          CANT        = v_rec.cant,
          PRET        = v_rec.pret,
          D1          = v_rec.d1,
          D2          = v_rec.d2,
          D3          = v_rec.d3,
          IndexLocal  = v_rec.indexlocal,
          Reziduu     = v_rec.reziduu,
          CantUM1     = v_rec.CantUM1,
          CodProdGest = v_Rec.Codprodgest,
          Obs         = v_rec.Obs
        WHERE
          codrez = v_rec.codrez ;
      else
        INSERT INTO prodrez ( CODREZ, CODPRODCOMP, CODOBIECT, CANT, PRET, D1, D2, D3, IndexLocal, Reziduu, CantUM1, CODPRODGEST, Obs )
        values ( nextval('SEQ_PRODREZ_CODREZ'), RecId, v_rec.CODOBIECT, v_rec.CANT, v_Rec.PRET, v_Rec.D1, v_Rec.D2, v_Rec.D3,
                 v_Rec.IndexLocal, v_Rec.Reziduu, v_rec.CantUM1, v_rec.CodProdGest, v_rec.Obs );
      end if;
    end loop;

    DELETE FROM tmp_prodmas
    WHERE coalesce(codprodgest, 0) = 0
      and descriere is null
      and frecventa is null
      and metoda is null
      and coalesce(codobiect, 0) = 0;

    DELETE FROM prodmas ps
    WHERE ps.codprodcomp = RecId and not exists (SELECT tmp_Ps.codprodmas FROM tmp_prodmas tmp_ps WHERE tmp_ps.codprodmas = ps.codprodmas );

    for v_rec in (SELECT * FROM tmp_prodmas ) loop
      if v_Rec.CodProdMas &gt; 0 then
        UPDATE prodmas
        SET
          descriere  = v_Rec.Descriere,
          frecventa  = v_rec.frecventa,
          metoda     = v_Rec.Metoda,
          codobiect  = v_Rec.Codobiect,
          indexlocal = v_Rec.Indexlocal
        WHERE
          codprodmas = v_rec.codprodmas ;
      else
        INSERT INTO prodmas ( codprodmas, codprodcomp, descriere, frecventa, metoda, codobiect, indexlocal )
        values ( nextval('SEQ_PRODMAS_CODPRODMAS'), RecId, v_Rec.descriere, v_Rec.frecventa, v_Rec.metoda, v_Rec.codobiect, v_rec.indexlocal );
      end if;
    end loop;

    DELETE FROM prodsdv sdv WHERE sdv.codprodcomp = recid and codprodsdv not in (SELECT codprodsdv FROM tmp_prodsdv );

    for v_rec in (SELECT * FROM tmp_prodsdv ) loop
      if v_Rec.Codprodsdv &gt; 0 then
        UPDATE prodsdv
        set
          CODPRODMAN = v_Rec.Codprodman,
          INDEXLOCAL = v_Rec.Indexlocal,
          CODSDV     = v_Rec.Codsdv,
          CODGENERIC = v_Rec.Codgeneric,
          CANT       = v_Rec.Cant,
          PRET       = v_Rec.Pret
        where
          codprodsdv = v_rec.codprodsdv ;
      else
        INSERT INTO prodsdv ( codprodsdv, codprodman, indexlocal, codsdv, codgeneric, cant, pret, codprodcomp )
        values ( nextval('SEQ_PRODSDV_CODPRODSDV'), v_Rec.codprodman, v_Rec.indexlocal, v_Rec.codsdv, v_Rec.codgeneric, v_Rec.cant, v_Rec.pret, RecId );
      end if;
    end loop;

    DELETE FROM normemat nmat WHERE nmat.codprodcomp = recid and codnormemat not in (SELECT codnormemat FROM tmp_normemat );
    DELETE FROM prodnorme nor WHERE nor.codprodcomp  = recid and codnorma    not in (SELECT codnorma    FROM tmp_prodnorme );

    for v_rec in (SELECT * FROM tmp_prodnorme ) loop
      if v_Rec.CodNorma &gt; 0 then
        UPDATE prodnorme
        SET
          norma       = v_Rec.norma,
          indexlocal  = v_rec.indexlocal,
          implicit    = v_rec.implicit,
          ACTIV       = V_REC.ACTIV,
          DATAACTIV   = V_REC.DATAACTIV,
          DATAINACTIV = V_REC.DATAINACTIV
        WHERE
          codnorma = v_rec.codnorma ;
      else
        SELECT  nextval('SEQ_PRODNORME_CODNORMA') INTO vCod;

        UPDATE tmp_normemat SET codnorma = vcod WHERE codnorma = v_rec.codnorma ;

        INSERT INTO prodnorme ( codnorma, codprodcomp, norma, indexlocal, implicit, activ, dataactiv, datainactiv )
        values ( vCod, RecId, v_rec.norma, v_rec.indexlocal, v_rec.implicit, v_rec.activ, v_rec.dataactiv, v_rec.datainactiv );
      end if;
    end loop;

    for v_rec in (SELECT * FROM tmp_normemat ) loop
      if v_Rec.Codnormemat &gt; 0 then
        UPDATE normemat
        SET
          codnorma    = v_rec.codnorma,
          codprodcomp = v_rec.codprodcomp,
          codobiect   = v_rec.codobiect,
          cant        = v_rec.cant,
          pret        = v_rec.pret,
          d1          = v_rec.D1,
          d2          = v_rec.D2,
          d3          = v_rec.D3,
          indexlocal  = v_rec.Indexlocal,
          cantum1     = v_rec.cantum1,
          codmat      = v_rec.codmat
        WHERE
          codnormemat = v_rec.codnormemat ;
      else
        INSERT INTO normemat ( codnormemat, codnorma, codprodcomp, codobiect, cant, pret, D1, D2, D3, indexlocal, cantum1, codmat )
        values ( nextval('SEQ_NORMEMAT_CODNORMEMAT'), v_Rec.codnorma, recid, v_rec.codobiect, v_rec.cant, v_rec.pret, v_rec.d1, v_rec.d2, v_rec.d3, v_rec.indexlocal, v_rec.cantum1, v_rec.codmat );
      end if;
    end loop;
  ELSE   --insert
    vcod := recid;
    SELECT nextval('SEQ_PRODCOMP_CODPRODCOMP') INTO RecId;
    PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('PRODCOMP', RecId);

    if vcod &gt; 0 then
    --propag arhiva
      insert into documente(coddocument,
                            coddoc,
                            tipdoc,
                            filename,
                            doc,
                            obs,
                            userid,
                            datacreare,
                            coddosar,
                            coddepozit,
                            tipdocument)
      select
                            nextval('seq_documente_coddocument'),
                            RecId,
                            tipdoc,
                            filename,
                            doc,
                            obs,
                            userid,
                            datacreare,
                            coddosar,
                            coddepozit,
                            tipdocument
      from documente where coddoc = vcod and tipdoc = 504;
    end if;

    SELECT 'OBJ:' || coalesce(DEN_OBIECT, '') || ' VER:' || coalesce(OBS, '') || ' (' || coalesce(RecId::varchar , '') || ')'
    INTO ADOC
    FROM TMP_PRODCOMP;

    if (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT
        FROM   PKG_USERFIRME_ValidPostLog(null,
                                          current_setting('PKG_GLOBALS.USERID', true)::numeric,
                                          current_setting('PKG_PRODCOMP.CT_MONITOR', true))
       )
    then
      perform pkg_userfirme_postlogcucommit('PRODCOMP',
                                            current_setting('PKG_GLOBALS.USERNAME', true),
                                            'A',
                                            RECID,
                                            current_setting('PKG_GLOBALS.FIRMANAME', true),
                                            current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric,
                                            aDataDoc,
                                            aDoc,
                                            null,
                                            current_setting('PKG_GLOBALS.EXE_VERSION', true));
    end if;

    INSERT INTO PRODCOMP ( CodProdComp, CODOBIECT, HFactor, OBS, data, ANULAT, BLOCAT, OPERAT, CANT, D1, D2, D3,
                           TIPRETETA, CANTUM1, COEFINDIRECTE, PRET, implicit, DESCRIERE, INACTIV, GEST, IDENTIFICATOR,
                           DATADOCUMENTATIE, ARHIVA, OBSERVATII, PROIECTANT, CodClasaProd, Invizibila, TipPret,
                           GENERIC, durata, userid, Datacreare, valmat, valman, valregie, Obs1, Obs2, Obs3, Obs4, Obs5, Obs6,
                           Codmoneda, Pretvaluta, AG, ValAG, Profit, ValProfit, PretFinal, VALPROFITV, PRETFINALV,
                           TOTPRETCOEF, TOTPRETFIX, TOTPRETCOEFV, TOTPRETFIXV, valregieman, nohfactor )
    (SELECT RecId, CODOBIECT, HFactor, OBS, data, ANULAT, BLOCAT, OPERAT, CANT, D1, D2, D3, TIPRETETA, CANTUM1, COEFINDIRECTE,
            PRET, implicit, DESCRIERE, INACTIV, GEST, IDENTIFICATOR, DATADOCUMENTATIE, ARHIVA, OBSERVATII, PROIECTANT,
            CodClasaProd, Invizibila, TipPret, GENERIC, durata, current_setting('PKG_GLOBALS.USERID', true)::numeric, current_timestamp,
            valmat, valman, valregie, Obs1, Obs2, Obs3, Obs4, Obs5, Obs6, CodMoneda, PretValuta, AG, ValAG, Profit,
            ValProfit, PretFinal, VALPROFITV, PRETFINALV, TOTPRETCOEF, TOTPRETFIX, TOTPRETCOEFV, TOTPRETFIXV, valregieman, nohfactor
    FROM tmp_PRODCOMP );

    for v_Rec in (SELECT * FROM tmp_prodgest ) loop
      SELECT nextval('SEQ_PRODGEST_CODPRODGEST') INTO vCodProdGest;

      INSERT INTO PRODGEST ( CODPRODGEST, CODPRODCOMP, INDEXLOCAL, CODGEST, COEFMAT, COEFMAN, TIMPEST )
      values ( vCodProdGest, RecId, v_Rec.INDEXLOCAL, v_Rec.CODGEST, v_rec.CoefMat, v_rec.CoefMan, V_REC.TIMPEST );

      UPDATE tmp_prodmat SET codprodgest = vCodProdGest WHERE codprodgest = v_rec.codprodgest ;
      UPDATE tmp_prodman SET codprodgest = vCodProdGest WHERE codprodgest = v_rec.codprodgest ;
      UPDATE tmp_prodrez SET codprodgest = vCodProdGest WHERE codprodgest = v_rec.codprodgest ;
    end loop;

    for v_Rec in (SELECT * FROM tmp_prodman ) loop
      SELECT nextval('SEQ_PRODMAN_CODMAN') INTO vCodProdMan;

      UPDATE tmp_prodsdv SET codprodman = vCodProdMan WHERE codprodman = v_Rec.Codman ;
      UPDATE tmp_prodmat SET codman     = vCodProdMan WHERE codman     = v_Rec.Codman ;

      INSERT INTO PRODMAN ( CODMAN, CODPRODCOMP, NROP, CODOP, CODLOC, CODTARIF, TU, VALOARE, CODPRODGEST, DSV, BPS, TPI, OBS, Detalii, Fix, Nivel, Decalaj, INCEPERE)
      values ( vCodProdMan, RecId, v_Rec.NROP, v_Rec.CODOP, v_Rec.CODLOC, v_Rec.CODTARIF, v_Rec.TU, v_Rec.VALOARE, v_Rec.CODPRODGEST, v_rec.DSV, v_rec.BPS,
               coalesce(v_rec.TPI, 0), v_rec.OBS, v_rec.Detalii, v_rec.Fix, v_rec.NROP, v_rec.decalaj, v_rec.incepere);
    end loop;

    for v_rec in (SELECT * FROM tmp_prodmat ) loop
      vCodMat := nextval('SEQ_PRODMAT_CODMAT');

      UPDATE tmp_prodmatechiv SET codmat = vCodMat WHERE CodMat = v_rec.CodMat ;
      UPDATE tmp_normemat     SET codmat = vCodMat WHERE CodMat = v_rec.codmat ;

      INSERT INTO PRODMAT ( CODMAT, CODPRODCOMP, CODOBIECT, CANT, PRET, PRETV, D1, D2, D3, CopyD1, CopyD2, CopyD3, IndexLocal, CantUM1, CodProdGest,
                            Tip, Obs, codatribut, adddim, adddim_transp, pretorig, ProcReal, Valoare, CodReteta, CodMan, ETAPA, PRINCIPAL, CONSUM )
      values ( vCodMat, RecId, v_rec.CODOBIECT, v_rec.CANT, v_rec.PRET, v_rec.PRETV, v_rec.D1, v_rec.D2, v_rec.D3,
               v_rec.CopyD1, v_rec.CopyD2, v_rec.CopyD3, v_rec.IndexLocal, v_rec.CantUM1, v_rec.CodProdGest, v_rec.Tip,
               v_rec.Obs, v_rec.codatribut, v_rec.adddim, v_rec.adddim_transp, v_rec.pretorig, v_rec.ProcReal, v_rec.Valoare,
               v_rec.CodReteta, v_rec.CodMan, V_REC.ETAPA, V_REC.PRINCIPAL, V_REC.CONSUM);
    end loop;

    INSERT INTO prodmatechiv ( codmatechiv, codprodcomp, codmat, codobiect, paritate, ordine )
    SELECT nextval('SEQ_PRODMATECHIV_CODMATECHIV'), RecId, CodMat, CodObiect, Paritate, Ordine
    FROM tmp_prodmatechiv;

    INSERT INTO PRODREZ ( CODREZ, CODPRODCOMP, CODOBIECT, CANT, PRET, D1, D2, D3, IndexLocal, Reziduu, CantUM1, CodProdGest, Obs )
    (SELECT nextval('SEQ_PRODREZ_CODREZ'), RecId, CODOBIECT, CANT, PRET, D1, D2, D3, IndexLocal, Reziduu, CantUM1, CodProdGest, Obs
     FROM tmp_PRODREZ );

    DELETE FROM tmp_prodmas
    WHERE
        coalesce(codprodgest, 0) = 0
        and descriere is null
        and frecventa is null
        and metoda is null
        and coalesce(codobiect, 0) = 0;

    INSERT INTO prodmas ( codprodmas, codprodcomp, descriere, frecventa, metoda, codobiect, indexlocal )
    SELECT nextval('SEQ_PRODMAS_CODPRODMAS'), RecId, descriere, frecventa, metoda, codobiect, indexlocal
    FROM tmp_prodmas;

    INSERT INTO prodsdv ( codprodsdv, codprodman, indexlocal, codsdv, codgeneric, cant, pret, codprodcomp )
    SELECT nextval('SEQ_PRODSDV_CODPRODSDV'), codprodman, indexlocal, codsdv, codgeneric, cant, pret, RecId
    FROM tmp_prodsdv;

    for v_rec in (SELECT * FROM tmp_prodnorme ) loop
      SELECT nextval('SEQ_PRODNORME_CODNORMA') INTO vCod;

      UPDATE tmp_normemat SET codnorma = vcod WHERE codnorma = v_rec.codnorma ;

      INSERT INTO prodnorme ( codnorma, codprodcomp, norma, indexlocal, implicit, activ, dataactiv, datainactiv )
      values ( vCod, recid, v_rec.norma, v_rec.indexlocal, v_rec.implicit, v_rec.activ, v_rec.dataactiv, v_rec.datainactiv );
    end loop;

    INSERT INTO normemat ( codnormemat, codnorma, codprodcomp, codobiect, cant, pret, D1, D2, D3, indexlocal, cantum1, codmat )
    SELECT nextval('SEQ_NORMEMAT_CODNORMEMAT'), codnorma, recid, codobiect, cant, pret, D1, D2, D3, indexlocal, cantum1, codmat
    FROM tmp_normemat;

    if fnc_GetValConstantaLucru('DoNormaImp') = '1' then
      SELECT count(*) INTO aCount FROM prodnorme WHERE implicit = 1 and codprodcomp = recid;

      if aCount = 0 then
        SELECT nextval('SEQ_PRODNORME_CODNORMA') INTO vCod;

        INSERT INTO prodnorme ( codnorma, codprodcomp, norma, indexlocal, implicit, activ, dataactiv )
        values ( vCod, recid, 'Optima',
                 (SELECT max(indexlocal) + 1 FROM prodnorme WHERE codprodcomp = recid ),
                 1, 1, to_date(to_char(current_timestamp, 'dd.mm.yyyy'), 'dd.mm.yyyy') );

        INSERT INTO normemat ( codnormemat, codnorma, codprodcomp, codobiect, cant, pret, D1, D2, D3, indexlocal, cantum1, codmat )
        SELECT nextval('SEQ_NORMEMAT_CODNORMEMAT'), vcod, recid, codobiect, cant, pret, D1, D2, D3, indexlocal, cantum1, codmat
        FROM prodmat WHERE codprodcomp = recid;
      end if;
    end if;

    if fnc_GetValConstantaLucru('InactivGenProdComp') = '1' then
      UPDATE prodcomp
      SET inactiv = 1
      WHERE codobiect = (SELECT codobiect FROM prodcomp WHERE codprodcomp = recid ) and codprodcomp &lt;&gt; recid ;

      SELECT count(*) INTO aCount FROM prodcomp
      WHERE codobiect = (SELECT codobiect FROM prodcomp WHERE codprodcomp = recid )
        and codprodcomp &lt;&gt; recid
        and implicit = 1;

      if aCount &gt; 0 then
        UPDATE prodcomp SET implicit = 1 WHERE codprodcomp = recid ;
        UPDATE prodcomp SET implicit = 0 WHERE codobiect = (SELECT codobiect FROM prodcomp WHERE codprodcomp = recid ) and codprodcomp &lt;&gt; recid ;
      end if;

      SELECT count(*) INTO aCount FROM prodcomp
      WHERE codobiect = (SELECT codobiect FROM prodcomp WHERE codprodcomp = recid )
        and codprodcomp &lt;&gt; recid
        and generic = 1;

      if aCount &gt; 0 then
        UPDATE prodcomp SET generic = 1 WHERE codprodcomp = recid ;
        UPDATE prodcomp SET generic = 0 WHERE codobiect = (SELECT codobiect FROM prodcomp WHERE codprodcomp = recid ) and codprodcomp &lt;&gt; recid ;
      end if;
    end if;

    if aClonare &gt; 0 then
      UPDATE prodcomp SET codutilizare = aCodUtilizare WHERE codprodcomp = RecID ;

      for v_rec in (SELECT pn.CODPROIECTNOD, pn.CODPROIECT, pn.CANT, pn.INDEXPARINTE, pn.NIVEL
                    FROM proiectnod pn inner join proiect p ON p.codproiect = pn.codproiect
                    WHERE coalesce(p.ascuns, 0) = 0 and pn.codreteta = aCodUtilizare
                   )
      loop
        for v_tmp in (SELECT mat.*, pn.codproiectnod, pn.indexparinte, pn.cant CANTNOD
                      FROM (SELECT coalesce(mv.codmat, 0) CODMATVECHI, coalesce(mn.codmat, 0) CODMATNOU, mv.codobiect,
                                   mn.codobiect CODOBIECTNOU, mn.cant, mn.indexlocal, mv.tip, mn.tip TIPNOU
                            FROM (SELECT * FROM prodmat WHERE codprodcomp = aCodUtilizare ) mv
                                 full join
                                 (SELECT * FROM prodmat WHERE codprodcomp = RecID ) mn ON mv.indexlocal = mn.indexlocal
                           ) mat
                           left join proiectnod pn ON pn.codprodmat = mat.codmatvechi and pn.codproiect = v_rec.codproiect
                                                      and pn.nodoriginal = v_rec.codproiectnod
                      ORDER BY mat.indexlocal
                     )
        loop
          if v_tmp.codmatvechi &gt; 0 and v_tmp.codmatnou &gt; 0 then
            if ( v_tmp.codobiect &lt;&gt; v_tmp.codobiectnou) or ( v_tmp.tip &lt;&gt; v_tmp.tipnou) then
              DELETE FROM proiectnod pn
              WHERE instr(pn.indexparinte, v_tmp.IndexParinte) &gt; 0
                and pn.codproiectnod &lt;&gt; v_tmp.codproiectnod
                and pn.codproiect = v_rec.codproiect;

              UPDATE proiectnod
              SET
                codobiect  = v_tmp.codobiectnou,
                codprodmat = v_tmp.codmatnou
              WHERE
                codproiectnod = v_tmp.codproiectnod ;

              UPDATE proiectnod
              SET
                cant = CASE when v_tmp.tip = 5 then v_tmp.cant else v_rec.cant * v_tmp.Cant / aCant END
              WHERE
                  codproiectnod = v_tmp.codproiectnod ;
            else
              UPDATE proiectnod pn
              SET
                cant = CASE when v_tmp.tip = 5 then v_tmp.cant else v_rec.cant * v_tmp.Cant / aCant end ,
                tip  = CASE when v_tmp.tip in (1, 2) then 1
                            when v_tmp.tip = 5       then 5
                            else 3
                       END  ,
                codprodmat = v_tmp.codmatnou
              WHERE
                    pn.codproiectnod = v_tmp.codproiectnod ;

              for v_xxx in (SELECT pn.codproiectnod, pp.cant CANTPARINTE, pc.cant CANTRETETA, mat.cant CANTMATERIAL
                            FROM proiectnod pn
                                inner join proiectnod pp  ON pp.codproiectnod = pn.nodoriginal
                                inner join prodmat    mat ON mat.codmat       = pn.codprodmat
                                inner join prodcomp   pc  ON pc.codprodcomp   = mat.codprodcomp
                            WHERE
                              instr(pn.indexparinte, v_tmp.IndexParinte) &gt; 0
                              and pn.codproiectnod &lt;&gt; v_tmp.codproiectnod
                              and pn.codproiect = v_rec.codproiect )
              loop
                UPDATE proiectnod SET cant = v_xxx.cantparinte * v_xxx.cantmaterial / v_xxx.cantreteta WHERE codproiectnod = v_xxx.codproiectnod ;
              end loop;
            end if;
          end if;

          if v_tmp.codmatnou = 0 and v_tmp.codmatvechi &gt; 0 then
            DELETE FROM proiectnod pn WHERE instr(pn.indexparinte, v_tmp.IndexParinte) &gt; 0 and pn.codproiect = v_rec.codproiect;
          end if;

          if v_tmp.codmatnou &gt; 0 and v_tmp.codmatvechi = 0 then
            INSERT INTO proiectnod ( codproiectnod, codproiect, cant, nodoriginal, pozitie, codreteta, tip, codobiect, indexparinte, codprodmat, nivel, ordine )
            values ( nextval('SEQ_PROIECTNOD_CODPROIECTNOD'), v_rec.codproiect,
                     CASE when v_tmp.tip = 5 then v_tmp.cant else v_rec.cant * v_tmp.Cant / aCant end ,
                     v_rec.codproiectnod, v_tmp.indexlocal, 0,
                     CASE when v_tmp.tip in (1, 2) then 1
                          when v_tmp.tip = 5       then 5
                          else 3
                     END ,
                     v_tmp.codobiectnou,
                     trim(coalesce(v_rec.indexparinte, '')) || '.' || coalesce(lpad(v_tmp.indexlocal::varchar, 2, '0'), ''),
                     v_tmp.codmatnou, v_rec.nivel + 1, v_tmp.indexlocal );
          end if;
        end loop;

        UPDATE proiectnod SET codreteta = RecID   WHERE codproiectnod = v_rec.codproiectnod ;
        UPDATE proiect    SET codutilizare = NULL WHERE codproiect    = v_rec.codproiect ;
      end loop;
    end if;
  end if;

--  IF NOT fnc_getValConstantaLucru('CalculDurata')::NUMERIC IN (1,3) THEN
--    for v_rec in (SELECT * FROM tmp_prodman ) loop
--      UPDATE prodcomp
--      SET
--      durata = (SELECT round((sum(coalesce(man.tpi, 0) + PC.Cant / case when coalesce(man.bps, 0)= 0 then 1 else man.bps end * coalesce(TUMAX.TU, 0)))::numeric, 2)
--                FROM (SELECT distinct nrop, codman, codprodcomp, max(tu) TU
--                      FROM prodman
--                      GROUP BY nrop, codman, codprodcomp
--                     ) TUMAX
--                    inner join prodcomp PC ON tumax.codprodcomp = pc.codprodcomp
--                    inner join prodman man ON tumax.codman = man.codman and man.codprodcomp = tumax.codprodcomp
--                WHERE pc.codprodcomp = recid
--               )
--      WHERE codprodcomp = recid ;
--
--      exit ;
--    end loop;
--  END IF;

  for v_rec in (SELECT ROW_NUMBER() OVER() INDEXLOCAL, pm.codmat
                FROM (SELECT codmat FROM prodmat WHERE codprodcomp = RecId order BY indexlocal ) pm
               )
  loop
    UPDATE prodmat SET indexlocal = v_rec.indexlocal WHERE codmat = v_rec.codmat ;
  end loop;

  UPDATE prodcomp
  SET
    generic  = 0,
    implicit = 0
  WHERE
    codprodcomp = recid and coalesce(anulat, 0) = 1 ;

  PERFORM pkg_prodcomp_PropagaGant(RecID);
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS(504);

  perform NotifyModif(Operation, RecId, 'PRODCOMP');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_updatecodretetamat</obj_name>
  <obj_hashval>9e2e8f3cfd640b230f875917a74a1092</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_updatecodretetamat()
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodProdComp NUMERIC(20);
  v_rec record;
BEGIN
  --Florin 16.05.2022 - sinc. Oracle (13.05.2022)
  --Florin 28.03.2022
  for v_rec in (select * from tmp_manevra_liste where filtru = 'CODMAT') LOOP
    aCodProdComp := 0;
    BEGIN
      select codprodcomp into aCodProdComp from prodcomp where trim(obs) = trim(v_rec.filtru1) and coalesce(ascuns,0) = 0;
    exception when others then
      aCodProdComp := 0;
    end;
    if aCodProdComp &gt; 0 then
      update prodmat set codreteta = aCodProdComp where codmat = v_rec.valoare;
    end if;
  end loop;
 END;
 $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_updatenartobj1bytipcont</obj_name>
  <obj_hashval>c71e2c55397530994f40036611861424</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_updatenartobj1bytipcont(aan numeric, aluna numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Adina 12.03.2021 - prc_al_refresh
  FOR v_rec IN (SELECT obj1.*, cont.simbol
                FROM  nartobj1 obj1
                      INNER JOIN nartobj       obj  ON  obj.codobiect  = obj1.codobiect
                      LEFT  JOIN nartimplicite imp  ON  obj.codarticol = imp.codarticol and  imp.codsubunit = 2
                      LEFT  JOIN ioart1        ioa1 ON  ioa1.codioart  = imp.contimplicit
                      LEFT  JOIN ncont         cont ON  cont.codcont   = ioa1.cont
                WHERE aAn*12+aLuna BETWEEN obj1.alstart AND obj1.alstop
                  and aAn*12+aLuna BETWEEN ioa1.alstart AND ioa1.alstop
                ORDER BY obj1.codobiect
              )
  LOOP
    IF  v_rec.simbol = '341' THEN
      IF  v_Rec.anstart * 12 + v_Rec.lunastart &lt;&gt; aAn * 12 + aLuna THEN
        INSERT INTO nartobj1(codobiect1, codobiect, pretmaximal, procadaosmaximal, adaosla, anstart, lunastart, tippretmax, compensat, tipcompensare, pretreferinta, grupa, uplift, codmoneda, puncte, umiditate, corpuri_straine, incoltit, hectolitrica, gluten, fuzaritate, cadere, deformare, sticlozitate, sparturi, punctesectie, tippret)
        VALUES(NEXTVAL('SEQ_NARTOBJ1_CODOBIECT1'), v_Rec.codobiect, v_Rec.pretmaximal, v_Rec.procadaosmaximal, v_Rec.adaosla, aAn, aLuna, v_Rec.tippretmax, v_Rec.compensat, v_Rec.tipcompensare, v_rec.pretreferinta, v_Rec.grupa, v_Rec.uplift, v_Rec.codmoneda, v_Rec.puncte, v_Rec.umiditate, v_Rec.corpuri_straine, v_Rec.incoltit, v_Rec.hectolitrica, v_Rec.gluten, v_Rec.fuzaritate, v_Rec.cadere, v_Rec.deformare, v_Rec.sticlozitate, v_Rec.sparturi, v_Rec.punctesectie, 2);
        CALL prc_al_refresh('nartobj1', v_Rec.codobiect);
      ELSE
        UPDATE nartobj1 SET tippret = 2 WHERE codobiect1 = v_Rec.codobiect1;
      END IF;
    END IF;

    IF  v_rec.simbol = '345' THEN
      IF  v_Rec.anstart * 12 + v_Rec.lunastart &lt;&gt; aAn * 12 + aLuna THEN
        INSERT INTO nartobj1(codobiect1, codobiect, pretmaximal, procadaosmaximal, adaosla, anstart, lunastart, tippretmax, compensat, tipcompensare, pretreferinta, grupa, uplift, codmoneda, puncte, umiditate, corpuri_straine, incoltit, hectolitrica, gluten, fuzaritate, cadere, deformare, sticlozitate, sparturi, punctesectie, tippret)
        VALUES(NEXTVAL('SEQ_NARTOBJ1_CODOBIECT1'), v_Rec.codobiect, v_Rec.pretmaximal, v_Rec.procadaosmaximal, v_Rec.adaosla, aAn, aLuna, v_Rec.tippretmax, v_Rec.compensat, v_Rec.tipcompensare, v_rec.pretreferinta, v_Rec.grupa, v_Rec.uplift, v_Rec.codmoneda, v_Rec.puncte, v_Rec.umiditate, v_Rec.corpuri_straine, v_Rec.incoltit, v_Rec.hectolitrica, v_Rec.gluten, v_Rec.fuzaritate, v_Rec.cadere, v_Rec.deformare, v_Rec.sticlozitate, v_Rec.sparturi, v_Rec.punctesectie, 1);
        CALL prc_al_refresh('nartobj1', v_Rec.codobiect);
      ELSE
        UPDATE nartobj1 SET tippret = 1 WHERE codobiect1 = v_Rec.codobiect1;
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_vallret</obj_name>
  <obj_hashval>8e8944c6e1e9367d7bc7e942abbfc20d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_vallret(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PRODCOMP.vAllRet', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_vcodmat</obj_name>
  <obj_hashval>ae6ec8ab29bd4f5678dfe0a4c40705c6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_vcodmat(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PRODCOMP.vCodMat', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_checkextprjascunse</obj_name>
  <obj_hashval>6deed1d88c5ea062f1160a6afe6117bd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_checkextprjascunse()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  IF  (fnc_TmpExists('PROIECTEXT')) = 1 THEN
    PERFORM PKG_PROIECT_CurataExtAcunse();
    PERFORM PKG_PROIECT_CorectExtUnic();
    PERFORM PKG_PROIECT_CheckTmpExt();

    FOR v_rec IN (SELECT p.codproiect, pi.codproiect CODPROIECTI
                  FROM proiect p INNER JOIN proiect pi ON  p.codutilizare = pi.codproiect
                  WHERE p.codutilizare &gt; 0
                 )
    LOOP
      PERFORM PKG_PROIECT_CheckExtPrj(v_rec.CodProiect, v_rec.CodProiectI);
    END LOOP;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_genretetanoua</obj_name>
  <obj_hashval>96fdd291f8a14503ce1e912843ea3537</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_genretetanoua(acodproiectnod numeric, acodprodcomp numeric, acodobiect numeric, aobs character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  vCodProdComp numeric;
  vCodProdGest numeric;
  vCodMat      numeric;
begin
  SELECT NEXTVAL('SEQ_PRODCOMP_CODPRODCOMP') INTO vCodProdComp;

  FOR v_rec IN (SELECT pc.* FROM prodcomp pc WHERE pc.codprodcomp = aCodProdComp) LOOP
    INSERT INTO prodcomp(codprodcomp, codobiect, obs, data, anulat, blocat, operat, cant, pret, coefindirecte, implicit, descriere, inactiv, gest, identificator, datadocumentatie, arhiva, observatii, proiectant, codclasaprod, invizibila, generic, durata, userid, datacreare, hfactor, valmat, valman, valregie, tippret, obs1, obs2, obs3, obs4, obs5, obs6, codmoneda, pretvaluta, ag, valag, profit, valprofit, pretfinal, valprofitv, pretfinalv, totpretcoef, totpretfix, totpretcoefv, totpretfixv, valregieman)
    VALUES(vCodProdComp, acodobiect, aobs, v_rec.data, v_rec.anulat, v_rec.blocat, v_rec.operat, v_rec.cant, v_rec.pret, v_rec.coefindirecte, v_rec.implicit, v_rec.descriere, v_rec.inactiv, v_rec.gest, v_rec.identificator, v_rec.datadocumentatie, v_rec.arhiva, v_rec.observatii, v_rec.proiectant, v_rec.codclasaprod, v_rec.invizibila, v_rec.generic, v_rec.durata, v_rec.userid, v_rec.datacreare, v_rec.hfactor, v_rec.valmat, v_rec.valman, v_rec.valregie, v_rec.tippret, v_rec.obs1, v_rec.obs2, v_rec.obs3, v_rec.obs4, v_rec.obs5, v_rec.obs6, v_rec.codmoneda, v_rec.pretvaluta, v_rec.ag, v_rec.valag, v_rec.profit, v_rec.valprofit, v_rec.pretfinal, v_rec.valprofitv, v_rec.pretfinalv, v_rec.totpretcoef, v_rec.totpretfix, v_rec.totpretcoefv, v_rec.totpretfixv, v_rec.valregieman);

    EXIT ;
  END LOOP;

  SELECT NEXTVAL('SEQ_PRODGEST_CODPRODGEST') INTO vCodProdGest;

  FOR v_rec IN (SELECT pg.* FROM prodgest PG WHERE pg.codprodcomp = aCodProdComp) LOOP
    INSERT INTO prodgest(codprodgest, codprodcomp, indexlocal, codgest, coefmat, coefman)
    VALUES(vCodProdGest, vCodProdComp, v_rec.indexlocal, v_rec.codgest, v_rec.coefmat, v_rec.coefman);

    EXIT ;
  END LOOP;

  FOR v_rec IN (SELECT mat.* FROM prodmat mat WHERE mat.codprodcomp = aCodProdComp) LOOP
    SELECT NEXTVAL('SEQ_PRODMAT_CODMAT') INTO vCodMat;

    INSERT INTO prodmat(codmat, codprodcomp, codobiect, cant, pret, d1, d2, d3, indexlocal, cantum1, codprodgest, tip, codatribut, valmat, valman, valregie, adddim, adddim_transp, pretorig, procreal, valoare, copyd1, copyd2, copyd3)
    VALUES(vCodMat, vCodProdComp, v_rec.codobiect, v_rec.cant, v_rec.pret, v_rec.d1, v_rec.d2, v_rec.d3, v_rec.indexlocal, v_rec.cantum1, vCodProdGest, v_rec.tip, v_rec.codatribut, v_rec.valmat, v_rec.valman, v_rec.valregie, v_rec.adddim, v_rec.adddim_transp, v_rec.pretorig, v_rec.procreal, v_rec.valoare, v_rec.copyd1, v_rec.copyd2, v_rec.copyd3);

    UPDATE proiectnod SET codprodmat = vCodMat WHERE codprodmat = v_rec.codmat and  nodoriginal = aCodProiectNod;
  END LOOP;

  UPDATE proiectnod SET codreteta = vCodProdComp WHERE codproiectnod = aCodProiectNod;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiectcrm_sp_insertrecord</obj_name>
  <obj_hashval>3784bfbb49d8f61e350f1dc67ad694b7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiectcrm_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_PROIECTCRM (CodProiectCRM) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_promo_sp_postrecords</obj_name>
  <obj_hashval>56da2609ab62c727d55f3338151086b9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_promo_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  VREC         RECORD;
  vRecNo       numeric := 0;
  vCod         numeric;
  vCodCadou    numeric;
  aCarnetDoc   numeric;
  aNrDoc       numeric;
  aCodSubunit  numeric;
  aDataStart   date;
  aDataEnd     date;
  aDoc         varchar;
  aCount       numeric;
  aTipPromotie numeric;
  aAmPrioritar numeric;
   aSyncPromoRetail varchar;
begin
  --Florin 01.06.2023 - monitor
  --Bogdan 02.03.2022 - 53337 - Promotii clienti - cantitatea maxima trebuie trecuta prin paritatea unitatii de masura de pe linie
  --Laura 22.10.2021 - sinc Oracle (21.10.2021)
  --Bogdan 11.10.2021 - corectie alias promopart si PKG_POSTRETAIL_MEMO_MODIF_PROMO_RETAIL
  --Florin 20.09.2021 - fixat 51401
  --Adina 23.06.2021 - sinc.Oracle din 22.06.2021 - s-a facut in Oracle ca in PG
  --Adina 07.06.2021 - sinc.Oracle din 03.06.2021
  --Adina 16.01.2021 - aranjat pt.verificare modificari de pe 15.01.2021
  --Florin23.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_promo_setct_monitor('MON_30');
  SELECT CodPromo, CarnetDoc, NrDoc, Subunitatea, DataStart, DataEnd,
         'PROMO' || coalesce(NrDoc::varchar,'') || '/' || coalesce(to_char(DataStart,'dd.mm.yyyy'),'') || '-' || coalesce(to_char(DataEnd,'dd.mm.yyyy'),''),
         TipPromotie
  INTO RecId, aCarnetDoc, aNrDoc, aCodSubunit, aDataStart, aDataEnd, aDoc, aTipPromotie
  FROM TMP_PROMO;

  DELETE FROM TMP_PROMO1CADOUSER
  WHERE CodCadou IN (SELECT CodCadou FROM TMP_PROMO1CADOU WHERE coalesce(TipLimita,0) &lt;&gt; 3);

  DELETE FROM TMP_PROMO1SER
  WHERE CodPromo1 IN (SELECT CodPromo1 FROM TMP_PROMO1 WHERE coalesce(TipLimita,0) &lt;&gt; 3);

  DELETE FROM TMP_PROMOSUB WHERE coalesce(SUBUNITATEA,0) = 0;

  DELETE FROM TMP_PROMOPART
  WHERE coalesce(CODCLASEP, 0) = 0 AND coalesce(PARTENER, 0) = 0;

  SELECT count(1) INTO aCount FROM TMP_PROMOSUB;

  IF aCount = 0 THEN
    UPDATE TMP_PROMO SET SUBUNITATEA = 1 ;
  ELSE
    UPDATE TMP_PROMO SET SUBUNITATEA = NULL;
  END IF;

  SELECT count(1) INTO aCount FROM TMP_PROMOPART;

  IF aCount = 0 THEN
    UPDATE TMP_PROMO SET PARTENER = 0 ;
  END IF;

  IF aTipPromotie &lt;&gt; 2 THEN
    UPDATE TMP_PROMOPART SET PRIORITAR = 0 ;
  ELSE
    UPDATE TMP_PROMOPART SET PRIORITAR = 0 WHERE coalesce( PARTENER, 0) = 0 ;
  END IF;

  SELECT max(Prioritar) INTO aAmPrioritar FROM TMP_PROMOPART;

  IF Operation = 0 THEN    -- UPDATE
    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT
        FROM PKG_USERFIRME_ValidPostLog(null, current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_PROMO.CT_MONITOR', true))
       )
    THEN
      PERFORM pkg_userfirme_postlogcucommit( 'PROMO', current_setting('PKG_GLOBALS.USERNAME', true), 'M', RECID,
                                     current_setting('PKG_GLOBALS.FIRMANAME', true),
                                     aCodSubunit, aDataStart, aDoc, null,
                                     (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(null, null))
                                   );
    END IF;

    UPDATE PROMO
    SET (CodPromo, TipDoc, Anulat, Blocat, Operat, CarnetDoc, SeriaDoc, NrDoc, DataStart, DataEnd, Partener,
         Moneda, TipPromotie, TipConditie, Obs, Subunitatea, TipClaseP, TipServire, DeMana, ValMin, Praguri,
         CantMin, ExclAltePromo, OraStart, OraStop, PRETCUAMANUNT
        )
      = (SELECT CodPromo, TipDoc, Anulat, Blocat, Operat, CarnetDoc, SeriaDoc, NrDoc, DataStart, DataEnd, Partener,
                Moneda, TipPromotie, TipConditie, Obs, Subunitatea, TipClaseP, TipServire, DeMana, ValMin, Praguri,
                CantMin,
                CASE WHEN DeMana in (3,4) THEN ExclAltePromo ELSE 0 END EXCLALTEPROMO,
                OraStart, OraStop, PRETCUAMANUNT
         FROM TMP_PROMO )
    WHERE CodPromo = RecId ;

    DELETE FROM PROMOPART
    WHERE CodPromo = RecID
      AND CodPromoPart NOT IN (SELECT CodPromoPart FROM TMP_PROMOPART );

    UPDATE PROMOPART pp
    SET (CodClaseP, Partener, CodLocatie, CodFiscal, CodPersc, Prioritar)
      = (SELECT T.CodClaseP, T.Partener, T.CodLocatie, T.CodFiscal, T.CodPersc, T.Prioritar
         FROM TMP_PROMOPART T WHERE T.CodPromoPart = PP.CodPromoPart
        )
    WHERE PP.CodPromo = RecID ;

    INSERT INTO PROMOPART ( CodPromoPart, CodPromo, CodClaseP, Partener, CodLocatie, CodFiscal, CodPersc, Prioritar)
    SELECT nextval('SEQ_PROMOPART_CODPROMOPART'), RecID, CodClaseP, Partener, CodLocatie, CodFiscal, CodPersc, Prioritar
    FROM TMP_PROMOPART WHERE coalesce( CodPromoPart, 0) &lt;= 0;

    DELETE FROM PROMOSUB
    WHERE CodPromo = RecID AND CodPromoSub NOT IN (SELECT CodPromoSub FROM TMP_PROMOSUB );

    UPDATE PROMOSUB PS
    SET Subunitatea = (SELECT T.Subunitatea FROM TMP_PROMOSUB T WHERE T.CodPromoSub = PS.CodPromoSub )
    WHERE PS.CodPromo = RecID ;

    INSERT INTO PROMOSUB (CodPromoSub, CodPromo, Subunitatea)
    SELECT nextval('SEQ_PROMOSUB_CODPROMOSUB'), RecID, Subunitatea FROM TMP_PROMOSUB WHERE coalesce( CodPromoSub, 0) &lt;= 0;

    DELETE FROM PROMOPRAG
    WHERE CodPromo = RecID AND CodPrag NOT IN (SELECT CodPrag FROM TMP_PROMOPRAG );

    UPDATE PROMOPRAG pp
    SET (ValMin, ProcDisc, ValDisc, CantMin) = (SELECT T.ValMin, T.ProcDisc, T.ValDisc, T.CantMin FROM TMP_PROMOPRAG T WHERE T.CodPrag = pp.CodPrag)
    WHERE pp.CodPromo = RecID ;

    INSERT INTO PROMOPRAG (CodPrag, CodPromo, ValMin, ProcDisc, ValDisc, CantMin)
    SELECT nextval('SEQ_PROMOPRAG_CODPRAG'),   RecID, ValMin, ProcDisc, ValDisc, CantMin
    FROM TMP_PROMOPRAG
    WHERE coalesce( CodPrag, 0) &lt;= 0;

    DELETE FROM PROMO1CADOUSER
    WHERE CodCadou      IN (SELECT CODCADOU  FROM PROMO1CADOU P1C, PROMO1 P1 WHERE coalesce( P1C.CODPROMO1, 0) &lt;&gt; 0 AND P1.CODPROMO1 = P1C.CODPROMO1 AND P1.CODPROMO = RECID)
      AND CodCadouS NOT IN (SELECT CODCADOUS FROM TMP_PROMO1CADOUSER WHERE CODCADOUS &gt; 0 );

    DELETE FROM PROMO1CADOUSER
    WHERE CodCadouS     IN (SELECT CODCADOUS FROM PROMO1CADOU P1C WHERE coalesce( P1C.CODPROMO1,0) = 0 AND P1C.CODPROMO = RECID )
      AND CodCadouS NOT IN (SELECT CODCADOUS FROM TMP_PROMO1CADOUSER WHERE CODCADOUS &gt; 0 );

    DELETE FROM PROMO1SER
    WHERE CodPromo1      IN (SELECT P1.CodPromo1 FROM Promo1 P1     WHERE P1.CodPromo = RecID )
      AND CodPromo1S NOT IN (SELECT CODPROMO1S   FROM TMP_PROMO1SER WHERE CODPROMO1S &gt; 0 );

    DELETE FROM PROMO1CADOU
    WHERE coalesce(CODPROMO1,0) &lt;&gt; 0
          AND CodPromo1    IN (SELECT P1.CodPromo1 FROM Promo1 P1       WHERE P1.CodPromo = RecID )
          AND CodCadou NOT IN (SELECT CodCadou      FROM TMP_PROMO1CADOU WHERE CodCadou &gt; 0 );

    DELETE FROM PROMO1CADOU
    WHERE coalesce(CODPROMO1,0) = 0
          AND CodPromo          = RECID
          AND CodCadou NOT IN (SELECT CodCadou FROM TMP_PROMO1CADOU WHERE CodCadou &gt; 0 );

    DELETE FROM PROMO1
    WHERE CodPromo = RecID
          AND CodPromo1 NOT IN (SELECT CodPromo1 FROM TMP_PROMO1 );

    FOR v_rec IN (SELECT CodPromo1, CodObiect, CodArticol, CodClaseA, CuEchivalente, UMSec,
                         Cant * coalesce( Paritate, 1)        CANT,
                         CantOptim * coalesce( Paritate, 1)   CANTOPTIM,
                         Pret / coalesce( Paritate, 1)        PRET,
                         PretAmanunt / coalesce( Paritate, 1) PRETAMANUNT,
                         ProcDisc, ValDisc, ZileC, TipLimita, ModAplic, TG_Max, GrupaPret, Zile_Exp, ValMin,
                         CANT_MAX*Coalesce(PARITATE,1) as cant_max
                  FROM TMP_Promo1 ORDER BY IndexLocal
                 )
    LOOP
      IF coalesce( v_rec.CodPromo1, 0) &gt; 0 THEN
        UPDATE Promo1
        SET
          CodObiect     = v_rec.CodObiect,
          CodArticol    = v_rec.CodArticol,
          CodClaseA     = v_rec.CodClaseA,
          CuEchivalente = v_rec.CuEchivalente,
          UMSec         = v_rec.UMSec,
          Cant          = v_rec.Cant,
          Pret          = v_rec.Pret,
          ProcDisc      = v_rec.ProcDisc,
          ValDisc       = v_rec.ValDisc,
          ZileC         = v_rec.ZileC,
          TipLimita     = v_rec.TipLimita,
          ModAplic      = v_rec.ModAplic,
          TG_Max        = CASE WHEN v_rec.TipLimita = 1 THEN v_rec.TG_Max  ELSE NULL END ,
          GrupaPret     = v_rec.GrupaPret,
          Zile_Exp      = CASE WHEN v_rec.TipLimita = 2 THEN v_rec.Zile_Exp ELSE NULL END ,
          ValMin        = v_rec.ValMin,
          PretAmanunt   = v_rec.PretAmanunt,
          CantOptim     = v_rec.CantOptim,
          cant_max      = v_rec.cant_max
        WHERE CodPromo1 = v_rec.CodPromo1 ;
      ELSE
        SELECT nextval('SEQ_PROMO1_CODPROMO1') INTO vCod;

        UPDATE TMP_PROMO1CADOU SET CodPromo1 = vCOD WHERE CodPromo1 = v_rec.CodPromo1 ;
        UPDATE TMP_PROMO1SER   SET CodPromo1 = vCOD WHERE CodPromo1 = v_rec.CodPromo1 ;

        INSERT INTO Promo1 (CodPromo1, CodPromo, CodObiect, CodArticol, CodClaseA, CuEchivalente, UMSec, Cant,
                            Pret, ProcDisc, ValDisc, GrupaPret, ZileC, TipLimita, ModAplic, TG_Max,
                            Zile_Exp, ValMin, PretAmanunt, CantOptim, cant_max
                           )
        VALUES (vCod, RecId, v_rec.CodObiect, v_rec.CodArticol, v_rec.CodClaseA, v_rec.CuEchivalente,
                v_rec.UMSec, v_rec.Cant, v_rec.Pret, v_rec.ProcDisc, v_rec.ValDisc, v_rec.GrupaPret,
                v_rec.ZileC, v_rec.TipLimita, v_rec.ModAplic,
                CASE WHEN v_rec.TipLimita = 1 THEN v_rec.TG_Max   ELSE NULL END ,
                CASE WHEN v_rec.TipLimita = 2 THEN v_rec.Zile_Exp ELSE NULL END ,
                v_rec.ValMin, v_rec.PretAmanunt, v_rec.CantOptim, v_rec.cant_max
               );
      END IF;
    END LOOP;

    FOR v_rec IN (SELECT CodCadou, CodPromo1, CodPromo, CodObiect, UMSec, Cant * Paritate CANT,
                         TipLimita, TG_Max, Zile_Exp, ValMin, CantMin * Paritate CANTMIN
                  FROM TMP_Promo1Cadou ORDER BY CodPromo1, IndexLocal
                 )
    LOOP
      IF coalesce(v_rec.CodCadou, 0) &gt; 0 THEN
        UPDATE Promo1Cadou
        SET
          CodObiect = v_rec.CodObiect,
          UMSec     = v_rec.UMSec,
          Cant      = v_rec.Cant,
          TipLimita = v_rec.TipLimita,
          TG_Max    = CASE WHEN v_rec.TipLimita = 1 THEN v_rec.TG_Max   ELSE NULL END ,
          Zile_Exp  = CASE WHEN v_rec.TipLimita = 2 THEN v_rec.Zile_Exp ELSE NULL END ,
          ValMin    = v_Rec.ValMin,
          CantMin   = v_rec.CantMin,
          CODPROMO  = RECID
        WHERE CodCadou = v_rec.CodCadou ;
      ELSE
        SELECT nextval('SEQ_PROMO1CADOU_CODCADOU') INTO vCod;

        UPDATE TMP_PROMO1CADOUSER SET CodCadou = vCOD WHERE CodCadou = v_rec.CodCadou ;

        INSERT INTO Promo1Cadou (CodCadou, CodPromo1, CodObiect, UMSec, Cant, TipLimita, TG_Max,
                                 Zile_Exp, Codpromo, ValMin, CantMin
                                )
        VALUES (vCod, v_rec.CodPromo1, v_rec.CodObiect, v_rec.UMSec, v_rec.Cant, v_rec.TipLimita,
                CASE WHEN v_rec.TipLimita = 1 THEN v_rec.TG_Max   ELSE NULL END ,
                CASE WHEN v_rec.TipLimita = 2 THEN v_rec.Zile_Exp ELSE NULL END ,
                RECID, v_rec.ValMin, v_rec.CantMin );
      END IF;
    END LOOP;

    UPDATE PROMO1SER PS
    SET Serie = (SELECT T.Serie FROM TMP_PROMO1SER T WHERE T.CodPromo1S = PS.CodPromo1S )
    WHERE CodPromo1S IN (SELECT CodPromo1S FROM TMP_PROMO1SER WHERE coalesce( CodPromo1S, 0) &gt; 0 );

    INSERT INTO PROMO1SER (CodPromo1S, CodPromo1, Serie )
    SELECT nextval('SEQ_PROMO1SER_CODPROMO1S'), CodPromo1, Serie
    FROM (SELECT CodPromo1, Serie
          FROM TMP_PROMO1SER
          WHERE coalesce( CodPromo1S, 0) &lt;= 0 AND coalesce( CodPromo1, 0) &gt; 0
          ORDER BY CodPromo1, IndexLocal
         ) A_PG;

    UPDATE PROMO1CADOUSER PCS
    SET Serie = (SELECT T.Serie FROM TMP_PROMO1CADOUSER T WHERE T.CodCadouS = PCS.CodCadouS )
    WHERE CodCadouS IN (SELECT CodCadouS FROM TMP_PROMO1CADOUSER WHERE coalesce( CodCadouS, 0) &gt; 0 );

    INSERT INTO PROMO1CADOUSER (CodCadouS, CodCadou, Serie )
    SELECT nextval('SEQ_PROMO1CADOUSER_CODCADOUS'), CodCadou, Serie
    FROM (SELECT CodCadou, Serie
          FROM TMP_PROMO1CADOUSER
          WHERE coalesce( CodCadouS, 0) &lt;= 0 AND coalesce( CodCadou, 0) &gt; 0
          ORDER BY CodCadou, IndexLocal
         ) B_PG;
  ELSE  --INSERT
    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT
        FROM PKG_USERFIRME_ValidPostLog(null, current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_PROMO.CT_MONITOR', true))
       )
    THEN
      PERFORM pkg_userfirme_postlogcucommit( 'PROMO', current_setting('PKG_GLOBALS.USERNAME', true), 'A', RECID,
                                     current_setting('PKG_GLOBALS.FIRMANAME', true),
                                     aCodSubunit, aDataStart, aDoc, null,
                                     (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(null, null))
                                   );
    END IF;

    SELECT nextval('SEQ_PROMO_CODPROMO') INTO RecId;

    INSERT INTO PROMO (CodPromo, TipDoc, Anulat, Blocat, Operat, CarnetDoc, SeriaDoc, NrDoc, DataStart, DataEnd,
                       Partener, Moneda, TipPromotie, TipConditie, Obs, Subunitatea, An, Luna, TipClaseP,
                       TipServire, DeMana, ValMin, Praguri, CantMin, ExclAltePromo,
                       OraStart, OraStop, UserId, DataCreare, PRETCUAMANUNT
                      )
    SELECT RecId, TipDoc, Anulat, Blocat, Operat, CarnetDoc, SeriaDoc, NrDoc, DataStart, DataEnd,
           Partener, Moneda, TipPromotie, TipConditie, Obs, Subunitatea, An, Luna, TipClaseP,
           TipServire, DeMana, ValMin, Praguri, CantMin,
           CASE WHEN DeMana in (3,4) THEN ExclAltePromo ELSE 0 END EXCLALTEPROMO,
           OraStart, OraStop, current_setting('PKG_GLOBALS.UserId', true)::numeric, current_timestamp, PRETCUAMANUNT
    FROM TMP_PROMO;

    INSERT INTO PROMOPART (CodPromoPart, CodPromo, CodClaseP, Partener, CodLocatie, CodFiscal, CodPersc, Prioritar )
    SELECT nextval('SEQ_PROMOPART_CODPROMOPART'), RecID, CodClaseP, Partener, CodLocatie, CodFiscal, CodPersc, Prioritar
    FROM TMP_PROMOPART;

    INSERT INTO PROMOSUB (CodPromoSub, CodPromo, Subunitatea )
    SELECT nextval('SEQ_PROMOSUB_CODPROMOSUB'), RecID, Subunitatea
    FROM TMP_PROMOSUB;

    INSERT INTO PROMOPRAG (CodPrag, CodPromo, ValMin, ProcDisc, ValDisc, CantMin )
    SELECT nextval('SEQ_PROMOPRAG_CODPRAG'), RecID, ValMin, ProcDisc, ValDisc, CantMin
    FROM TMP_PROMOPRAG;

    FOR v_rec IN (SELECT CodPromo1, CodObiect, CodArticol, CodClaseA, CuEchivalente, UMSec,
                         Cant * coalesce( Paritate, 1)        CANT,
                         CantOptim * coalesce( Paritate, 1)   CANTOPTIM,
                         Pret / coalesce( Paritate, 1)        PRET,
                         PretAmanunt / coalesce( Paritate, 1) PRETAMANUNT,
                         ProcDisc, ValDisc, GrupaPret, ZileC, TipLimita, ModAplic, TG_Max, Zile_Exp, ValMin,
                         CANT_MAX*Coalesce(Paritate,1) as cant_max
                  FROM TMP_Promo1 ORDER BY IndexLocal
                )
    LOOP
      SELECT nextval('SEQ_PROMO1_CODPROMO1') INTO vCod;

      UPDATE TMP_PROMO1CADOU SET CodPromo1 = vCOD WHERE CodPromo1 = v_rec.CodPromo1 ;
      UPDATE TMP_PROMO1SER   SET CodPromo1 = vCOD WHERE CodPromo1 = v_rec.CodPromo1 ;

      INSERT INTO Promo1 (CodPromo1, CodPromo, CodObiect, CodArticol, CodClaseA, CuEchivalente, UMSec, Cant,
                          Pret, ProcDisc, ValDisc, GrupaPret, ZileC, TipLimita, ModAplic,
                          TG_Max, Zile_Exp, ValMin, PretAmanunt, CantOptim, cant_max
                         )
      VALUES (vCod, RecId, v_rec.CodObiect, v_rec.CodArticol, v_rec.CodClaseA, v_rec.CuEchivalente, v_rec.UMSec,
              v_rec.Cant, v_rec.Pret, v_rec.ProcDisc, v_rec.ValDisc, v_rec.GrupaPret, v_rec.ZileC, v_rec.TipLimita,
              v_rec.ModAplic, v_rec.TG_Max, v_rec.Zile_Exp, v_rec.ValMin, v_rec.PretAmanunt, v_rec.CantOptim, v_rec.cant_max
             );
    END LOOP;

    FOR v_rec IN (SELECT CodCadou, CodPromo1, CodObiect, UMSec, Cant * Paritate CANT, TipLimita,
                         TG_Max, Zile_Exp, ValMin, CantMin * Paritate CANTMIN, CodPromo
                  FROM TMP_Promo1Cadou ORDER BY CodPromo1, IndexLocal
                 )
    LOOP
      SELECT nextval('SEQ_PROMO1CADOU_CODCADOU') INTO vCod;

      UPDATE TMP_PROMO1CADOUSER SET CodCadou = vCOD WHERE CodCadou = v_rec.CodCadou ;

      INSERT INTO Promo1Cadou (CodCadou, CodPromo1, CodObiect, UMSec, Cant, TipLimita, TG_Max,
                               Zile_Exp, ValMin, CantMin, CODPROMO
                              )
      VALUES (vCod, v_rec.CodPromo1, v_rec.CodObiect, v_rec.UMSec, v_rec.Cant, v_rec.TipLimita, v_rec.TG_Max,
              v_rec.Zile_Exp, v_rec.ValMin, v_rec.CantMin, RecId
             );
    END LOOP;

    INSERT INTO PROMO1SER (CodPromo1S, CodPromo1, Serie )
    SELECT nextval('SEQ_PROMO1SER_CODPROMO1S'), CodPromo1, Serie
    FROM (SELECT CodPromo1, Serie FROM TMP_PROMO1SER ORDER BY CodPromo1, IndexLocal) C_PG;

    INSERT INTO PROMO1CADOUSER (CodCadouS, CodCadou, Serie )
    SELECT nextval('SEQ_PROMO1CADOUSER_CODCADOUS'), CodCadou, Serie
    FROM (SELECT CodCadou, Serie FROM TMP_PROMO1CADOUSER ORDER BY CodCadou, IndexLocal ) D_PG;
  END IF;

  PERFORM PKG_CARNETEDOC_SOLVENUMARDOC( aCarnetDoc, (aNrDoc)::character varying);

  PERFORM NotifyModif( Operation, RecId, 'PROMO');

  IF aAmPrioritar = 1 THEN
    FOR vRec IN (SELECT PARTENER, coalesce( CODLOCATIE, 0) CODLOCATIE FROM tmp_promopart WHERE prioritar = 1 ) LOOP
      UPDATE promopart pp
      SET prioritar = 0
      WHERE pp.Partener = vRec.Partener
            AND ( coalesce( pp.CodLocatie, 0) = vREc.CodLocatie or vRec.CodLocatie = 0)
            AND pp.codpromo &lt;&gt; RecId
            AND EXISTS (SELECT 1
                        FROM promo p
                        WHERE p.codpromo        = pp.codpromo
                              AND p.TipPromotie = 2
                              AND p.DataStart  &lt;= aDataEnd
                              AND p.DataEnd    &gt;= aDataStart
                       ) ;
    END LOOP;
  END IF;

BEGIN
SELECT (SELECT PKG_CATEGCONST_GetValConstanta.WME_RESULT FROM PKG_CATEGCONST_GetValConstanta(NULL,'SyncPromoRetail', current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric, current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric))
INTO aSyncPromoRetail;
EXCEPTION WHEN OTHERS THEN
aSyncPromoRetail := '0';
END;
IF  aSyncPromoRetail = '1'
THEN
PERFORM PKG_POSTRETAIL_MEMO_MODIF_PROMO_RETAIL(RECID, 0);
END IF;

END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_rez_isdatacuora</obj_name>
  <obj_hashval>398b9ba4ce43483b1286be8c43667a72</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_rez_isdatacuora(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_RAC_REZ.IsDataCuOra')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_rez_setct_monitor</obj_name>
  <obj_hashval>40b67d1cd33ee9395e228ee99f7ddca0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_rez_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_RAC_REZ.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_raportp_setcarnetdoc_i</obj_name>
  <obj_hashval>03071e54dd2367884d5a17a0c3ffdf83</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_raportp_setcarnetdoc_i(acarnetdoc_i numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_RAPORTP.CARNETDOC_I',to_char(aCARNETDOC_I,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanz_spec_processlist</obj_name>
  <obj_hashval>8ba53c72c6c9f9706e954b9ed1518e2e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanz_spec_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  DEN_COL     varchar;
  gSuplCols   varchar := 'NARTOBJ O';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 22.05.2023 - fixat 58376
  --Florin 21.04.2023 - sinc. Oracle
  --Adina 16.12.2020 tichet 41681
  --Florin 22.08.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = O.CODOBIECT',NULL);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_VANZ_SPEC.gSuplCols', gSuplCols, FALSE);

  IF (fnc_TmpExists('NPARTDET')) = 1 THEN
    BEGIN
      SELECT COALESCE(T.COLUMN_NAME, '')
      INTO STRICT DEN_COL
      FROM information_schema.columns T
      WHERE table_schema = lower(current_setting('PKG_GLOBALS.FIRMANAME', true)) AND
            T.ORDINAL_POSITION = 3 AND  TABLE_NAME = 'npartdet';
    EXCEPTION
      WHEN no_data_found THEN DEN_COL := '';
      WHEN OTHERS        THEN DEN_COL := '';
    END;
  END IF;

  sInsert := 'INSERT INTO ' || TMPNAME || ' (
         Luna,
         ClasifPart,
         CodExtern,
         CodIntern,
         CodCNAS,
         Denumire,
         ClsArt,
         TipArticol,
         Cant,
         Val,
         DiscGen,
         DiscArt,
         DiscCum,
         ValNet ' || gUserFields || ')
      select
        x.Luna,
        x.ClasifPart,
        x.CodExtern,
        x.CodIntern,
        x.CodCNAS,
        x.Denumire,
        x.ClsArt,
        x.TipArticol,
        x.cant,
        x.Val,
        COALESCE(DiscGen.val,0) DiscGen,
        COALESCE(DiscArt.val,0) + COALESCE(DiscArtSec.val,0) DiscArt,
        COALESCE(DiscCum.val,0) DiscCum,
        x.Val - COALESCE(DiscGen.val,0) - COALESCE(DiscArt.val,0) - COALESCE(DiscArtSec.val,0) - COALESCE(DiscCum.val,0) ValNet' || gUserAlias || '
      from (
      select
        Luna,
        ClasifPart,
        CodExtern,
        CodIntern,
        CodCNAS,
        Denumire,
        ClsArt,
        TipArticol,
        sum(Cant) cant,
        round(sum(Val),2) Val,
        codobiect
      from
      (
        select
          getlunalucru() Luna,';

  IF (fnc_TmpExists('NPARTDET')) = 1 AND Length(trim(DEN_COL)) &gt; 0 THEN
    sInsert := coalesce(sInsert,'') || '
          pext.' || coalesce(DEN_COL,'') || ' ClasifPart,';
  ELSE
    sInsert := coalesce(sInsert,'') || '
          null ClasifPart,';
  END IF;

  sInsert := coalesce(sInsert,'') || '
          obj.codextern,
          obj.codintern,
          obj.codcnas,
          obj.denumire,
          cls.den_clasea ClsArt,
          case when i1.pu = 0 then 0 else 1 end TipArticol,
          i1.cant,
          round(i1.Cant * i1.Pretorig,2) Val,
          i1.codobiect
        from iesiri1 i1
             inner join iesiri  i   on i1.codies      = i.codies
             inner join npart   p   on p.codpart      = i.partener
             inner join nartobj obj on i1.codobiect   = obj.codobiect
             inner join nart    art on art.codarticol = obj.codarticol
             left  join nclasea cls on cls.codclasea  = art.clasa ';

  IF (fnc_TmpExists('NPARTDET')) = 1  AND Length(trim(DEN_COL)) &gt; 0 THEN
    sInsert := coalesce(sInsert,'') || '
             left join npartdet pext on pext.codpart = p.codpart';
  END IF;

  sInsert := coalesce(sInsert,'') || '
        where i.an * 12 + i.luna = getanlunalucru() and i.anulat = 0
            and (getsubunitate() = 1 or i.subunitatea = GETSUBUNITATE())
          and i.tipdoc &lt;&gt; 26
      union all
      select
          GETLUNALUCRU() Luna,';

  IF  (fnc_TmpExists('NPARTDET')) = 1 AND Length(trim(DEN_COL)) &gt; 0 THEN
    sInsert := coalesce(sInsert,'') || '
          pext.' || coalesce(DEN_COL,'') || ' ClasifPart,';
  ELSE
    sInsert := coalesce(sInsert,'') || '
          null ClasifPart,';
  END IF;

  sInsert := coalesce(sInsert,'') || '
          obj.codextern,
          obj.codintern,
          obj.codcnas,
          obj.denumire,
          cls.den_clasea ClsArt,
          case when i1.pu = 0 then 0 else 1 end TipArticol,
          0 cant,
          0 Val,
          i1.codobiectorig codobiect
        from iesiri1 i1
             inner join iesiri  i   on i1.codies = i.codies
             inner join npart   p   on p.codpart = i.partener
             inner join nartobj obj on i1.codobiectorig = obj.codobiect
             inner join nart    art on art.codarticol   = obj.codarticol
             left  join nclasea cls on cls.codclasea    = art.clasa ';

  IF (fnc_TmpExists('NPARTDET')) = 1 THEN
    sInsert := coalesce(sInsert,'') || '
             left join npartdet pext on pext.codpart = p.codpart';
  END IF;

  sInsert := coalesce(sInsert,'') || '
        where i.an * 12 + i.luna = getanlunalucru() and i.anulat = 0
          and i.tipdoc &lt;&gt; 26
              and (getsubunitate() = 1 or i.subunitatea = getsubunitate())
              and (i1.codobiect in (
                                   COALESCE(fnc_getvalconstantalucru(''ArtDiscAcCant'')::numeric, 0),
                                   COALESCE(fnc_getvalconstantalucru(''ArtDiscAcVol'' )::numeric, 0)
                                   )
                   or
                   strpos(fnc_getvalconstantalucru(''ArtDiscAcTer''), i1.codobiect::varchar) &gt; 0
                   )
      ) A_PG group by
          Luna,
          ClasifPart,
          CodExtern,
          CodIntern,
          CodCNAS,
          Denumire,
          ClsArt,
          TipArticol,
          codobiect
        ) x
         left join nartobj o ON o.codobiect = x.codobiect
         left join (select - sum(i1.cant * i1.pu) val, i1.codobiectorig codobiect
                    from iesiri1 i1
                         inner join iesiri i on i1.codies = i.codies
                    where i1.codobiect = COALESCE(fnc_getvalconstantalucru(''ArtDiscAcCant'')::numeric, 0)
                          and i.an * 12 + i.luna = getanlunalucru() and (getsubunitate() = 1 or i.subunitatea = getsubunitate())
                          and i.anulat = 0
                    group by i1.codobiectorig
                   ) DiscGen on DiscGen.codobiect = x.codobiect
         left join (select - sum(i1.cant * i1.pu) val, i1.codobiectorig codobiect
                    from iesiri1 i1
                         inner join iesiri i on i1.codies = i.codies
                    where strpos(fnc_getvalconstantalucru(''ArtDiscAcTer''),i1.codobiect::varchar) &gt; 0
                          and i.an * 12 + i.luna = getanlunalucru() and (getsubunitate() = 1 or i.subunitatea = getsubunitate())
                          and i.anulat = 0
                    group by i1.codobiectorig
                   ) DiscArt on DiscArt.codobiect = x.codobiect
         left join (select sum(i1.cant * i1.pretorig * (1 - COALESCE(i1.coefdiscmaj,1))) val, i1.codobiect
                    from iesiri1 i1
                         inner join iesiri i on i1.codies = i.codies
                    where i.an * 12 + i.luna = GETANLUNALUCRU()
                          and i1.tiplinie = ''='' and (getsubunitate() = 1 or i.subunitatea = getsubunitate())
                          and i.anulat = 0
                    group by i1.codobiect
                   ) DiscArtSec on DiscArtSec.codobiect = x.codobiect
         left join (select - sum(i1.cant * i1.pu) val, i1.codobiectorig codobiect
                    from iesiri1 i1
                         inner join iesiri i on i1.codies = i.codies
                    where i1.codobiect = COALESCE(fnc_getvalconstantalucru(''ArtDiscAcVol'')::numeric, 0)
                          and i.an * 12 + i.luna = getanlunalucru() and (getsubunitate() = 1 or i.subunitatea = getsubunitate())
                          and i.anulat = 0
                    group by i1.codobiectorig
                   ) DiscCum on DiscCum.codobiect = x.codobiect
         ' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_verif_imp_ies_processlist</obj_name>
  <obj_hashval>7584bff910365acd07cc3c3e49513828</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_verif_imp_ies_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert VARCHAR(2000);
  sSelect VARCHAR(10000);
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplCols   varchar := 'iesiri i, npart np, spvarhiva a';
  gSuplJoins  VARCHAR := '';
  anLucru     NUMERIC(4);
  alStart     NUMERIC;
  alStop      NUMERIC;
  condHolding VARCHAR(1000);
  joinHolding VARCHAR(1000);
  subunitHolding VARCHAR(1000);
  vSubunit NUMERIC (20);
BEGIN
  --Florin 07.10.2024 - sinc. oracle
  --Florin 10.09.2024 - fixat 63310
  --Florin 09.09.2024 - sinc. Oracle

  CALL pkg_list_struct_StartSuplCols();
  CALL pkg_list_struct_GetSuplCols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config('PKG_LIST_BASE_VERIF_IMP_IES.gSuplCols',gSuplCols,false);

  anLucru := getANLUCRU();
  alStart := anLucru * 12 + coalesce(current_setting('PKG_LIST_SELECTLUNA.vLunaStart', true)::numeric, 0);
  alStop  := anLucru * 12 + coalesce(current_setting('PKG_LIST_SELECTLUNA.vLunaFin', true)::numeric, 0);

  condHolding := '';
  joinHolding := '';
  subunitHolding := 'i.subunitatea';
  if (fnc_getvalconstantalucru('Holding') = '1') then
    vSubunit := GETSUBUNITATE();
      subunitHolding := ' coalesce(i.subunitatea, ns.codsubunit) ';
      joinHolding    := ' left join nsubunit ns on REGEXP_REPLACE (ns.cif,  ''[[:alpha:]]'','''',''g'') = a.cif ';
      if (vSubunit &lt;&gt; 0) then
        if (vSubunit &lt;&gt; 1) then
          condHolding := ' and '||subunitHolding||' = ' || vSubunit;
        ELSIF Coalesce(fnc_getvalconstantalucru('CumulatFirmaToateSub'),2) = '2' THEN
           condHolding := 'and '||subunitHolding||' IN (SELECT codsubunit FROM tmp_subunitdedicate)';
        end if;
      end if;
  end if;

  sInsert := 'INSERT INTO '|| COALESCE(tmpName, '') ||'(
                       NAV_CodDoc, NAV_TipDoc, NrDoc, DATADOC, VALDOC, TVADOC, VALDOCEFACT, ANWME, LUNAWME,
                       ANSPV, LUNASPV, ID_DESC_WME, ID_DESC_SPV, DEN_PART, DATAINCARCARE, ANDOC,
                       LUNADOC, DATADOCSPV, CIF, STARE_CUI, TIPTRANZ, TIPTVA, LOCALITATE, TARA, DEN_SUBUNIT '||gUserFields||' )';
  sSelect := '
                select i.codies, i.tipdoc, i.nrdoc, i.datadoc, i.valdoc,i.tvadoc,i.valdocefact,
                   i.an as anwme, i.luna as lunawme, a.an as anspv, a.luna as lunaspv,
                   i.iddescarcare as idwme, a.iddescarcare as idspv, np.den_part, a.dataincarcare ,
                   coalesce(i.an, a.an),
                   coalesce(i.luna, a.luna),
                   a.DATADOCSPV,
                   coalesce(a.cif_partener, npcfintr.codfiscal),
                   case when NPA.CONTRIBUABIL = 0 then ''CUI neplatitor TVA''
                        when NPA.CONTRIBUABIL = 1 then ''CUI platitor TVA''
                        when NPA.CONTRIBUABIL = -1 then ''CUI incorect''
                        when NPA.CONTRIBUABIL = -2 then ''CUI radiat/inactiv''
                        else null::varchar
                        end,
                   case i.tiptranzactie
                        when  1 then ''tranzactie interna''
                        when  2 then ''achizitie intracomunitara''
                        when  3 then ''import servicii''
                        when  4 then ''factura de transport taxabila pe DVI''
                        when  5 then ''factura de decontare''
                        when  6 then ''monetar''
                        when  7 then ''Borderou de achizitii''
                        when  8 then ''Fila carnet producator''
                        when  9 then ''Contract achizitii''
                        when 10 then ''Alte documente''
                        when 11 then ''Arenda''
                        else null::varchar
                   end,
                   case i.tiptva
                        when 1 then ''taxare normala''
                        when 2 then ''taxare inversa''
                        when 3 then ''tranzactie triunghiulara''
                        when 4 then ''taxare normala Prorata''
                        when 6 then ''regim special de scutire art 311 CF''
                        when 7 then ''regim special de scutire art 312 CF''
                        when 8 then ''achizitii UE de bunuri cu instalare/montaj''
                        when 9 then ''regim special pt. agricultori (art.315)''
                        else null::varchar
                   end, loc.den_localit, t.den_tara,  nsu.den_subunit '||gUserAlias||
            ' from iesiri i
              full join spvarhiva a on a.iddescarcare = i.iddescarcare::varchar
              left join (SELECT
                                  distinct FIRST_VALUE(ncfi.codpart)
                                           OVER(PARTITION BY ncfi.CODFISCAL
                                                          order by  np.blocat nulls first, np.inactiv nulls first, ncfi.principal desc  nulls last
                                                          ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
                                           ) as codpart,
                                           ncfi.CODFISCAL
                            FROM NPARTCODFISC ncfi
                            join npart np on np.codpart = ncfi.codpart ) ncf on upper(trim(ncf.codfiscal)) = upper(trim(a.cif_partener))
              left join npart np on np.codpart = coalesce(i.partener, ncf.codpart)
              left join NPARTCODFISC npcfintr on npcfintr.cod_codfiscal = i.codfiscal
              left join nagenda nag on nag.codagenda = i.codlocatie
              left join nlocalit loc on loc.codlocalit = nag.codlocalit
              left join ntari t on t.codtara = loc.codtara '
              ||joinHolding||
              ' left join nsubunit nsu on nsu.codsubunit = ' || subunitHolding ||
              ' LEFT JOIN (select distinct npi.cui, first_value(npi.contribuabil) over (partition by npi.cui order by npi.contribuabil ) as contribuabil from  NPART_ANAF npi) NPA ON NPA.CUI::varchar = REGEXP_REPLACE (coalesce(a.cif_partener, npcfintr.codfiscal), ''[[:alpha:]]'','''',''g'')'
              ||gSuplJoins||
              ' where (a.tipdoc = 19 or a.tipdoc is null)
               and (i.tipdoc in (19,26) or i.tipdoc is null)'
               || condHolding ||
               ' and ((i.an *12 + i.luna BETWEEN '||alStart||' AND '||alStop||')
               or (a.an *12 + a.luna BETWEEN '||alStart||' AND '||alStop||')) ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_fisaanalitikpart_getinfopart</obj_name>
  <obj_hashval>ef85598e4b15b7002b36bf85df41fd59</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_fisaanalitikpart_getinfopart(acodpart numeric, alunastart numeric, alunafin numeric, areconturi boolean, aremonezi boolean, info_kind numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sSelect            varchar;
  tmpTableCursorName varchar;
  sCreateTable       varchar;

  aSubunitate        numeric;
  sDistinctCol       varchar(300);
  sCondPart          varchar(300);
  sFiltru            varchar(300) := ' 1=1 ';
  vAnLunaIni         numeric;

  CT_INFO_MONEDA     numeric := 0;
  CT_INFO_CONT       numeric := 1;
BEGIN
  --Adina 14.07.2021 - sinc.Oracle din 13.07.2021
  --Bogdan 24.08.2020; Adina 16.11.2020-tuning (dura 1 minut)
  tmpTableCursorName :='TMP_CURSOR_PG';

  if AreConturi is null then
    areconturi := false;
  end if;
  if AreMonezi is null then
    AreMonezi := false;
  end if;

  execute 'drop table if exists ' || tmpTableCursorName;

  sCreateTable := 'CREATE TEMP TABLE '||tmpTableCursorName||' AS ';

  sDistinctCol := CASE info_kind
                    WHEN CT_INFO_MONEDA THEN  ' DISTINCT CODMONEDA, DEN_MONEDA '
                    WHEN CT_INFO_CONT   THEN  ' DISTINCT CODCONT, CONT '
                  END;

  SELECT aninitial*12+lunainitiala
  INTO vAnLunaIni
  FROM FIRMALUNI;

  IF coalesce(aCodPart,0) = 0
  THEN sCondPart := ' &lt;&gt; 0';
  ELSE sCondPart := ' = '||coalesce(aCodPart,0);
  END IF;

  IF getsubunitate() &gt; 1
  THEN aSubunitate := getsubunitate();
  ELSE aSubunitate := 0;
  END IF;

  sSelect :='
    WITH
    crs_doc AS (
          SELECT g.codgeneral,g.moneda,intr.an,intr.luna
        FROM general g
            INNER JOIN intrari intr ON g.coddoc = intr.codintr AND g.tipdoc = intr.tipdoc
        WHERE intr.an * 12 + intr.luna BETWEEN '||aLunastart::varchar||' AND  '||aLunaFin::varchar||'
            AND G.SEMNIFICATIE NOT IN (800,801,900,901,950,951,1100,1000,1101)
              AND Coalesce(intr.partener,0)'||sCondPart||
              pkg_list_base_utils_cond_subunit('intr', null, null, aSubunitate)||'
          UNION ALL
            SELECT g.codgeneral,g.moneda,ies.an,ies.luna
            FROM general g
                INNER JOIN iesiri ies ON g.coddoc = ies.codies AND g.tipdoc = ies.tipdoc
            WHERE ies.an * 12 + ies.luna BETWEEN '||aLunastart::varchar||' AND '||aLunaFin::varchar||'
                AND G.SEMNIFICATIE  NOT IN (800,801,900,901,950,951,1100,1000,1101)
                AND Coalesce(ies.partener,0)'||sCondPart||
                pkg_list_base_utils_cond_subunit('ies', null, null, aSubunitate)||'
        UNION ALL
          SELECT g.codgeneral,g.moneda,nc.an,nc.luna
            FROM general g
                INNER JOIN nc1  ON g.coddoc = nc1.codnc1 AND g.tipdoc = 35
                INNER JOIN NC ON NC.CODNC = NC1.CODNC
            WHERE nc.an * 12 + nc.luna BETWEEN '||aLunastart::varchar||' AND '||aLunaFin::varchar||'
                AND G.SEMNIFICATIE  NOT IN (800,801,900,901,950,951,1100,1000,1101)
                AND Coalesce(nc.part,0)'||sCondPart||
                  pkg_list_base_utils_cond_subunit('nc',null,null,aSubunitate)||'
        UNION ALL
            SELECT g.codgeneral,g.moneda,c.an,c.luna
            FROM general g
                INNER JOIN compens c ON g.coddoc = c.codcompens AND g.tipdoc = 28
            WHERE c.an * 12 + c.luna BETWEEN '||aLunastart||' AND '||aLunaFin||'
                AND G.SEMNIFICATIE  NOT IN (800,801,900,901,950,951,1100,1000,1101)
            AND(coalesce(c.partd,0)'||sCondPart||' OR COALESCE(c.partc,0)'||sCondPart||')'||
                pkg_list_base_utils_cond_subunit('c', null, null, aSubunitate)||'
        UNION ALL
            SELECT g.codgeneral,g.moneda,t1.an,t1.luna
            FROM general g
                INNER JOIN trezor1 t1 ON g.coddoc = t1.codtrezor1 AND g.tipdoc IN (29,30,31)
                INNER JOIN TREZOR T ON T.CODTREZOR = T1.CODTREZOR
            WHERE t1.an * 12 + t1.luna BETWEEN '||aLunastart::varchar||' AND '||aLunaFin::varchar||'
                AND G.SEMNIFICATIE  NOT IN (800,801,900,901,950,951,1100,1000,1101)
                AND coalesce(t1.CodPart,0)'||sCondPart||
                pkg_list_base_utils_cond_subunit('t', null, null, aSubunitate)||'
          ),
      res As (';
  IF info_kind = CT_INFO_MONEDA AND areConturi THEN
    sSelect := sSelect||'
        SELECT MON.CODMONEDA, MON.DEN_MONEDA
        FROM (Select a.*, PKG_LIST_BASE_UTILS_iCont_CodCont(o.icont, o.codpart, a.an*12+a.luna, o.semnificatie) acont
              From crs_doc a INNER JOIN obligpif o  ON a.codgeneral = o.codgeneral
             ) aa
             INNER JOIN nmonede mon ON mon.codmoneda = aa.moneda
             --INNER JOIN obligpif o  ON crs_doc.codgeneral = o.codgeneral
             INNER JOIN ncont n     on n.codcont = aa.acont  --PKG_LIST_BASE_UTILS_iCont_CodCont(o.icont, o.codpart, crs_doc.an*12+crs_doc.luna, o.semnificatie)
        WHERE n.codcont IN (SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODCONT'')
      UNION ALL
        SELECT MON.CODMONEDA, MON.DEN_MONEDA
        FROM (SELECT a.*, PKG_LIST_BASE_UTILS_iCont_CodCont(a.icont,a.codpart,a.an*12+a.luna,0) acont
              FROM NPARTSOLDLUNA a
             ) aa
             INNER JOIN nmonede mon ON mon.codmoneda = aa.codmoneda
             INNER JOIN ncont n     ON n.codcont = aa.acont '||  -- PKG_LIST_BASE_UTILS_iCont_CodCont(nps.icont,nps.codpart,Greatest(nps.an*12+nps.luna,'||vAnLunaIni::varchar||'),0)
      ' WHERE aa.an*12+aa.luna = '||(aLunaStart - 1)::varchar||'
              AND aa.codpart'||sCondPart||'
              AND n.codcont IN (SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODCONT'')';
  ELSIF info_kind = CT_INFO_MONEDA THEN
    sSelect := sSelect||'
        SELECT MON.CODMONEDA, MON.DEN_MONEDA
        FROM crs_doc
             INNER JOIN nmonede mon ON mon.codmoneda = crs_doc.moneda
      UNION ALL
        SELECT MON.CODMONEDA, MON.DEN_MONEDA
        FROM NPARTSOLDLUNA nps
             INNER JOIN nmonede mon ON mon.codmoneda = nps.codmoneda
        WHERE nps.an*12+nps.luna = '||(aLunaStart - 1)::varchar||'
              AND nps.codpart'||sCondPart;
  ELSIF info_kind = CT_INFO_CONT AND areMonezi THEN
    sSelect := sSelect||'
        SELECT N.CODCONT, N.SIMBOL||'' - ''||N.DEN_CONT CONT
        FROM (SELECT a.*, PKG_LIST_BASE_UTILS_iCont_CodCont(o.icont, o.codpart, a.an*12+a.luna, o.semnificatie) acont
              FROM crs_doc a
                   INNER JOIN obligpif o ON a.codgeneral = o.codgeneral
             ) aa
             INNER JOIN ncont n on n.codcont = aa.acont  --PKG_LIST_BASE_UTILS_iCont_CodCont(o.icont, o.codpart, crs_doc.an*12+crs_doc.luna, o.semnificatie)
        WHERE aa.moneda IN (SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODMONEDA'')
      UNION ALL
        SELECT N.CODCONT, N.SIMBOL||'' - ''||N.DEN_CONT CONT
        FROM (SELECT a.*, PKG_LIST_BASE_UTILS_iCont_CodCont(a.icont,a.codpart,a.an*12+a.luna,0) acont
              FROM NPARTSOLDLUNA a
             ) nps
             INNER JOIN ncont n ON n.codcont = nps.acont '||  --PKG_LIST_BASE_UTILS_iCont_CodCont(nps.icont,nps.codpart,Greatest(nps.an*12+nps.luna,'||vAnLunaIni::varchar||'),0)
      ' WHERE nps.an*12+nps.luna = '||(aLunaStart - 1)::varchar||'
              AND nps.codpart'||sCondPart||'
              AND nps.codmoneda IN (SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODMONEDA'')';
  ELSIF info_kind = CT_INFO_CONT THEN
    sSelect := sSelect||'
        SELECT N.CODCONT, N.SIMBOL||'' - ''||N.DEN_CONT CONT
        FROM (SELECT a.*, PKG_LIST_BASE_UTILS_iCont_CodCont(o.icont, o.codpart, a.an*12+a.luna, o.semnificatie) acont
              FROM crs_doc a
                   INNER JOIN obligpif o ON a.codgeneral = o.codgeneral
             ) aa
             INNER JOIN ncont n on n.codcont = aa.acont  --PKG_LIST_BASE_UTILS_iCont_CodCont(o.icont, o.codpart, crs_doc.an*12+crs_doc.luna, o.semnificatie)
        WHERE'||sFiltru||'
      UNION ALL
        SELECT N.CODCONT, N.SIMBOL||'' - ''||N.DEN_CONT CONT
        FROM (SELECT a.*, PKG_LIST_BASE_UTILS_iCont_CodCont(a.icont,a.codpart,a.an*12+a.luna,0) acont
              FROM NPARTSOLDLUNA a
             ) nps
             INNER JOIN ncont n ON n.codcont = nps.acont '||  --PKG_LIST_BASE_UTILS_iCont_CodCont(nps.icont,nps.codpart,Greatest(nps.an*12+nps.luna,'||vAnLunaIni::varchar||'),0)
      ' WHERE nps.an*12+nps.luna = '||(aLunaStart - 1)::varchar||'
              AND nps.codpart'||sCondPart||'
              AND'||sFiltru;
  END IF;

   sSelect := sSelect||'
               )
        SELECT '||sDistinctCol||'
        FROM res';
--    insert into x values('ssl',sSelect)  ;
  EXECUTE sCreateTable||sSelect;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectlunaan_setparams_listeproprii</obj_name>
  <obj_hashval>b9c4bd1cb8640b3f7d8ab80a5324b448</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectlunaan_setparams_listeproprii(puserid numeric, plistid numeric, plistver numeric, pluna1 numeric DEFAULT NULL::numeric, pluna2 numeric DEFAULT NULL::numeric, pan1 numeric DEFAULT NULL::numeric, pan2 numeric DEFAULT NULL::numeric, pdata1 character varying DEFAULT '?'::character varying, pdata2 character varying DEFAULT '?'::character varying, pint1luna1 numeric DEFAULT NULL::numeric, pint1luna2 numeric DEFAULT NULL::numeric, pint1an1 numeric DEFAULT NULL::numeric, pint1an2 numeric DEFAULT NULL::numeric, pint1data1 character varying DEFAULT '?'::character varying, pint1data2 character varying DEFAULT '?'::character varying, pint2luna1 numeric DEFAULT NULL::numeric, pint2luna2 numeric DEFAULT NULL::numeric, pint2an1 numeric DEFAULT NULL::numeric, pint2an2 numeric DEFAULT NULL::numeric, pint2data1 character varying DEFAULT '?'::character varying, pint2data2 character varying DEFAULT '?'::character varying, pint3luna1 numeric DEFAULT NULL::numeric, pint3luna2 numeric DEFAULT NULL::numeric, pint3an1 numeric DEFAULT NULL::numeric, pint3an2 numeric DEFAULT NULL::numeric, pint3data1 character varying DEFAULT '?'::character varying, pint3data2 character varying DEFAULT '?'::character varying, pint4luna1 numeric DEFAULT NULL::numeric, pint4luna2 numeric DEFAULT NULL::numeric, pint4an1 numeric DEFAULT NULL::numeric, pint4an2 numeric DEFAULT NULL::numeric, pint4data1 character varying DEFAULT '?'::character varying, pint4data2 character varying DEFAULT '?'::character varying, pint5luna1 numeric DEFAULT NULL::numeric, pint5luna2 numeric DEFAULT NULL::numeric, pint5an1 numeric DEFAULT NULL::numeric, pint5an2 numeric DEFAULT NULL::numeric, pint5data1 character varying DEFAULT '?'::character varying, pint5data2 character varying DEFAULT '?'::character varying, pval1 character varying DEFAULT NULL::character varying, pval2 character varying DEFAULT NULL::character varying, pval3 character varying DEFAULT NULL::character varying, pval4 character varying DEFAULT NULL::character varying, pval5 character varying DEFAULT NULL::character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLuna1 numeric(2,0);
  xLuna2 numeric(2,0);
  xAn1   numeric(4,0);
  xAn2   numeric(4,0);
  xData1 date;
  xData2 date;
  xInt1Luna1 numeric(2,0);
  xInt1Luna2 NUMERIC(2,0);
  xInt1An1   NUMERIC(4,0);
  xInt1An2   NUMERIC(4,0);
  xInt1Data1  Date;
  xInt1Data2  Date;
  xInt2Luna1 NUMERIC(2,0);
  xInt2Luna2 NUMERIC(2,0);
  xInt2An1   NUMERIC(4,0);
  xInt2An2   NUMERIC(4,0);
  xInt2Data1  Date;
  xInt2Data2  Date;
  xInt3Luna1 NUMERIC(2,0);
  xInt3Luna2 NUMERIC(2,0);
  xInt3An1   NUMERIC(4,0);
  xInt3An2   NUMERIC(4,0);
  xInt3Data1  Date;
  xInt3Data2  Date;
  xInt4Luna1 NUMERIC(2,0);
  xInt4Luna2 NUMERIC(2,0);
  xInt4An1   NUMERIC(4,0);
  xInt4An2   NUMERIC(4,0);
  xInt4Data1  Date;
  xInt4Data2  Date;
  xInt5Luna1 NUMERIC(2,0);
  xInt5Luna2 NUMERIC(2,0);
  xInt5An1   NUMERIC(4,0);
  xInt5An2   NUMERIC(4,0);
  xInt5Data1  Date;
  xInt5Data2  Date;
  Cod    numeric;
BEGIN
  --Florin 04.09.2024 - sinc. Oracle
  --Florin 06.12.2022 - sinc. Oracle (05.12.2022)
  --Bogdan 14.10.2022 - corectii
  --Florin 11.10.2022 - sinc. Oracle
  --Florin 16.06.2021 - fixat 50562
  --Adina 25.02.2021
  xLuna1 := pLuna1;
  xLuna2 := pLuna2;
  xAn1   := pAn1;
  xAn2   := pAn2;

  xInt1Luna1 := pInt1Luna1;
  xInt1Luna2 := pInt1Luna2;
  xInt1An1   := pInt1An1;
  xInt1An2   := pInt1An2;

  xInt2Luna1 := pInt2Luna1;
  xInt2Luna2 := pInt2Luna2;
  xInt2An1   := pInt2An1;
  xInt2An2   := pInt2An2;

  xInt3Luna1 := pInt3Luna1;
  xInt3Luna2 := pInt3Luna2;
  xInt3An1   := pInt3An1;
  xInt3An2   := pInt3An2;


  xInt4Luna1 := pInt4Luna1;
  xInt4Luna2 := pInt4Luna2;
  xInt4An1   := pInt4An1;
  xInt4An2   := pInt4An2;

  xInt5Luna1 := pInt5Luna1;
  xInt5Luna2 := pInt5Luna2;
  xInt5An1   := pInt5An1;
  xInt5An2   := pInt5An2;

  IF (xLUNA1 IS NOT NULL) AND (xAN1 IS NOT NULL) AND (xLUNA2 IS NOT NULL) AND (xAN2 IS NOT NULL) then
    IF pData1 &lt;&gt; '?' AND pData1 IS NOT NULL THEN
      xData1 := To_Date(pData1, 'dd.mm.yyyy');
      IF xLuna1 = 0 THEN
        xLuna1 := Extract( Month FROM xData1);
      END IF;

      IF  xAn1 = 0 THEN
        xAn1 := Extract( Year FROM xData1);
      END IF;
    ELSE
      xData1 := To_Date('01.' || lpad(coalesce(trunc(xLUNA1)::varchar,''), 2, '0') || '.' || coalesce(xAN1::varchar,''), 'dd.mm.yyyy');
    END IF;

    IF  pData2 &lt;&gt; '?' AND pData2 IS NOT NULL THEN
      xData2 := To_Date(pData2, 'dd.mm.yyyy');
      IF  xLuna2 = 0 THEN
        xLuna2 := Extract( Month FROM xData2);
      END IF;

      IF  xAn2 = 0 THEN
        xAn2 := Extract( Year FROM xData2);
      END IF;
    ELSE
      xData2 := Last_Day(To_Date('01.' || lpad(coalesce(trunc(xLUNA2)::varchar,''), 2, '0') || '.' || coalesce(xAN2::varchar,''), 'dd.mm.yyyy'));
    END IF;
  END IF;

--interval1

  IF (xInt1LUNA1 IS NOT NULL) AND (xInt1AN1 IS NOT NULL) AND (xInt1LUNA2 IS NOT NULL) AND (xInt1AN2 IS NOT NULL) THEN
    IF pInt1Data1 &lt;&gt; '?' THEN
      xInt1Data1 := To_Date(pInt1Data1,'dd.mm.yyyy');
      if xInt1Luna1 = 0 then xInt1Luna1 := Extract(Month from xInt1Data1); end if;
      if xInt1An1   = 0 then xInt1An1   := Extract(Year from xInt1Data1); end if;
    ELSE
      xInt1Data1 := To_Date('01.'||xInt1LUNA1::varchar||'.'||xInt1AN1::varchar,'dd.mm.yyyy');
     END IF;
    IF pInt1Data2 &lt;&gt; '?' THEN
      xInt1Data2 := To_Date(pInt1Data2,'dd.mm.yyyy');
      if xInt1Luna2 = 0 then xInt1Luna2 := Extract(Month from  xInt1Data2); end if;
      if xInt1An2   = 0 then xInt1An2   := Extract(Year from xInt1Data2); end if;
    ELSE
      xInt1Data2 := Last_Day(To_Date(xInt1LUNA2||'.'||xInt1AN2,'mm.yyyy'));
    END IF;
  END IF;
  --interval2
  IF (xInt2LUNA1 IS NOT NULL) AND (xInt2AN1 IS NOT NULL) AND (xInt2LUNA2 IS NOT NULL) AND (xInt2AN2 IS NOT NULL) THEN
    IF pInt2Data1 &lt;&gt; '?' THEN
      xInt2Data1 := To_Date(pInt2Data1,'dd.mm.yyyy');
      if xInt2Luna1 = 0 then xInt2Luna1 := Extract(Month from xInt2Data1); end if;
      if xInt2An1   = 0 then xInt2An1   := Extract(Year from xInt2Data1); end if;
    ELSE
      xInt2Data1 := To_Date('01.'||xInt2LUNA1||'.'||xInt2AN1,'dd.mm.yyyy');
    END IF;
    IF pInt2Data2 &lt;&gt; '?' THEN
      xInt2Data2 := To_Date(pInt2Data2,'dd.mm.yyyy');
      if xInt2Luna2 = 0 then xInt2Luna2 := Extract(Month from  xInt2Data2); end if;
      if xInt2An2   = 0 then xInt2An2   := Extract(Year from xInt2Data2); end if;
    ELSE
      xInt2Data2 := Last_Day(To_Date(xInt2LUNA2||'.'||xInt2AN2,'mm.yyyy'));
    END IF;
  END IF;
    --interval3
  IF (xInt3LUNA1 IS NOT NULL) AND (xInt3AN1 IS NOT NULL) AND (xInt3LUNA2 IS NOT NULL) AND (xInt3AN2 IS NOT NULL) THEN
    IF pInt3Data1 &lt;&gt; '?' THEN
      xInt3Data1 := To_Date(pInt3Data1,'dd.mm.yyyy');
      if xInt3Luna1 = 0 then xInt3Luna1 := Extract(Month from xInt3Data1); end if;
      if xInt3An1   = 0 then xInt3An1   := Extract(Year from xInt3Data1); end if;
    ELSE
      xInt3Data1 := To_Date('01.'||xInt3LUNA1||'.'||xInt3AN1,'dd.mm.yyyy');
    END IF;
    IF pInt3Data2 &lt;&gt; '?' THEN
      xInt3Data2 := To_Date(pInt3Data2,'dd.mm.yyyy');
      if xInt3Luna2 = 0 then xInt3Luna2 := Extract(Month from  xInt3Data2); end if;
      if xInt3An2   = 0 then xInt3An2   := Extract(Year from xInt3Data2); end if;
    ELSE
      xInt3Data2 := Last_Day(To_Date(xInt3LUNA2||'.'||xInt3AN2,'mm.yyyy'));
    END IF;
  END IF;
    --interval4
  IF (xInt4LUNA1 IS NOT NULL) AND (xInt4AN1 IS NOT NULL) AND (xInt4LUNA2 IS NOT NULL) AND (xInt4AN2 IS NOT NULL) THEN
    IF pInt4Data1 &lt;&gt; '?' THEN
      xInt4Data1 := To_Date(pInt4Data1,'dd.mm.yyyy');
      if xInt4Luna1 = 0 then xInt4Luna1 := Extract(Month from xInt4Data1); end if;
      if xInt4An1   = 0 then xInt4An1   := Extract(Year from xInt4Data1); end if;
    ELSE
      xInt4Data1 := To_Date('01.'||xInt4LUNA1||'.'||xInt4AN1,'dd.mm.yyyy');
    END IF;
    IF pInt4Data2 &lt;&gt; '?' THEN
      xInt4Data2 := To_Date(pInt4Data2,'dd.mm.yyyy');
      if xInt4Luna2 = 0 then xInt4Luna2 := Extract(Month from  xInt4Data2); end if;
      if xInt4An2   = 0 then xInt4An2   := Extract(Year from xInt4Data2); end if;
    ELSE
      xInt4Data2 := Last_Day(To_Date(xInt4LUNA2||'.'||xInt4AN2,'mm.yyyy'));
    END IF;
  END IF;
    --interval5
  IF (xInt5LUNA1 IS NOT NULL) AND (xInt5AN1 IS NOT NULL) AND (xInt5LUNA2 IS NOT NULL) AND (xInt5AN2 IS NOT NULL) THEN
    IF pInt5Data1 &lt;&gt; '?' THEN
      xInt5Data1 := To_Date(pInt5Data1,'dd.mm.yyyy');
      if xInt5Luna1 = 0 then xInt5Luna1 := Extract(Month from xInt5Data1); end if;
      if xInt5An1   = 0 then xInt5An1   := Extract(Year from xInt5Data1); end if;
    ELSE
      xInt5Data1 := To_Date('01.'||xInt5LUNA1||'.'||xInt5AN1,'dd.mm.yyyy');
    END IF;
    IF pInt5Data2 &lt;&gt; '?' THEN
      xInt5Data2 := To_Date(pInt5Data2,'dd.mm.yyyy');
      if xInt5Luna2 = 0 then xInt5Luna2 := Extract(Month from  xInt5Data2); end if;
      if xInt5An2   = 0 then xInt5An2   := Extract(Year from xInt5Data2); end if;
    ELSE
      xInt5Data2 := Last_Day(To_Date(xInt5LUNA2||'.'||xInt5AN2,'mm.yyyy'));
    END IF;
  END IF;


  BEGIN
    SELECT COALESCE(codparamliste, 0) into strict Cod FROM paramliste WHERE userid = puserid and  listid = plistid and  listver = plistver;
  EXCEPTION WHEN OTHERS THEN
    COD := 0;
  END;

  if Cod = 0 then
    Cod := NextVal('SEQ_paramliste');
    Insert into paramliste (
      codparamliste,
      userid,
      listid,
      listver,
      data1,
      data2,
      an1,
      luna1,
      an2,
      luna2,
      int1data1,
      int1data2,
      int1an1,
      int1luna1,
      int1an2,
      int1luna2,
      int2data1,
      int2data2,
      int2an1,
      int2luna1,
      int2an2,
      int2luna2,
      int3data1,
      int3data2,
      int3an1,
      int3luna1,
      int3an2,
      int3luna2,
      int4data1,
      int4data2,
      int4an1,
      int4luna1,
      int4an2,
      int4luna2,
      int5data1,
      int5data2,
      int5an1,
      int5luna1,
      int5an2,
      int5luna2,
      val1,
      val2,
      val3,
      val4,
      val5)
    values (
      cod,
      puserid,
      plistid,
      plistver,
      xdata1,
      xdata2,
      xan1,
      xluna1,
      xan2,
      xluna2,
      xInt1data1,
      xInt1data2,
      xInt1an1,
      xInt1luna1,
      xInt1an2,
      xInt1luna2,
      xInt2data1,
      xInt2data2,
      xInt2an1,
      xInt2luna1,
      xInt2an2,
      xInt2luna2,
      xInt3data1,
      xInt3data2,
      xInt3an1,
      xInt3luna1,
      xInt3an2,
      xInt3luna2,
      xInt4data1,
      xInt4data2,
      xInt4an1,
      xInt4luna1,
      xInt4an2,
      xInt4luna2,
      xInt5data1,
      xInt5data2,
      xInt5an1,
      xInt5luna1,
      xInt5an2,
      xInt5luna2,
      pVal1,
      pVal2,
      pVal3,
      pVal4,
      pVal5
 );
  else
    update paramliste set
      data1  = xdata1 ,
      data2  = xdata2 ,
      an1    = xan1   ,
      luna1  = xluna1 ,
      an2    = xan2   ,
      luna2  = xluna2,
      int1data1  = xInt1data1 ,
      int1data2  = xInt1data2 ,
      int1an1    = xInt1an1   ,
      int1luna1  = xInt1luna1 ,
      int1an2    = xInt1an2   ,
      int1luna2  = xInt1luna2,
      int2data1  = xInt2data1 ,
      int2data2  = xInt2data2 ,
      int2an1    = xInt2an1   ,
      int2luna1  = xInt2luna1 ,
      int2an2    = xInt2an2   ,
      int2luna2  = xInt2luna2,
      int3data1  = xInt3data1 ,
      int3data2  = xInt3data2 ,
      int3an1    = xInt3an1   ,
      int3luna1  = xInt3luna1 ,
      int3an2    = xInt3an2   ,
      int3luna2  = xInt3luna2,
      int4data1  = xInt4data1 ,
      int4data2  = xInt4data2 ,
      int4an1    = xInt4an1   ,
      int4luna1  = xInt4luna1 ,
      int4an2    = xInt4an2   ,
      int4luna2  = xInt4luna2,
      int5data1  = xInt5data1 ,
      int5data2  = xInt5data2 ,
      int5an1    = xInt5an1   ,
      int5luna1  = xInt5luna1 ,
      int5an2    = xInt5an2   ,
      int5luna2  = xInt5luna2 ,
      val1       = pVal1      ,
      val2       = pVal2      ,
      val3       = pVal3      ,
      val4       = pVal4      ,
      val5       = pVal5
    where codparamliste = cod;
  end if;

end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_utilfisacont_umple_tmp_lst_jurnal1</obj_name>
  <obj_hashval>e82d005579b3ee316964cca4c11e75db</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_utilfisacont_umple_tmp_lst_jurnal1(p_plan numeric, p_lunaini numeric, p_lunafin numeric, p_subcurenta numeric, p_listid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  -- BogdanL  27.07.2020
  UPDATE distribchelt
    SET  datacreare = last_day(to_date(coalesce(to_char(an, 'fm0000'),'') || coalesce(to_char(luna, 'fm00'),''), 'yyyymm'))
  where datacreare IS NULL ;

  DELETE FROM tmp_lst_jurnal1;

  INSERT INTO tmp_lst_jurnal1 (
      codjurnal1, coddoc, tipdoc, indexlocal, codbazad, tipbazad, icontbazad, coddescrd,
      icontd, tipcontd, analiticcontd, codbazac, tipbazac, icontbazac, coddescrc, icontc,
      tipcontc, analiticcontc, gest, valoare, valoarev, obs, an, luna, dirty, subunitatea,
      datadoc, document, codcentru, valoaregrup, codanalizanod, valoare_ifrs, valoarev_ifrs,
      codintr1, codobligpif, codnc1 )
  SELECT
      j1.codjurnal1, j1.coddoc, j1.tipdoc, j1.indexlocal, j1.codbazad, j1.tipbazad, j1.icontbazad,
      j1.coddescrd, j1.icontd, j1.tipcontd, j1.analiticcontd, j1.codbazac, j1.tipbazac, j1.icontbazac,
      j1.coddescrc, j1.icontc, j1.tipcontc, j1.analiticcontc, j1.gest, j1.valoare, j1.valoarev,
      j1.obs, j1.an, j1.luna, j1.dirty, j1.subunitatea, j1.datadoc, j1.document, j1.codcentru, j1.valoaregrup,
      j1.codanalizanod, j1.valoare_ifrs, j1.valoarev_ifrs, cv.codintr1, cv.codobligpif, cv.codnc1
  FROM jurnal1 j1
    LEFT JOIN cheltavans cv ON  cv.codcheltavans = j1.coddoc AND  j1.tipdoc = 52
  WHERE   j1.an * 12 + j1.luna BETWEEN p_LunaIni AND p_LunaFin
    AND  CASE  WHEN  p_SubCurenta=1 THEN j1.subunitatea ELSE  p_SubCurenta END  = j1.subunitatea;


  UPDATE tmp_lst_jurnal1 j1 set
    BazaD      = pkg_list_utilfisacont_GET_BAZA(TipBazaD),
    InfoBazaD  = pkg_list_utilfisacont_GET_INFOBAZA(TipBazaC, CodBazaC, IndexLocal, An, Luna),
    BazaC      = pkg_list_utilfisacont_GET_BAZA(TipBazaC),
    InfoBazaC  = pkg_list_utilfisacont_GET_INFOBAZA(TipBazaC, CodBazaC, IndexLocal, An, Luna),
    DescrD     = pkg_list_utilfisacont_GET_DESCR(TipContD),
    InfoDescrD = pkg_list_utilfisacont_GET_INFODESCR(TipContD, CodDescrD, An, Luna),
    DescrC     = pkg_list_utilfisacont_GET_DESCR(TipContC),
    InfoDescrC = pkg_list_utilfisacont_GET_INFODESCR(TipContC, CodDescrC, An, Luna),
    CodContd   = (SELECT pkg_jurnal_GETCONTFORJURNAL.WME_RESULT FROM pkg_jurnal_GETCONTFORJURNAL(NULL,CodDescrD, IcontD, TipContD, AnaliticContD, An, Luna)),
    CodContc   = (SELECT pkg_jurnal_GETCONTFORJURNAL.WME_RESULT FROM pkg_jurnal_GETCONTFORJURNAL(NULL,CodDescrC, IcontC, TipContC, AnaliticContC, An, Luna));

  IF p_ListId IN (332) THEN
    DELETE FROM tmp_lst_jurnal1 j1
    where  NOT  EXISTS ( SELECT codcont FROM ncont WHERE codcont = j1.codcontd and clasa IN (6, 7) )
      AND  NOT  EXISTS ( SELECT codcont FROM ncont WHERE codcont = j1.codcontc and clasa IN (6, 7) );
  END IF;

  UPDATE tmp_lst_jurnal1 j1
  set
  (articol, codobiect, cant, obslinie, coddoc1, userid)
  =
  (
    SELECT obj.denumire, i1.codobiect, i1.cant, i1.obs, i1.codintr1, i.userid
    FROM intrari1 i1
        INNER JOIN intrari i   ON  i.codintr    = i1.codintr
        LEFT  JOIN nartobj obj ON  i1.codobiect = obj.codobiect
    WHERE
       i1.codintr1 = j1.indexlocal
  )
  where j1.tipdoc IN (1, 2, 3, 4, 6, 7, 9);

  UPDATE tmp_lst_jurnal1 j1
  set
  (articol, codobiect, cant, obslinie, coddoc1, userid)
  = (
      SELECT obj.denumire, i1.codobiect, i1.cant, i1.obs, i1.codintr1, i.userid
      FROM dvi1
          INNER JOIN intrari1 i1  ON  i1.codintr1  = dvi1.codintr1
          INNER JOIN intrari  i   ON  i.codintr    = i1.codintr
          LEFT  JOIN nartobj  obj ON  i1.codobiect = obj.codobiect
      WHERE
         dvi1.coddvi1 = j1.indexlocal
    )
    where j1.tipdoc IN (5);

  UPDATE tmp_lst_jurnal1 j1
  set (articol, codobiect, cant, userid)
  = (
      SELECT obj.denumire, t1.codobiect, t1.cant, t.userid
      FROM transf1 t1
        INNER JOIN transf  t   ON  t.codtransf  = t1.codtransf
        LEFT  JOIN nartobj obj ON  t1.codobiect = obj.codobiect
      WHERE
         t1.codtransf1 = j1.indexlocal
      )
    where j1.tipdoc IN (12, 13);

  UPDATE tmp_lst_jurnal1 j1
  SET
    (articol, codobiect, cant, obslinie, coddoc1, userid)
    = (
        SELECT obj.denumire, i1.codobiect, i1.cant, i1.obs, i1.codies1, i.userid
        FROM iesiri1 i1
            INNER JOIN iesiri  i   ON  i.codies     = i1.codies
            LEFT  JOIN nartobj obj ON  i1.codobiect = obj.codobiect
        WHERE
           i1.codies1 = j1.indexlocal
      )
  where j1.tipdoc IN (14, 15, 16, 19, 20, 21, 22, 23, 24, 26);

  UPDATE tmp_lst_jurnal1 j1
  SET
  (coddoc1, userid) = (SELECT t1.codtrezor1, t1.userid FROM trezor1 t1 WHERE t1.codtrezor1 = j1.indexlocal)
  where   j1.tipdoc IN (29, 30, 31, 33);

  UPDATE tmp_lst_jurnal1 j1
  SET  (coddoc1, userid) = (SELECT nc1.codnc1, nc.userid FROM nc1 INNER JOIN nc ON  nc.codnc = nc1.codnc WHERE nc1.codnc1 = j1.indexlocal)
  WHERE j1.tipdoc = 35  ;

  UPDATE tmp_lst_jurnal1 j1
  SET
  userid = (SELECT PKG_LIST_BASE_UTILS_GetUserDoc.WME_RESULT FROM PKG_LIST_BASE_UTILS_GetUserDoc(null, j1.coddoc, j1.tipdoc, null))
  WHERE userid is null ;

  UPDATE tmp_lst_jurnal1 j1 SET pret = valoare / cant WHERE j1.cant &lt;&gt; 0 ;

  UPDATE tmp_lst_jurnal1 j1
  SET
    (DocLegatura, CodMoneda, CodPart)
    =
    (SELECT coalesce(c.prefixdoc, '') || coalesce(c.nrdoc::varchar , '') || '/' || coalesce(To_Char(c.datadoc, 'dd.mm.yyyy'), ''), c.moneda, c.partener
     FROM intrlink l
          inner join comanda1 c1 ON c1.codcomanda1 = l.codliniecomanda
          inner join comanda  c  ON c1.codcomanda  = c.codcomanda
      WHERE l.codintr1 = j1.indexlocal
    )
  WHERE j1.tipdoc in (1, 2, 4) and exists (SELECT l.codliniecomanda FROM intrlink l WHERE l.codintr1 = j1.indexlocal) ;

  UPDATE tmp_lst_jurnal1 j1
  SET
    (DocLegatura, CodMoneda, CodPart)
    =
    (SELECT coalesce(i.prefixdoc, '') || coalesce(i.nrdoc::varchar , '') || '/' || coalesce(To_Char(i.datadoc, 'dd.mm.yyyy'), ''), i.moneda, i.partener
     FROM intrasteptlink l
          inner join intrari1 i1 ON i1.codintr1 = l.codliniefactura
          inner join intrari  i  ON i1.codintr  = i.codintr
     WHERE l.codintr1 = j1.indexlocal
    )
  WHERE j1.tipdoc in (2) and exists (SELECT l.codliniefactura FROM intrasteptlink l WHERE l.codintr1 = j1.indexlocal) ;

  UPDATE tmp_lst_jurnal1 j1
  SET
    (DocLegatura, CodMoneda, CodPart)
    =
    ( SELECT coalesce(i.prefixdoc, '') || coalesce(i.nrdoc::varchar , '') || '/' || coalesce(To_Char(i.datadoc, 'dd.mm.yyyy'), ''), i.moneda, i.partener
      FROM intrlink l
          inner join intrari1 i1 ON i1.codintr1 = l.codlinieaviz
          inner join intrari  i  ON i1.codintr  = i.codintr
      WHERE l.codintr1 = j1.indexlocal
    )
  WHERE j1.tipdoc in (9) and exists (SELECT l.codlinieaviz FROM intrlink l WHERE l.codintr1 = j1.indexlocal) ;

  UPDATE tmp_lst_jurnal1 j1
  SET
    (DocLegatura, CodMoneda, CodPart)
    =
    ( SELECT coalesce(c.prefixdoc, '') || coalesce(c.nrdoc::varchar , '') || '/' || coalesce(To_Char(c.datadoc, 'dd.mm.yyyy'), ''), c.moneda, c.partener
      FROM intrlink l
          inner join comanda1 c1 ON c1.codcomanda1 = l.codliniecomanda
          inner join comanda  c  ON c1.codcomanda  = c.codcomanda
      WHERE l.codintr1 = j1.indexlocal
    )
  WHERE j1.tipdoc in (9) and exists (SELECT l.codliniecomanda FROM intrlink l WHERE l.codintr1 = j1.indexlocal) ;

  UPDATE tmp_lst_jurnal1 j1
  SET
    (DocLegatura, CodMoneda, CodPart)
    =
    ( SELECT coalesce(i.prefixdoc, '') || coalesce(i.nrdoc::varchar , '') || '/' || coalesce(To_Char(i.datadoc, 'dd.mm.yyyy'), ''), i.moneda, i.partener
      FROM dvi1
          inner join intrari1 ii1 ON dvi1.codintr1 = ii1.codintr1
          inner join intrlink l   ON ii1.codintr1  = l.codintr1
          inner join intrari1 i1  ON i1.codintr1   = l.codlinieaviz
          inner join intrari  i   ON i1.codintr    = i.codintr
      WHERE dvi1.coddvi1 = j1.indexlocal
    )
  WHERE j1.tipdoc in (5) and exists ( SELECT l.codlinieaviz
                                      FROM dvi1
                                          inner join intrari1 ii1 ON dvi1.codintr1 = ii1.codintr1
                                          inner join intrlink l   ON ii1.codintr1  = l.codintr1
                                      WHERE dvi1.coddvi1 = j1.indexlocal and l.codlinieaviz &gt; 0
                                    ) ;

  UPDATE tmp_lst_jurnal1 j1
  SET
    (DocLegatura, CodMoneda, CodPart)
    =
    ( SELECT coalesce(c.prefixdoc, '') || coalesce(c.nrdoc::varchar , '') || '/' || coalesce(To_Char(c.datadoc, 'dd.mm.yyyy'), ''), c.moneda, c.partener
      FROM dvi1
          inner join intrari1 ii1 ON dvi1.codintr1  = ii1.codintr1
          inner join intrlink l   ON ii1.codintr1   = l.codintr1
          inner join comanda1 c1  ON c1.codcomanda1 = l.codliniecomanda
          inner join comanda  c   ON c1.codcomanda  = c.codcomanda
      WHERE dvi1.coddvi1 = j1.indexlocal
    )
  WHERE j1.tipdoc in (5) and exists ( SELECT l.codliniecomanda
                                      FROM dvi1
                                          inner join intrari1 ii1 ON dvi1.codintr1 = ii1.codintr1
                                          inner join intrlink l   ON ii1.codintr1  = l.codintr1
                                      WHERE dvi1.coddvi1 = j1.indexlocal and l.codliniecomanda &gt; 0
                                    ) ;

  UPDATE tmp_lst_jurnal1 j1
  SET
    (DocLegatura, CodMoneda, CodPart)
    =
    ( SELECT coalesce(c.prefixdoc, '') || coalesce(c.nrdoc::varchar , '') || '/' || coalesce(To_Char(c.datadoc, 'dd.mm.yyyy'), ''), c.moneda, c.partener
      FROM intrari1 i1
          inner join comanda1 c1 ON c1.codcomanda1 = i1.codcmdint1
          inner join comanda  c  ON c1.codcomanda  = c.codcomanda
      WHERE i1.codintr1 = j1.indexlocal
    )
  WHERE j1.tipdoc = 7 and exists (SELECT c1.codcomanda1 FROM comanda1 c1 inner join intrari1 i1 ON c1.codcomanda1 = i1.codcmdint1 WHERE i1.codintr1 = j1.indexlocal) ;

  UPDATE tmp_lst_jurnal1 j1
  SET
    (DocLegatura, CodMoneda, CodPart)
    =
    ( SELECT coalesce(c.prefixdoc, '') || coalesce(c.nrdoc::varchar , '') || '/' || coalesce(To_Char(c.datadoc, 'dd.mm.yyyy'), ''), c.moneda, c.partener
      FROM ieslink l
          inner join comanda1 c1 ON c1.codcomanda1 = l.codliniecomanda
          inner join comanda  c  ON c1.codcomanda  = c.codcomanda
      WHERE l.codies1 = j1.indexlocal
    )
  WHERE j1.tipdoc in (19, 20, 21) and exists (SELECT l.codliniecomanda FROM ieslink l WHERE l.codies1 = j1.indexlocal) ;

  UPDATE tmp_lst_jurnal1 j1
  SET
    (DocLegatura, CodMoneda, CodPart)
    =
    ( SELECT coalesce(i.prefixdoc, '') || coalesce(i.nrdoc::varchar , '') || '/' || coalesce(To_Char(i.datadoc, 'dd.mm.yyyy'), ''), i.moneda, i.partener
      FROM ieslink l
          inner join iesiri1 i1 ON i1.codies1 = l.codlinieaviz
          inner join iesiri  i  ON i1.codies  = i.codies
      WHERE l.codies1 = j1.indexlocal
    )
  WHERE j1.tipdoc in (26, 22) and exists (SELECT l.codlinieaviz FROM ieslink l WHERE l.codies1 = j1.indexlocal) ;

  UPDATE tmp_lst_jurnal1 j1
  SET
    (DocLegatura, CodMoneda, CodPart)
    =
    ( SELECT coalesce(c.prefixdoc, '') || coalesce(c.nrdoc::varchar , '') || '/' || coalesce(To_Char(c.datadoc, 'dd.mm.yyyy'), ''), c.moneda, c.partener
      FROM iesiri1 i1
          inner join comanda1 c1 ON c1.codcomanda1 = i1.codcmdint1
          inner join comanda  c  ON c1.codcomanda  = c.codcomanda
      WHERE i1.codies1 = j1.indexlocal
    )
  WHERE j1.tipdoc = 24 and exists (SELECT c1.codcomanda1 FROM comanda1 c1 inner join iesiri1 i1 ON c1.codcomanda1 = i1.codcmdint1 WHERE i1.codies1 = j1.indexlocal) ;

  UPDATE tmp_lst_jurnal1 j1
  SET
    (datacreare, codpart, codmonedadoc, codagenda, cod_codfiscal, valdoc, tvadoc, curs, codauto)
    =
    ( SELECT i.datacreare, i.partener, i.moneda, i.codlocatie, i.codfiscal, i.valdoc, i.tvadoc, i.curs, i.codauto
      FROM intrari i WHERE i.codintr = j1.coddoc
    )
  WHERE j1.tipdoc in (1, 2, 3, 4, 5, 6, 7, 9) ;

  UPDATE tmp_lst_jurnal1 j1
  SET
    (datacreare, valdoc, tvadoc)
    =
    (SELECT t.datacreare, t.valdoc, t.tvadoc FROM transf t WHERE t.codtransf = j1.coddoc)
  WHERE j1.tipdoc in (12, 13) ;

  UPDATE tmp_lst_jurnal1 j1
  SET
    (datacreare, codpart, codmonedadoc, codagenda, cod_codfiscal, valdoc, tvadoc, curs, codauto)
    =
    ( SELECT i.datacreare, i.partener, i.moneda, i.codlocatie, i.codfiscal, i.valdoc, i.tvadoc, i.curs, i.codauto
      FROM iesiri i WHERE i.codies = j1.coddoc
    )
  WHERE j1.tipdoc in (14, 15, 16, 19, 20, 23, 24, 26) ;

  UPDATE tmp_lst_jurnal1 j1
  SET
    (datacreare, codpart, codmonedadoc) = (  SELECT c.datacreare, c.partener, c.moneda FROM contract c WHERE c.codcontract = j1.coddoc)
  WHERE j1.tipdoc in (25) ;

  UPDATE tmp_lst_jurnal1 j1
  SET
    datacreare = (SELECT c.datacreare FROM compens c WHERE c.codcompens = j1.coddoc)
  WHERE j1.tipdoc in (28) ;

  UPDATE tmp_lst_jurnal1 j1
  SET
    (datacreare, codmonedadoc, obslinie, valdoc, tvadoc, curs, codauto)
    =
    ( SELECT t.datacreare, t.monedapers, t1.obs, t1.valdoc, sum(g.tva), t1.curs, min(o.codnparcaut)
      FROM trezor1 t1
          inner join trezor   t ON t.codtrezor  = t1.codtrezor
          inner join general  g ON g.coddoc     = t1.codtrezor1 and g.tipdoc = t.tipdoc
          inner join obligpif o ON o.codgeneral = g.codgeneral
      WHERE t1.codtrezor = j1.coddoc and t1.codtrezor1 = j1.indexlocal
      group BY t.datacreare, t.monedapers, t1.obs, t1.valdoc, t1.curs
    )
  WHERE j1.tipdoc in (29, 30, 31, 33) ;

  UPDATE tmp_lst_jurnal1 j1
  SET
    (datacreare, obslinie, codmonedadoc, valdoc, curs)
    =
    ( SELECT nc.datacreare, nc1.obs, nc.moneda, nc.valoare, nc.curs
      FROM nc1 inner join nc ON nc.codnc = nc1.codnc
      WHERE nc.codnc = j1.coddoc and j1.indexlocal = nc1.codnc1
    )
  WHERE j1.tipdoc in (35) ;

  UPDATE tmp_lst_jurnal1 j1
  SET
    datacreare = (SELECT dc.datacreare FROM distribchelt dc WHERE dc.coddistribchelt = j1.coddoc)
  WHERE j1.tipdoc in (76) ;

  UPDATE tmp_lst_jurnal1 j1
  SET
    articol = ( SELECT obj.denumire
                FROM intrari1 i1
                    inner join nartobj    obj ON i1.codobiect = obj.codobiect
                    inner join cheltavans cv  ON cv.codintr1  = i1.codintr1
                WHERE j1.coddoc = cv.codcheltavans and coalesce(cv.codintr1, 0) &gt; 0
              )
  WHERE j1.tipdoc = 52 and j1.codintr1 &gt; 0 ;

  UPDATE tmp_lst_jurnal1 j1
  SET
    articol = (SELECT
                    case
                      when O.SEMNIFICATIE = 900 then 'Direct pe cheltuieli(TVA)'
                      else 'Datorii, taxe, impozite'
                    end
                  FROM obligpif o inner join cheltavans cv ON cv.codobligpif = o.codobligpif
                  WHERE j1.coddoc = cv.codcheltavans and o.semnificatie in (900, 950) and coalesce(cv.codobligpif, 0) &gt; 0
              )
  WHERE j1.tipdoc = 52 and j1.codobligpif &gt; 0 ;

  UPDATE tmp_lst_jurnal1 j1
  SET
    articol = (SELECT 'Chelt Avans din NC ' FROM nc1 inner join cheltavans cv ON cv.codnc1 = nc1.codnc1 WHERE j1.coddoc = cv.codcheltavans and coalesce(cv.codnc1, 0) &gt; 0)
  WHERE j1.tipdoc = 52 and j1.codnc1 &gt; 0 ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_make_manevra_nc</obj_name>
  <obj_hashval>954b16a065b3ca08b61bec65e132db34</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_make_manevra_nc(acodncredit numeric, cucommit boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Florin 05.01.2023 - sinc. Oracle
  --Bogdan 06.01.2021
  DELETE
  FROM manevra_notecredit;

  perform set_config ('PKG_NOTECREDIT.KArtDiscAcTer'      , COALESCE ( (fnc_GetValConstantalucru ('ArtDiscAcTer'      )) , '0') ::varchar, false);
  perform set_config ('PKG_NOTECREDIT.KArtDiscAcVol'      , COALESCE ( (fnc_GetValConstantalucru ('ArtDiscAcVol'      )) , '0') ::varchar, false);
  perform set_config ('PKG_NOTECREDIT.KArtDiscAcCant'     , COALESCE ( (fnc_GetValConstantalucru ('ArtDiscAcCant'     )) , '0') ::varchar, false);
  perform set_config ('PKG_NOTECREDIT.KArtPenAcTer'       , COALESCE ( (fnc_GetValConstantalucru ('ArtPenAc'          )) , '0') ::varchar, false);
  perform set_config ('PKG_NOTECREDIT.KArtDiscOffInvoiceC', COALESCE ( (fnc_GetValConstantalucru ('ArtDiscOffInvoiceC')) , '0') ::varchar, false);
  perform set_config ('PKG_NOTECREDIT.KArtDiscPrimTer'    , fnc_GetValConstantalucru ('ArtDiscPrimTer')                         ::varchar, false);
  perform set_config ('PKG_NOTECREDIT.KArtDiscPrimVol'    , COALESCE ( (fnc_GetValConstantalucru ('ArtDiscPrimVol'    )) , '0') ::varchar, false);
  perform set_config ('PKG_NOTECREDIT.KArtDiscPrimCant'   , COALESCE ( (fnc_GetValConstantalucru ('ArtDiscPrimCant'   )) , '0') ::varchar, false);
  perform set_config ('PKG_NOTECREDIT.KArtPenPrimTer'     , COALESCE ( (fnc_GetValConstantalucru ('ArtPenPrim'        )) , '0') ::varchar, false);
  perform set_config ('PKG_NOTECREDIT.KArtDiscOffInvoiceF', COALESCE ( (fnc_GetValConstantalucru ('ArtDiscOffInvoiceF')) , '0') ::varchar, false);

  FOR v_rec IN (SELECT nc.tipdoc, COALESCE (nc.codcontract, 0) CODCONTRACT, nc.codpart, nc.datastart,
                       nc.datastop, nc.subunitatea, nc.codmoneda, COALESCE (c.TipTargetV, 0) TIPTARGETV
                FROM notecredit nc INNER JOIN contract c ON nc.codcontract = c.codcontract
                WHERE nc.codncredit = aCodNCredit
               )
  LOOP
    IF v_Rec.TipDoc = 58 THEN
      IF v_rec.TipTargetV = 0 THEN
        INSERT INTO manevra_notecredit (codobiect, valoare, UserID, Codncredit)
        SELECT 0, SUM (ValM) , current_setting ('PKG_GLOBALS.USERID', true) ::numeric, aCodNCredit
        FROM (SELECT SUM (CASE WHEN i.tipdoc = 21 THEN I1.Cant * I1.PU - I1.TVA ELSE i1.cant * i1.pu END) VALM
              FROM IESIRI I INNER JOIN iesiri1 I1 ON i.codies = i1.codies
              WHERE
                I.TipDoc IN (19, 21, 26)
                AND I.Partener = v_rec.codpart
                AND COALESCE (I.Anulat, 0) = 0
                and i.operat = 1
                AND I1.CodObiect &gt; 0
                AND I.DataDoc BETWEEN v_rec.datastart AND v_rec.DataStop
                AND (I1.CodObiect NOT IN (current_setting ('PKG_NOTECREDIT.KArtDiscAcVol', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtDiscAcCant', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtPenAcTer', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceC', true) ::numeric)
                AND STRPOS (current_setting ('PKG_NOTECREDIT.KArtDiscAcTer', true) , (I1.CODOBIECT) ::varchar) = 0)
                AND I.Subunitatea = v_rec.subunitatea
                AND I.Moneda = v_Rec.codmoneda
              union ALL
              SELECT SUM (i1.restfact) VALM
              FROM IESIRI I INNER JOIN iesiri1   I1 ON i.codies = i1.codies
              WHERE
                I.TipDoc IN (19, 21, 26)
                AND I.Partener = v_Rec.codpart
                AND COALESCE (I.Anulat, 0) = 0
                and i.operat = 1
                AND (i1.tiplinie = 'T' or i1.tiplinie = 'G')
                AND I.DataDoc BETWEEN v_rec.DataStart AND v_Rec.DataStop
                AND I.Subunitatea = v_Rec.Subunitatea
                and I.Moneda = v_Rec.CodMoneda) A_PG;
      ELSE
        IF v_rec.TipTargetV = 1 THEN
          INSERT INTO manevra_notecredit (codobiect, valoare, UserID, CodNCredit)
          SELECT 0, SUM (ValM) , current_setting ('PKG_GLOBALS.USERID', true) ::numeric, aCodNCredit
          FROM (SELECT SUM (CASE WHEN COALESCE (c1.tipdiscount, 0) = 0 THEN CASE WHEN i.tipdoc = 21 THEN I1.Cant * I1.PU - I1.TVA ELSE i1.cant * i1.pu END
                                 ELSE I1.Cant * C1.pret
                            END) VALM
              FROM IESIRI            I
                INNER JOIN iesiri1   I1 ON i.codies        = i1.codies
                INNER JOIN contract1 c1 ON c1.codcontract1 = (SELECT pkg_notecredit_getcodcontract1.WME_RESULT
                                                              FROM   pkg_notecredit_getcodcontract1 (NULL,i1.codobiect, i.datadoc, v_rec.codcontract))
                  WHERE
                    I.TipDoc IN (19, 21, 26)
                    AND I.Partener = v_rec.CodPart
                    AND COALESCE (I.Anulat, 0) = 0
                    and i.operat = 1
                    AND I1.CodObiect &gt; 0
                    AND I.DataDoc BETWEEN v_rec.DataStart AND v_rec.DataStop
                    AND (I1.CodObiect NOT IN (current_setting ('PKG_NOTECREDIT.KArtDiscAcVol', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtDiscAcCant', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtPenAcTer', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceC', true) ::numeric)
                    AND STRPOS (current_setting ('PKG_NOTECREDIT.KArtDiscAcTer', true) , (I1.CODOBIECT) ::varchar) = 0)
                    AND I.Subunitatea = v_rec.Subunitatea
                    AND I.Moneda = v_Rec.CodMoneda
                    AND c1.codcontract = v_Rec.CodContract
              union ALL
              SELECT SUM (i1.restfact) VALM
              FROM IESIRI            I
                INNER JOIN iesiri1   I1 ON i.codies        = i1.codies
                INNER JOIN contract1 c1 ON c1.codcontract1 = (SELECT pkg_notecredit_getcodcontract1.WME_RESULT
                                                              FROM   pkg_notecredit_getcodcontract1 (NULL,i1.codobiect, i.datadoc, v_rec.codcontract))
                  WHERE
                    I.TipDoc IN (19, 21, 26)
                    AND I.Partener = v_Rec.CodPart
                    AND COALESCE (I.Anulat, 0) = 0
                    and i.operat = 1
                    AND (i1.tiplinie = 'T' or i1.tiplinie = 'G')
                    AND I.DataDoc BETWEEN v_rec.DataStart AND v_rec.DataStop
                    AND I.Subunitatea = v_Rec.subunitatea
                    AND I.Moneda = v_rec.codmoneda
                    AND c1.codcontract = v_Rec.codcontract) B_PG;
        ELSE
          INSERT INTO manevra_notecredit (codobiect, codcontract1, valoare, UserID, Codncredit, valoare_b)
          SELECT codobiect, codcontract1, sum (valm) , current_setting ('PKG_GLOBALS.USERID', true) ::numeric, aCodNCredit, sum (valm_b)
          FROM (SELECT i1.codobiect, c1.codcontract1,
                       SUM (CASE WHEN COALESCE (c1.tipdiscount, 0) = 0 THEN CASE WHEN i.tipdoc = 21 THEN (I1.Cant * i1.pretorig - I1.TVA) * COALESCE (I1.CoefDiscMaj, 1)
                                                                                 ELSE i1.cant * i1.pretorig * COALESCE (I1.CoefDiscMaj, 1)
                                                                            END
                                 ELSE I1.Cant * C1.pret
                            END) VALM,
                       SUM (CASE WHEN COALESCE (c1.tipdiscount, 0) = 0 THEN CASE WHEN i.tipdoc = 21 THEN I1.Cant * i1.pretorig - I1.TVA
                                                                                 ELSE i1.cant * i1.pretorig
                                                                            END
                                 ELSE I1.Cant * C1.pret
                            END) VALM_B
                FROM IESIRI            I
                  INNER JOIN iesiri1   I1 ON i.codies        = i1.codies
                  INNER JOIN contract1 c1 ON c1.codcontract1 = (SELECT pkg_notecredit_getcodcontract1.WME_RESULT
                                                                FROM   pkg_notecredit_getcodcontract1 (NULL,i1.codobiect, i.datadoc, v_Rec.CodContract))
                WHERE
                  I.DataDoc BETWEEN v_Rec.DataStart AND v_rec.DataStop
                  AND (I1.CodObiect NOT IN (current_setting ('PKG_NOTECREDIT.KArtDiscAcVol', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtDiscAcCant', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtPenAcTer', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtDiscOffInvoiceC', true) ::numeric)
                  AND STRPOS(current_setting ('PKG_NOTECREDIT.KArtDiscAcTer', true) , (I1.CODOBIECT)::varchar) = 0)
                  AND I1.CodObiect &gt; 0
                  and c1.codcontract = v_Rec.CodContract
                  and i.subunitatea = v_Rec.Subunitatea
                  and ( (i.partener = v_Rec.CodPart) or (i.partcustodie = v_rec.codpart))
                GROUP BY i1.codobiect, c1.codcontract1
                union ALL
                SELECT i1.CodObiect, c1.codcontract1, SUM (i1.restfact) VALM, SUM (i1.restfact) VALM_B
                FROM IESIRI            I
                  INNER JOIN iesiri1   I1 ON i.codies        = i1.codies
                  INNER JOIN contract1 c1 ON c1.codcontract1 = (SELECT pkg_notecredit_getcodcontract1.WME_RESULT
                                                                FROM   pkg_notecredit_getcodcontract1 (NULL,i1.codobiect, i.datadoc, v_rec.CodContract))
                WHERE
                  I.TipDoc IN (19, 21, 26)
                  AND COALESCE (I.Anulat, 0) = 0
                  and i.operat = 1
                  AND (i1.tiplinie = 'T' or i1.tiplinie = 'G')
                  AND I.DataDoc BETWEEN v_Rec.DataStart AND v_rec.DataStop
                  AND I.Subunitatea = v_rec.Subunitatea
                  and I.Moneda = v_Rec.CodMoneda
                  and c1.codcontract = v_Rec.CodContract
                  and ( (i.partener = v_Rec.CodPart) or (i.partcustodie = v_rec.codpart))
                GROUP BY i1.codobiect, c1.codcontract1
                   ) C_PG
          GROUP BY codobiect, codcontract1;
        END IF;
      END IF;
    ELSE
      IF v_rec.TipTargetV = 0 THEN
        INSERT INTO manevra_notecredit (codobiect, valoare, UserID, Codncredit)
        SELECT 0, SUM (ValM) , current_setting ('PKG_GLOBALS.USERID', true) ::numeric, aCodNCredit
        FROM (SELECT SUM (I1.Cant * I1.PretOrig * COALESCE (I1.CoefDiscMaj, 1)) VALM
              FROM Intrari          I
                INNER JOIN intrari1 I1 ON i.codintr = i1.codintr
              WHERE
                I.DataDoc BETWEEN v_rec.DataStart AND v_rec.DataStop
                AND I1.CodObiect NOT IN (current_setting ('PKG_NOTECREDIT.KArtDiscPrimVol', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtDiscPrimCant', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtPenPrimTer', true) ::numeric)
                    AND INSTR(current_setting ('PKG_NOTECREDIT.KArtDiscPrimTer', true), (I1.CODOBIECT)::varchar) = 0
                AND I1.CodObiect &gt; 0
                and i.subunitatea = v_rec.Subunitatea
                and i.partener = v_rec.CodPart
              union ALL
              SELECT SUM (I1.restfact) VALM
              FROM INTRARI I INNER JOIN intrari1  I1 ON i.codintr = i1.codintr
              WHERE I.TipDoc IN (1, 3, 4, 5, 9)
                AND I.Partener = v_rec.CodPart
                AND I.DataDoc BETWEEN v_rec.DataStart AND v_rec.DataStop
                and i.operat = 1
                and COALESCE (I.Anulat, 0) = 0
                and I.Moneda = v_rec.CodMoneda
                AND (i1.tiplinie = 'T' or i1.tiplinie = 'G')
                AND I.Subunitatea = v_rec.Subunitatea
              ) D_PG;
      ELSE
        IF v_rec.TipTargetV = 1 THEN
          INSERT INTO manevra_notecredit (codobiect, valoare, UserID, Codncredit)
          SELECT 0, SUM (ValM) , current_setting ('PKG_GLOBALS.USERID', true) ::numeric, aCodNCredit
          FROM (SELECT SUM (CASE WHEN COALESCE (c1.tipdiscount, 0) = 0 THEN I1.Cant * I1.PretOrig * COALESCE (I1.CoefDiscMaj, 1)
                                 ELSE I1.Cant * C1.pret
                            END) VALM
              FROM Intrari           I
                INNER JOIN intrari1  I1 ON i.codintr       = i1.codintr
                INNER JOIN contract1 c1 ON c1.codcontract1 = (SELECT pkg_notecredit_getcodcontract1.WME_RESULT
                                                              FROM   pkg_notecredit_getcodcontract1 (NULL,i1.codobiect, i.datadoc, v_rec.CodContract))
              WHERE
                I.DataDoc BETWEEN v_rec.DataStart AND v_rec.DataStop
                AND I1.CodObiect NOT IN (current_setting ('PKG_NOTECREDIT.KArtDiscPrimVol', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtDiscPrimCant', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtPenPrimTer', true) ::numeric)
                  AND INSTR(current_setting ('PKG_NOTECREDIT.KArtDiscPrimTer', true), (I1.CODOBIECT)::varchar) = 0
                AND I1.CodObiect &gt; 0
                and i.subunitatea = v_rec.Subunitatea
                and i.partener = v_rec.CodPart
                and c1.codcontract = v_rec.CodContract
              union ALL
              SELECT SUM (I1.restfact) VALM
              FROM INTRARI           I
                INNER JOIN intrari1  I1 ON i.codintr       = i1.codintr
                INNER JOIN contract1 c1 ON c1.codcontract1 = (SELECT pkg_notecredit_getcodcontract1.WME_RESULT
                                                              FROM   pkg_notecredit_getcodcontract1 (NULL,i1.codobiect, i.datadoc, v_rec.CodContract))
              WHERE
                I.TipDoc IN (1, 3, 4, 5, 9)
                AND I.Partener = v_rec.CodPart
                AND I.DataDoc BETWEEN v_rec.DataStart AND v_rec.DataStop
                and i.operat = 1
                and COALESCE (I.Anulat, 0) = 0
                and I.Moneda = v_rec.CodMoneda
                AND (i1.tiplinie = 'T' or i1.tiplinie = 'G')
                AND I.Subunitatea = v_rec.Subunitatea
                and c1.codcontract = v_rec.CodContract) E_PG;
        ELSE
          INSERT INTO manevra_notecredit (codobiect, codcontract1, valoare, UserID, CodNCredit, valoare_b)
          SELECT codobiect, codcontract1, SUM (ValM) , current_setting ('PKG_GLOBALS.USERID', true) ::numeric, aCodNCredit, sum (valm_b)
          FROM (SELECT i1.codobiect, c1.codcontract1,
                       SUM (CASE WHEN COALESCE (c1.tipdiscount, 0) = 0 THEN I1.Cant * I1.PretOrig * COALESCE (I1.CoefDiscMaj, 1)
                                 ELSE I1.Cant * C1.pret
                            END) VALM,
                       SUM (CASE WHEN COALESCE (c1.tipdiscount, 0) = 0 THEN I1.Cant * I1.PretOrig ELSE I1.Cant * C1.pret END) VALM_B
              FROM Intrari             I
                INNER JOIN intrari1  I1 ON i.codintr       = i1.codintr
                INNER JOIN contract1 c1 ON c1.codcontract1 = (SELECT pkg_notecredit_getcodcontract1.WME_RESULT
                                                              FROM   pkg_notecredit_getcodcontract1 (NULL,i1.codobiect, i.datadoc, v_rec.CodContract))
              WHERE
                I.DataDoc BETWEEN v_Rec.DataStart AND v_rec.DataStop
                AND I1.CodObiect NOT IN (current_setting ('PKG_NOTECREDIT.KArtDiscPrimVol', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtDiscPrimCant', true) ::numeric, current_setting ('PKG_NOTECREDIT.KArtPenPrimTer', true) ::NUMERIC)
                  AND INSTR(current_setting('PKG_NOTECREDIT.KArtDiscPrimTer', true), (I1.CODOBIECT)::varchar) = 0
                AND I1.CodObiect &gt; 0
                and i.subunitatea = v_rec.Subunitatea
                and i.partener = v_Rec.CodPart
                and c1.codcontract = v_rec.CodContract
              GROUP BY i1.codobiect, c1.codcontract1
              union ALL
              SELECT i1.CodObiect, c1.codcontract1, SUM (I1.restfact) VALM, SUM (I1.restfact) VALM_B
              FROM INTRARI           I
                INNER JOIN intrari1  I1 ON i.codintr       = i1.codintr
                INNER JOIN contract1 c1 ON c1.codcontract1 = (SELECT pkg_notecredit_getcodcontract1.WME_RESULT
                                                              FROM   pkg_notecredit_getcodcontract1 (NULL,i1.codobiect, i.datadoc, v_rec.CodContract))
              WHERE
                I.TipDoc IN (1, 3, 4, 5, 9)
                and i.partener = v_Rec.CodPart
                AND I.DataDoc BETWEEN v_rec.DataStart AND v_rec.DataStop
                and i.operat = 1
                and COALESCE (I.Anulat, 0) = 0
                and I.Moneda       = v_rec.CodMoneda
                AND (i1.tiplinie   = 'T' or i1.tiplinie = 'G')
                AND I.Subunitatea  = v_Rec.Subunitatea
                and c1.codcontract = v_rec.CodContract
              GROUP BY i1.CodObiect, c1.codcontract1) F_PG
          GROUP BY
            CodObiect, codcontract1;
        END IF;
      END IF;
    END IF;
  END LOOP;

  IF CuCommit THEN
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_onorarecomenzi_preluareautomatadinstoc</obj_name>
  <obj_hashval>83a68cb34ecf6687dedbb00cf123d3fb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_onorarecomenzi_preluareautomatadinstoc(pdatalivr character varying, pcodioart numeric, pcodgest numeric, pordinegr numeric, pimp numeric DEFAULT 0, prezonly numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  RC          RECORD;
  PREC        RECORD;
  PREC1        RECORD;
  VREC        RECORD;
  BREC        RECORD;
  dDataLivr   date;
  vMG         numeric;
  vCodGest    numeric;
  vCodIoart   numeric;
  vCodObiect  numeric;
  vRestObj    numeric;
  vRestCom1   numeric;
  vRowId tid;
  vCodnirstoc numeric;
  vCodnirser  numeric;
  vPreluat    numeric;
  nrRows      NUMERIC;
  v_rec       record;
BEGIN
  --Florin 20.02.2024 - sinc. Oracle
  --Florin 05.07.2023 - fixat 58730
  --Florin 26.09.2022
  --Florin 26.09.2022 - sinc. Oracle (23.09.2022)
  --Florin 26.08.2022 - sinc. Oracle (25.08.2022)
  --Florin 13.01.2022 - sinc. Oracle (29.12.2021)
  --Bogdan 11.02.2021
  --Bogdan 05.02.2021
  --Bogdan 25.01.2021
  BEGIN
    dDataLivr := To_Date (COALESCE (pDataLivr, 'X') , 'DD.MM.YYYY');
  EXCEPTION
  WHEN OTHERS THEN
    dDataLivr := DATE_TRUNC ('DAY',CURRENT_TIMESTAMP);
  END;
  -- pasul 1 preluare din rezervare comenzi
  FOR RC IN (SELECT R.CodComanda1, R.Rest, R.CodNirstoc, COALESCE (R.CodNirser, 0) CODNIRSER
             FROM TMP_OnorCom_Articole A INNER JOIN RezervatS R ON R.CodComanda1 = A.CodComanda1
            )
  LOOP
    UPDATE TMP_OnorCom_PrelStoc
    SET PRELUAT = RC.REST,
        Rezervat = RC.Rest
    WHERE
      RC.CodComanda1 = CodComanda1
      AND RC.CodNirstoc = CodNirstoc
      AND RC.CodNirser = CodNirser
      and PRELUAT &lt; RC.REST;


  select count(*) INTO nrRows from TMP_OnorCom_PrelStoc
    where
      RC.CodComanda1 = CodComanda1
      and RC.CodNirstoc = CodNirstoc
      and RC.CodNirser = CodNirser;
  IF nrRows = 0 THEN
    INSERT INTO TMP_ONORCOM_PRELSTOC (CodComanda1, CodNirstoc, CodNirser, Preluat, Rezervat)
    VALUES (RC.CodComanda1, RC.CodNirstoc, RC.CodNirser, RC.Rest, RC.Rest);
  END IF;
END LOOP;

 FOR PREC IN (SELECT CodComanda1, Sum (Preluat) LIVRSTOC FROM TMP_OnorCom_PrelStoc GROUP BY CodComanda1) LOOP
    UPDATE TMP_OnorCom_Articole A
    SET LIVRSTOC = PREC.LIVRSTOC
    WHERE
      PREC.CodComanda1 = A.CodComanda1
      and A.LIVRSTOC &lt;&gt; PREC.LivrStoc;
  END LOOP;
  if pRezOnly = 0 THEN
  IF pImp &gt; 0 THEN
    vCodObiect := 0;
    IF pOrdineGR = 1 THEN
      FOR vREC IN (SELECT TMPA.CodComanda1, TMPA.CodObiect, TMPA.RestLivr - TMPA.LivrStoc RESTCOM1,
                          Sum (TMPA.RestLivr - TMPA.LivrStoc) OVER (PARTITION BY TMPA.CodObiect) RESTOBJ,
                          tmpa.codgest, tmpa.codioart
                   FROM TMP_OnorCom_Articole TMPA INNER JOIN TMP_ONORCOM_COMENZI TMPC ON TMPA.CODCOMANDA = TMPC.CODCOMANDA
                   WHERE TMPA.RestLivr &gt; 0 AND TipLinie = '='
                   ORDER BY TMPC.GRLIVR
                  )
      LOOP
        vCodIOArt := COALESCE (vrec.CodIOArt, 0);
        vCodGest  := COALESCE (vrec.CodGest , 0);

        IF vCodIOArt &lt;&gt; 0 AND vCodGest &lt;&gt; 0 THEN
          SELECT MG INTO vMG
          FROM IOART1
          WHERE CODIOART = vCodIOArt AND GetAnLunaLucru() BETWEEN ALStart AND ALStop;

          vRestCom1 := vRec.RestCom1;
          IF vCodObiect &lt;&gt; vRec.CodObiect THEN
            vCodObiect := vRec.CodObiect;
            vRestObj   := vRec.RestObj;
            select pcant
            from PKG_ONORARECOMENZI_Rezervare_Stoc (vCodObiect, vCodIOArt, vCodGest, vMG, dDataLivr, vRestObj)
            INTO vRestObj;
          END IF;

          IF vRestCom1 &gt; vRestObj THEN
            vRestCom1 := vRestObj;
          END IF;

          WHILE vRestCom1 &gt; 0 LOOP
            SELECT CTID, codnirstoc, codnirser, preluat
            INTO vRowId, vcodnirstoc, vcodnirser, vpreluat
            FROM TMP_OnorCom_StocBuf limit 1;

            IF vpreluat &gt; vRestCom1 THEN
              vpreluat := vRestCom1;
              UPDATE TMP_OnorCom_StocBuf SET preluat = preluat - vpreluat WHERE CTID = vRowId;
            ELSE
              DELETE FROM TMP_OnorCom_StocBuf WHERE CTID = vRowId;
            END IF;

            vRestCom1 := vRestCom1 - vpreluat;
            vRestObj  := vRestObj  - vpreluat;

            FOR BREC IN (SELECT vREC.CodComanda1 CODCOMANDA1, vcodnirstoc CODNIRSTOC, vcodnirser CODNIRSER, vpreluat PRELUAT, (select sum(rest) from rezervats where codcomanda1 = vrec.codcomanda1 and codnirstoc = vcodnirstoc and codnirser = vcodnirser) rezervat) LOOP
              UPDATE TMP_OnorCom_PrelStoc
              SET PRELUAT = PRELUAT + BREC.PRELUAT,
                  REZERVAT = REZERVAT + CASE WHEN BREC.REZERVAT &gt; BREC.PRELUAT THEN BREC.PRELUAT ELSE BREC.REZERVAT END
              WHERE
                BREC.CodComanda1 = CodComanda1
                AND BREC.CodNirstoc = CodNirstoc
                AND BREC.CodNirser = CodNirser;

              IF NOT FOUND THEN
                INSERT INTO TMP_ONORCOM_PRELSTOC (CodComanda1, CodNirstoc, CodNirser, Preluat, Rezervat)
                VALUES (BREC.CodComanda1, BREC.CodNirstoc, BREC.CodNirser, BREC.Preluat, CASE WHEN BREC.REZERVAT &gt; BREC.PRELUAT THEN BREC.PRELUAT ELSE BREC.REZERVAT END);
              END IF;
            END LOOP;
          END LOOP;
        END IF;
      END LOOP;
    ELSE
      FOR vREC IN (SELECT CodComanda1, CodObiect, RestLivr - LivrStoc RESTCOM1,
                          Sum (RestLivr - LivrStoc) OVER (PARTITION BY CodObiect) RESTOBJ, codgest, codioart
                   FROM TMP_OnorCom_Articole
                   WHERE RestLivr &gt; 0 AND TipLinie = '='
                   ORDER BY CodObiect
                  )
      LOOP
        vCodIOArt := COALESCE (vrec.CodIOArt, 0);
        vCodGest  := COALESCE (vrec.CodGest , 0);

        IF vCodIOArt &lt;&gt; 0 AND vCodGest &lt;&gt; 0 THEN
          SELECT MG INTO vMG
          FROM IOART1
          WHERE CODIOART = vCodIOArt AND GetAnLunaLucru() BETWEEN ALStart AND ALStop;

          vRestCom1 := vRec.RestCom1;
          IF vCodObiect &lt;&gt; vRec.CodObiect THEN
            vCodObiect := vRec.CodObiect;
            vRestObj   := vRec.RestObj;
            select pcant
            from  pkg_onorarecomenzi_Rezervare_Stoc (vCodObiect, vCodIOArt, vCodGest, vMG, dDataLivr, vRestObj)
            INTO vRestObj ;
          END IF;

          IF vRestCom1 &gt; vRestObj THEN
            vRestCom1 := vRestObj;
          END IF;

          WHILE vRestCom1 &gt; 0 LOOP
            SELECT CTID, codnirstoc, codnirser, preluat
            INTO vRowId, vcodnirstoc, vcodnirser, vpreluat
            FROM TMP_OnorCom_StocBuf limit 1;

            IF vpreluat &gt; vRestCom1 THEN
              vpreluat := vRestCom1;
              UPDATE TMP_OnorCom_StocBuf SET preluat = preluat - vpreluat WHERE CTID = vRowId;
            ELSE
              DELETE FROM TMP_OnorCom_StocBuf WHERE CTID = vRowId;
            END IF;

            vRestCom1 := vRestCom1 - vpreluat;
            vRestObj  := vRestObj  - vpreluat;

            FOR BREC IN (SELECT vREC.CodComanda1 CODCOMANDA1, vcodnirstoc CODNIRSTOC, vcodnirser CODNIRSER, vpreluat PRELUAT, (select sum(rest) from rezervats where codcomanda1 = vrec.codcomanda1 and codnirstoc = vcodnirstoc and codnirser = vcodnirser) rezervat) LOOP
              UPDATE TMP_OnorCom_PrelStoc
              SET PRELUAT = PRELUAT + BREC.PRELUAT,
                  REZERVAT = REZERVAT + CASE WHEN BREC.REZERVAT &gt; BREC.PRELUAT THEN BREC.PRELUAT ELSE BREC.REZERVAT END
              WHERE
                BREC.CodComanda1 = CodComanda1
                AND BREC.CodNirstoc = CodNirstoc
                AND BREC.CodNirser = CodNirser;

              IF NOT FOUND THEN
                INSERT INTO TMP_ONORCOM_PRELSTOC (CodComanda1, CodNirstoc, CodNirser, Preluat, Rezervat)
                  VALUES (BREC.CodComanda1, BREC.CodNirstoc, BREC.CodNirser, BREC.Preluat, CASE WHEN BREC.REZERVAT &gt; BREC.PRELUAT THEN BREC.PRELUAT ELSE BREC.REZERVAT END);
              END IF;
            END LOOP;
          END LOOP;
        END IF;
      END LOOP;
    END IF;

    FOR Prec IN (SELECT CodComanda1, Sum (Preluat) LIVRSTOC FROM TMP_OnorCom_PrelStoc GROUP BY CodComanda1) LOOP
      UPDATE TMP_OnorCom_Articole A
      SET LIVRSTOC = prec.LIVRSTOC
      WHERE
        prec.CodComanda1 = A.CodComanda1 AND A.LivrStoc &lt;&gt; Prec.LivrStoc;
    END LOOP;
  ELSE
    vCodIOArt := COALESCE (pCodIOArt, 0);
    vCodGest  := COALESCE (pCodGest , 0);

    IF vCodIOArt &lt;&gt; 0 AND vCodGest &lt;&gt; 0 THEN
      SELECT MG INTO vMG
      FROM IOART1
      WHERE CODIOART = vCodIOArt AND GetAnLunaLucru() BETWEEN ALStart AND ALStop;

      vCodObiect := 0;
      IF pOrdineGR = 1 THEN
        FOR vREC IN (SELECT TMPA.CodComanda1, TMPA.CodObiect, TMPA.RestLivr - TMPA.LivrStoc RESTCOM1,
                            Sum (TMPA.RestLivr - TMPA.LivrStoc) OVER (PARTITION BY TMPA.CodObiect) RESTOBJ
                     FROM TMP_OnorCom_Articole TMPA INNER JOIN TMP_ONORCOM_COMENZI TMPC ON TMPA.CODCOMANDA = TMPC.CODCOMANDA
                     WHERE TMPA.RestLivr &gt; 0 AND TipLinie = '='
                     ORDER BY TMPC.GRLIVR
                    )
        LOOP
          vRestCom1 := vRec.RestCom1;
          IF vCodObiect &lt;&gt; vRec.CodObiect THEN
            vCodObiect := vRec.CodObiect;
            vRestObj   := vRec.RestObj;
            SELECT pcant
            FROM pkg_onorarecomenzi_Rezervare_Stoc (vCodObiect, vCodIOArt, vCodGest, vMG, dDataLivr, vRestObj) INTO vRestObj;
          END IF;

          IF vRestCom1 &gt; vRestObj THEN
            vRestCom1 := vRestObj;
          END IF;

          WHILE vRestCom1 &gt; 0 LOOP
            SELECT CTID, codnirstoc, codnirser, preluat
            INTO vRowId, vcodnirstoc, vcodnirser, vpreluat
            FROM TMP_OnorCom_StocBuf limit 1;

            IF vpreluat &gt; vRestCom1 THEN
              vpreluat := vRestCom1;
              UPDATE TMP_OnorCom_StocBuf SET preluat = preluat - vpreluat WHERE CTID = vRowId;
            ELSE
              DELETE FROM TMP_OnorCom_StocBuf WHERE CTID = vRowId;
            END IF;

            vRestCom1 := vRestCom1 - vpreluat;
            vRestObj  := vRestObj  - vpreluat;

            FOR BREC IN (SELECT vREC.CodComanda1 CODCOMANDA1, vcodnirstoc CODNIRSTOC, vcodnirser CODNIRSER, vpreluat PRELUAT) LOOP
              UPDATE TMP_OnorCom_PrelStoc
              SET PRELUAT = PRELUAT + BREC.PRELUAT
              WHERE
                BREC.CodComanda1 = CodComanda1
                AND BREC.CodNirstoc = CodNirstoc
                AND BREC.CodNirser = CodNirser;

              IF NOT FOUND THEN
                INSERT INTO TMP_ONORCOM_PRELSTOC AS P (CodComanda1, CodNirstoc, CodNirser, Preluat)
                  VALUES (BREC.CodComanda1, BREC.CodNirstoc, BREC.CodNirser, BREC.Preluat);
              END IF;
            END LOOP;
          END LOOP;
        END LOOP;
      ELSE
        FOR vREC IN (SELECT CodComanda1, CodObiect, RestLivr - LivrStoc RESTCOM1, Sum (RestLivr - LivrStoc) OVER (PARTITION BY TMPA.CodObiect) RESTOBJ
                     FROM TMP_OnorCom_Articole TMPA WHERE RestLivr &gt; 0 ORDER BY CodObiect
                    )
        LOOP
          vRestCom1 := vRec.RestCom1;
          IF vCodObiect &lt;&gt; vRec.CodObiect THEN
            vCodObiect := vRec.CodObiect;
            vRestObj   := vRec.RestObj;
            SELECT pcant
            FROM pkg_onorarecomenzi_Rezervare_Stoc (vCodObiect, vCodIOArt, vCodGest, vMG, dDataLivr, vRestObj) INTO vRestObj;
          END IF;

          IF vRestCom1 &gt; vRestObj THEN
            vRestCom1 := vRestObj;
          END IF;

          WHILE vRestCom1 &gt; 0 LOOP
            SELECT CTID, codnirstoc, codnirser, preluat
            INTO vRowId, vcodnirstoc, vcodnirser, vpreluat
            FROM TMP_OnorCom_StocBuf limit 1;

            IF vpreluat &gt; vRestCom1 THEN
              vpreluat := vRestCom1;
              UPDATE TMP_OnorCom_StocBuf SET preluat = preluat - vpreluat WHERE CTID = vRowId;
            ELSE
              DELETE FROM TMP_OnorCom_StocBuf WHERE CTID = vRowId;
            END IF;

            vRestCom1 := vRestCom1 - vpreluat;
            vRestObj  := vRestObj  - vpreluat;

            FOR BREC IN (SELECT vREC.CodComanda1 CODCOMANDA1, vcodnirstoc CODNIRSTOC, vcodnirser CODNIRSER, vpreluat PRELUAT) LOOP
              UPDATE TMP_OnorCom_PrelStoc P
              SET PRELUAT = P.PRELUAT + BREC.PRELUAT
              WHERE
                BREC.CodComanda1 = P.CodComanda1
                AND BREC.CodNirstoc = P.CodNirstoc
                AND BREC.CodNirser = P.CodNirser;

              IF NOT FOUND THEN
                INSERT INTO TMP_ONORCOM_PRELSTOC AS P (CodComanda1, CodNirstoc, CodNirser, Preluat)
                VALUES (BREC.CodComanda1, BREC.CodNirstoc, BREC.CodNirser, BREC.Preluat);
              END IF;
            END LOOP;
          END LOOP;
        END LOOP;
      END IF;

      FOR PREC IN (SELECT CodComanda1, Sum (Preluat) LIVRSTOC FROM TMP_OnorCom_PrelStoc GROUP BY CodComanda1) LOOP
        UPDATE TMP_OnorCom_Articole A
        SET LIVRSTOC = PREC.LIVRSTOC
        WHERE
          PREC.CodComanda1 = A.CodComanda1 AND A.LivrStoc &lt;&gt; PREC.LivrStoc;
      END LOOP;
    END IF;
  END IF;
  END IF;

  UPDATE TMP_OnorCom_Articole
  SET flaginchidere = 1
  WHERE
    Abs (Round ( (RestLivr - LivrStoc - LivrEchiv) ::numeric, 2)) &lt; RESTNEGLIJCMD
    AND TipLinie = '=';

  UPDATE TMP_OnorCom_Articole  SET flaginchidere = 1, LivrStoc = RestLivr WHERE TipLinie = 'S';

  UPDATE TMP_OnorCom_Comenzi C SET COUNTNEINCHISE = (SELECT Count (1) FROM TMP_OnorCom_Articole A WHERE A.CodComanda = C.CodComanda AND A.FLAGINCHIDERE = 0);

  FOR V_REC IN (SELECT TMP.CODCOMANDA1, TMP.CODNIRSTOC
                  FROM TMP_ONORCOM_PRELSTOC TMP
                INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = TMP.CODNIRSTOC
                INNER JOIN COMANDA1 C1 ON TMP.CODCOMANDA1 = C1.CODCOMANDA1
                WHERE C1.CODOBIECT &lt;&gt; NS.CODOBIECT
                ) LOOP
                  DELETE FROM TMP_ONORCOM_PRELSTOC WHERE CODCOMANDA1 = V_REC.CODCOMANDA1 AND CODNIRSTOC = V_REC.CODNIRSTOC;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oportunitati_sp_postrecords</obj_name>
  <obj_hashval>f04f5bf5ae4527bb1c8a0138a131617b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oportunitati_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC      RECORD;
  aDoc       varchar;
  ACARNETDOC numeric;
  ANRDOC     numeric;
BEGIN
  --Florin 19.11.2024 - sinc. Oracle
  --Florin 01.06.2023 - monitor
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
    --Adina 05.02.2021 - modif.Oracle din 04.02.2021 - add codfiscal
    --Adina 03.02.2021 - modif.Oracle din 03.02.2021
    --Florin 11.11.2020 - fixat #40779
  perform pkg_oportunitati_setct_monitor('MON_55');
  SELECT COALESCE( CODCARNETDOC, 0), NRDOC INTO ACARNETDOC, ANRDOC FROM tmp_Oportunitati;
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT (82);

  IF  Operation = 0 THEN
    SELECT CodOportunitate INTO RecId FROM Tmp_Oportunitati;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_OPORTUNITATI.CT_MONITOR', true))))
    THEN
      SELECT 'Oportunitate "' || prefixdoc || nrdoc || '/' || datadoc || '"' INTO aDoc
      FROM Oportunitati
      WHERE codoportunitate = recid;

      PERFORM pkg_userfirme_postlogcucommit( 'Oportunitati', (current_setting('PKG_GLOBALS.USERNAME', true)), 'M', RECID, (current_setting('PKG_GLOBALS.FIRMANAME', true)), TO_NUMBER((current_setting('PKG_GLOBALS.SUBUNITATE', true)),'999999999999999999'), null, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    UPDATE Oportunitati
    SET
    (CodOportunitate, PrefixDoc, NrDoc, DataDoc, CodCarnetDoc, CodPartener, CodMoneda, Tip, CodAgent, CodCampanie,
     VenitEst, VenitProb, CodSubunitate, CodOferta, CodComanda, CodContract, An, Luna, ProbVanz, DataSemnare, SeriaDoc, CodLead, CodTask,
     UserID, CodProiectCRM, Codclaseopt, CodLocatie, Obs, Curs, CodFiscal
    )
    =
    (SELECT CodOportunitate, PrefixDoc, NrDoc, DataDoc, CodCarnetDoc, CodPartener, CodMoneda, Tip, CodAgent, CodCampanie,
            VenitEst, VenitProb, CodSubunitate, CodOferta, CodComanda, CodContract,
            EXTRACT( YEAR FROM DataDoc), EXTRACT( MONTH FROM DataDoc), ProbVanz, DataSemnare, SeriaDoc, CodLead, CodTask,
            UserID, CodProiectCRM, Codclaseopt, CodLocatie, Obs, Curs, CodFiscal
     FROM Tmp_Oportunitati
    )
    WHERE CodOportunitate = RecId;

    DELETE FROM Oportunitati1
    WHERE CodOportunitate = RecId AND CodOportunitate1 NOT IN (SELECT CodOportunitate1 FROM Tmp_Oportunitati1);

    FOR V_Rec IN (SELECT * FROM Tmp_Oportunitati1 ORDER BY IndexLocal) LOOP
      IF  COALESCE( V_Rec.CodOportunitate1, 0) &gt; 0 THEN
        UPDATE Oportunitati1
        SET
          IndexLocal = V_Rec.IndexLocal,
          Stadiu     = V_Rec.Stadiu,
          CodAgent   = V_Rec.CodAgent,
          Info       = V_Rec.Info,
          DataC      = V_Rec.DataC,
          CodMotiv   = v_rec.CodMotiv,
          FollowUp   = v_rec.FollowUp,
          CodTask    = v_rec.Codtask
        WHERE
         CodOportunitate1 = V_Rec.CodOportunitate1;
      ELSE
        INSERT INTO Oportunitati1(CodOportunitate1, CodOportunitate, IndexLocal, Stadiu, CodAgent, Info, DataC, CodMotiv, FollowUp, Codtask, CodPers)
        VALUES(NEXTVAL('SEQ_OPORTUNITATI1_CO1'), RecId, V_Rec.IndexLocal, V_Rec.Stadiu, V_Rec.CodAgent, V_Rec.Info, V_Rec.DataC, v_rec.CodMotiv,
               v_rec.FollowUp, v_rec.Codtask, v_rec.Codpers);
      END IF;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_OPORTUNITATI_CO') INTO RecId;
    PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('OPORTUNITATI', RecId);

    INSERT INTO Oportunitati(CodOportunitate, PrefixDoc, NrDoc, DataDoc, CodCarnetDoc, CodPartener, CodMoneda, Tip, CodAgent, CodCampanie,
                             VenitEst, VenitProb, CodSubunitate, CodOferta, CodComanda, CodContract, An, Luna, ProbVanz, DataSemnare, SeriaDoc,
                             CodLead, CodTask, UserID, Datacreare, CodProiectCRM, Codclaseopt, CodLocatie, Obs, Curs, CodFiscal
                            )
    SELECT RecId, PrefixDoc, NrDoc, DataDoc, CodCarnetDoc, CodPartener, CodMoneda, Tip, CodAgent, CodCampanie, VenitEst, VenitProb, CodSubunitate,
           CodOferta, CodComanda, CodContract, EXTRACT( YEAR FROM DataDoc), EXTRACT( MONTH FROM DataDoc), ProbVanz, DataSemnare, SeriaDoc,
           CodLead, CodTask, GETUSERID(), current_date, CodProiectCRM, Codclaseopt, CodLocatie, Obs, Curs, CodFiscal
    FROM Tmp_Oportunitati;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_OPORTUNITATI.CT_MONITOR', true))))
    THEN
      SELECT 'Oportunitate "' || prefixdoc || nrdoc || '/' || datadoc || '"' INTO aDoc
      FROM Oportunitati
      WHERE codoportunitate = recid;

      PERFORM pkg_userfirme_postlogcucommit( 'Oportunitati', (current_setting('PKG_GLOBALS.USERNAME', true)), 'A', RECID, (current_setting('PKG_GLOBALS.FIRMANAME', true)), TO_NUMBER((current_setting('PKG_GLOBALS.SUBUNITATE', true)),'999999999999999999'), null, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    INSERT INTO Oportunitati1(CodOportunitate1, CodOportunitate, IndexLocal, Stadiu, CodAgent, Info, DataC, CodMotiv, FollowUp, Codtask, CodPers)
    SELECT NEXTVAL('SEQ_OPORTUNITATI1_CO1'), RecId, IndexLocal, Stadiu, CodAgent, Info, DataC, CodMotiv, FollowUp, Codtask, CodPers
    FROM (SELECT IndexLocal, Stadiu, CodAgent, Info, DataC, CodMotiv, FollowUp, Codtask, CodPers
          FROM Tmp_Oportunitati1
          ORDER BY IndexLocal
         ) A_PG;
  END IF;

  IF (TO_NUMBER((current_setting('PKG_OPORTUNITATI.CARNETDOC_I', true)),'999999999999999999') &lt;&gt; 0)  AND (TO_NUMBER((current_setting('PKG_OPORTUNITATI.NRDOC_I', true)),'999999999999999999') &lt;&gt; 0)  AND (ACARNETDOC &lt;&gt; TO_NUMBER((current_setting('PKG_OPORTUNITATI.CARNETDOC_I', true)),'999999999999999999') OR  ANRDOC &lt;&gt; TO_NUMBER((current_setting('PKG_OPORTUNITATI.NRDOC_I', true)),'999999999999999999'))
  THEN
    PERFORM PKG_CARNETEDOC_RELEASENUMARDOC( TO_NUMBER((current_setting('PKG_OPORTUNITATI.CARNETDOC_I', true)),'999999999999999999'), TO_NUMBER((current_setting('PKG_OPORTUNITATI.NRDOC_I', true)),'999999999999999999'));
    PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE( TO_NUMBER((current_setting('PKG_OPORTUNITATI.CARNETDOC_I', true)),'999999999999999999'));
  END IF;

  IF  ACARNETDOC &lt;&gt; 0 THEN
    PERFORM PKG_CARNETEDOC_SOLVENUMARDOC( ACARNETDOC, TO_CHAR( ANRDOC,'9999999999'));
  END IF;
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS(82);

  PERFORM NotifyModif( OPERATION, RECID, 'OPORTUNITATI');

  IF (current_setting('PKG_OPORTUNITATI.DoCommit', true)) THEN
  --&lt;sstunknown&gt;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_set_interval_dinamic</obj_name>
  <obj_hashval>5c716f63a135a742598637fd10d45224</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_set_interval_dinamic(INOUT acodjob1 numeric, INOUT adataini date, INOUT adatafin date, INOUT alunaanini numeric, INOUT alunaanfin numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aANSTART    numeric;
  aLUNASTART  numeric;
  aZISTART    numeric;
  aANEND      numeric;
  aLUNAEND    numeric;
  aZIEND      numeric;
  AMAx        numeric;
  LMax        numeric;
  DMax        date;
  TipI        numeric := -1;
  AFin        numeric;
  LFin        numeric;
  DFin        DATE;
BEGIN
  --Florin 22.08.2025 - sinc. Oracle
  --Florin 04.03.2023 - fixat 61205
  --Florin 17.05.2022 - fixat 54291
  --Florin 11.04.2022 - sinc. Oracle (10.04.2022)
  --Florin 15.04.2022 - sinc. Oracle (13.04.2022)
  --Adina 19.08.2021 - sinc.Oracle din 18.08.2021
  --Adina 29.04.2021 - sinc.Oracle
  -- Stef 27.07.2020
  --Adina 08 august 2020 modificat liniile 37 (pus 0 in loc de ''), 44, 47 (pus date_trunc in loc de trunc)

    --  TIPINTERVAL --&gt; 0==(Zi max...zi max)
  --              --&gt; 1==(an max, luna max...an max, luna max)
                  --&gt; 2==(an ini, luna ini...an max, luna max)
                  --&gt; 3==(an max, ianuarie...an max, luna max)
                  --&gt; 4==(an, luna, zi din tabela TMP_INTERVAL_LISTARE) -- pentru liste WEB
                  --&gt; 5==(Zi max - 1...zi max - 1)
    --            --&gt; 6==(an max, luna max  - 1...an max, luna max - 1)

  BEGIN
    SELECT Coalesce(ANSTART,0), Coalesce(LUNASTART,0), Coalesce(ZISTART,0), Coalesce(ANEND,0), Coalesce(LUNAEND,0), Coalesce(ZIEND,0)
    INTO   aANSTART, aLUNASTART, aZISTART, aANEND, aLUNAEND, aZIEND
    FROM   TMP_INTERVAL_LISTARE
    WHERE CODJOB1 = aCODJOB1;
  EXCEPTION WHEN OTHERS THEN
    aANSTART := 0; aLUNASTART := 0; aZISTART := 0; aANEND := 0; aLUNAEND := 0; aZIEND := 0;
  END;

  IF aANSTART &lt;&gt; 0 THEN
    TipI := 4;
  ELSE
    SELECT Coalesce(TIPINTERVAL,1) INTO TipI FROM JOBLISTE1 WHERE CODJOB1 = aCodJob1;
  END IF;

   IF TipI &gt; -1 THEN
    --SELECT LUNAMAXIMA, ANMAXIM, Last_Day(To_Date(COALESCE(LUNAMAXIMA,'')||'.'||COALESCE(ANMAXIM,''), 'mm.yyyy')) INTO LMax, AMax, DMax FROM FIRMALUNI;
    SELECT LUNAMAXIMA, ANMAXIM, Last_Day(To_Date(COALESCE(LUNAMAXIMA,0)||'.'||COALESCE(ANMAXIM,0), 'mm.yyyy')) INTO LMax, AMax, DMax FROM FIRMALUNI;
    --intotdeauna se listeaza pana la ultima luna cu date
    if DMAx &gt; CURRENT_TIMESTAMP then DMAx := CURRENT_TIMESTAMP; END IF;
    aDataFin   := DMax;
    aLunaAnFin := AMax * 12 + LMax;
    --la tip interval 2 data de pornire e fixa, inceput de an sau luna initiala firma, dupa cum e setata in param listei
    IF TipI = 0 THEN
      --aDataIni   := DMax;
      --aLunaAnIni := AMax * 12 + LMax;
        aDataIni   := add_days(CURRENT_TIMESTAMP::date, -1::integer);
      aDataFin   := aDataIni;
    ELSIF TipI = 1 THEN
      aDataIni   := Date_Trunc('month',DMax);     --aDataIni   := Trunc(DMax,'mm');
      aLunaAnIni := AMax * 12 + LMax;
    ELSIF TipI = 3 THEN
      aDataIni   := Date_Trunc('year',DMax);  --aDataIni   := Trunc(DMax,'yyyy');
      aLunaAnIni := AMax * 12 + 1;
    ELSIF TipI = 4 THEN -- caz special pentru liste web
      IF aANEND=0 AND aLUNAEND=0 THEN --are numai start
        aANEND   := aAnStart;
        IF aLUNASTART = 0 THEN -- listeaza AnStart intreg
          aLunaStart := 1;
          aLunaEnd   := 12;
        ELSE
          aLunaEnd := aLunaStart;
        END IF;
      END IF;
      IF aANEND*12 + aLUNAEND &gt; AMAx*12+LMAX THEN
        aANEND := AMax;
        aLUNAEND := LMAX;
      END IF;
      IF aZIEND = 0 THEN
        aDataFin   := Last_Day(To_Date(aLUNAEND||'.'||aANEND,'mm.yyyy'));
      ELSE
        aDataFin   := To_Date(aZIEND||'.'||aLUNAEND||'.'||aANEND,'dd.mm.yyyy');
      END IF;
      aLunaAnFin := aANEND*12 + aLUNAEND;

      IF aZISTART = 0 then aZISTART := 1;END IF;
      aDataIni   := To_Date(aZISTART||'.'||aLUNASTART||'.'||aANSTART,'dd.mm.yyyy');
      aLunaAnIni := aANSTART*12 + aLUNASTART;
     ELSEIF TipI = 5 THEN
       aDataIni   := CURRENT_DATE;
       aDataFin   := aDataIni;
     ELSEIF TipI = 6 THEN
       SELECT LUNAMAXIMA, ANMAXIM, Last_Day(To_Date(LUNAMAXIMA||'.'||ANMAXIM,'mm.yyyy')) INTO LMax, AMax, DMax FROM FIRMALUNI;
      LFin := LMax;
      AFin := AMax;
      DFin := DMax;
      LMax := LMax - 1;
       If LMax = 0 then
         LMax := 12;
         AMax := AMax - 1;
       END IF;
       DMax := Last_Day(To_Date(LMAX||'.'||AMAX,'mm.yyyy'));
       if DMAx &gt; CURRENT_DATE then DMAx := CURRENT_DATE; END IF;
         aDataIni   := Date_Trunc('month', DMax);
         aDataFin   := DFin;
         aLunaAnIni := (AMax * 12 + LMax);
         aLunaAnFin := (AFin * 12 + LFin);
    END IF;
  END IF;
  PERFORM PKG_ORA_LISTS_SET_INTERVAL_LISTARE( aDataIni, aDataFin);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_set_job</obj_name>
  <obj_hashval>0b8a8909a7d05bde21c2fafe8492f07e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_set_job(acodorar numeric, acodjob1 numeric, activ boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  S          varchar;
  aListID    numeric;
  aListVER   numeric;
  ANUMETMP   varchar;
  SORAR      varchar;
  aJobName   varchar;
  STOREDPROC varchar;
  ALISTANAME varchar;
  aTableName varchar;

  IsWebServer numeric;  -- 28.01.2021
  aCodJob     numeric;  -- 28.01.2021

  aFirmaName  varchar;
  sjob numeric;
BEGIN
  --Florin 19.09.2024 - sysdate
  --Adina 31.03.2021 - sinc.Oracle din 31.03.2021
  --Florin 05.02.2021 - tradus nextval
  aFirmaName := coalesce(current_setting('PKG_GLOBALS.FIRMANAME', true), '');

  aJobName := 'JLIST' || coalesce(aCODJOB1,'');
  SELECT O.DENUMIRE INTO SORAR FROM ORAR O WHERE o.codorar = aCODORAR;

  ANUMETMP := 'JLST' || coalesce(ACODJOB1,'');

  SELECT J1.CodJob, J1.LISTAID, J1.LISTAVER, L.NAME, tabla INTO aCodJob, ALISTID, ALISTVER, ALISTANAME, aTableName
  FROM JOBLISTE1 J1
       INNER JOIN WINMADMIN.LISTS L ON  J1.LISTAID = L.LISTID AND  J1.LISTAVER = L.LISTVER
  WHERE J1.CODJOB1 = ACODJOB1;

  SELECT WebServer into IsWebServer from JobListe where CodJob = aCodJob;

  SELECT l.storedprocname INTO STOREDPROC
  FROM JOBLISTE1 J1
       INNER JOIN WINMADMIN.LISTS L ON  J1.LISTAID = L.LISTID AND COALESCE(STOREDPROCNAME, '?') &lt;&gt; '?'
  WHERE J1.CODJOB1 = ACODJOB1 LIMIT 1;

  IF  COALESCE( STOREDPROC, '?') &lt;&gt; '?' THEN
    IF  COALESCE(IsWebServer, 0) = 1 THEN


    S :=   'do language plpgsql ' ||
           '$$ '||
           'begin ' ||
              aFirmaName || '.PKG_ORA_LISTS_DO_JOBLISTA_WEBSERVICE(''' ||  aFirmaName  || ''', ' || aCODJOB1 || '); ' ||
           'end;
            $$;';
    ELSE
      S := 'do language plpgsql ' ||
           '$$ '||
           'DECLARE TMP_NAME VARCHAR; USERN NUMERIC;'                                                          || coalesce(Chr( 13),'') || coalesce(Chr( 10),'') ||
           'BEGIN '                                                                                            || coalesce(Chr( 13),'') || coalesce(Chr( 10),'') ||
           '  PERFORM PKG_ORA_LISTS_SET_VARIABILE_SESIUNE(' || coalesce(aCODJOB1,'') || '); '                  || coalesce(Chr( 13),'') || coalesce(Chr( 10),'') ||
           '  PERFORM PKG_ORA_LISTS_CREAZA_TABLA(TMP_NAME,' || coalesce(( ALISTID)::varchar,'') || ',' || coalesce(( ALISTVER)::varchar,'') || ',' || coalesce(aCODJOB1,'') || '); ' || coalesce(Chr( 13),'') || coalesce(Chr( 10),'') ||
           '  ' || coalesce(STOREDPROC,'') || '(TMP_NAME,' || coalesce(( aListID)::varchar,'') || ',' || coalesce(( AlISTvER)::varchar,'') || '); ' || coalesce(Chr( 13),'') || coalesce(Chr( 10),'') ||
           '  INSERT INTO JOBLISTEFIN (CODJOBLISTEFIN,CODJOB1,TABLA,SUBUNITATEA,SKEMAFIRMA,LISTANAME,DATAGEN,TABLE_TYPE,TIPDEPO,LISTID,LISTVER, DATAINI, DATAFIN)' || coalesce(Chr( 13),'') || coalesce(Chr( 10),'') ||
           '  VALUES (NEXTVAL(''SEQ_JOBLISTEFIN_CODJOBLISTEFIN''),' || coalesce(aCODJOB1,'') || ',TMP_NAME,GETSUBUNITATE(),''' || coalesce(current_setting('PKG_GLOBALS.FIRMANAME', true),'') || ''',''' || coalesce(ALISTANAME,'') || ''',current_date,0,0,' || coalesce(( ALISTID)::varchar,'') || ',' || coalesce(( ALISTVER)::varchar,'') || ',current_setting(''PKG_ORA_LISTS.JOB_DATAIni'', true), current_setting(''PKG_ORA_LISTS.JOB_DATAFIN'', true););' || coalesce(Chr( 13),'') || coalesce(Chr( 10),'') ||
           '  PERFORM PKG_ORA_LISTS_MESAJ_JOB_EXECUTAT(' || coalesce(aCODJOB1,'') || ');'                   || coalesce(Chr( 13),'') || coalesce(Chr( 10),'') ||
           '  PERFORM PKG_ORA_LISTS_CREATE_VIEW_4_LAST_JOB (' || coalesce(aCODJOB1,'') || ');'                      || coalesce(Chr( 13),'') || coalesce(Chr( 10),'') ||
           '  --COMMIT;'                                                                                    || coalesce(Chr( 13),'') || coalesce(Chr( 10),'') ||
           'END;
            $$;';
    END IF;

    SELECT jobid INTO sjob FROM pgagent.pga_job WHERE jobname = aJobName;
    BEGIN
      PERFORM pkg_scheduler_drop_job(sjob);
      --PERFORM DBMS_SCHEDULER.drop_job( aJobName, TRUE);
    EXCEPTION WHEN OTHERS THEN
      NULL;
    END;

    --PERFORM dbms_scheduler.create_job( job_name =&gt; aJobName, job_type =&gt; 'PLSQL_BLOCK', job_action =&gt; s, schedule_name =&gt; SORAR, comments =&gt; ( aCODJOB1)::varchar, auto_drop =&gt; false);
    --SELECT pkg_scheduler_updatejob INTO aJobID FROM pkg_scheduler_updatejob(1, 0,
--                                      v_rec.DenJob,
--                                      v_rec.ENABLED,  --true,
--                                      v_rec.ora,
--                                      v_rec.min,
--                                      v_rec.repetare,
--                                      v_rec.zile_sapt,
--                                      v_rec.zile_luna,
--                                      v_rec.data_start,
--                                      v_rec.data_fin,
--                                      asql);


    IF activ THEN
      UPDATE pgagent.pga_job SET JOBENABLED = 'TRUE' WHERE UPPER(JOBNAME) = UPPER(AJOBNAME);
      --PERFORM DBMS_SCHEDULER.enable( AJOBNAME);
    ELSE
      UPDATE pgagent.pga_job SET JOBENABLED = 'FALSE' WHERE UPPER(JOBNAME) = UPPER(AJOBNAME);
      --PERFORM DBMS_SCHEDULER.disable( AJOBNAME);
    END IF;
  ELSE
    BEGIN
      PERFORM pkg_scheduler_drop_job(sjob);
      --PERFORM DBMS_SCHEDULER.drop_job( aJobName, TRUE);
    EXCEPTION WHEN OTHERS THEN
      NULL;
    END;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_getvalconsumpecomanda</obj_name>
  <obj_hashval>1faf4988f58f917c4916986b7e46ee32</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_getvalconsumpecomanda(INOUT wme_result numeric, INOUT acodcomanda1 numeric, INOUT cusupliment numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  V_TMP   RECORD;
  aValMat numeric;
  aPret   numeric;
  aCant   numeric;
BEGIN
  --Florin 16.03.2023 - sinc. Oracle (14/15.03.2023)
  aValMat := 0;
  IF  (fnc_GetValConstantaLucru('CoefMatManInPretNP')) = '1' THEN
    IF  CuSupliment = 1 THEN
      FOR v_rec IN (SELECT l1.cant CANTLIVR, COALESCE(ns1.pretmat, 0) PU, COALESCE(nsi.pret, 0) - COALESCE(nsi.adaos, 0) PUNS, COALESCE(ns1.tipdoc, 0) TIPDOC, COALESCE(ns1.dirty, 1) DIRTY, nsi.codnirstoc, COALESCE(g.coefcheltmat, 0) COEFMAT
                    FROM iesiri1 ies1
                        INNER JOIN iesiri   ies ON  ies.codies     = ies1.codies
                        INNER JOIN ngest    g   ON  g.codgest      = ies.codgestprod
                        INNER JOIN livr     l   ON  l.codies       = ies.codies
                        INNER JOIN livr1    l1  ON  l1.codies1     = ies1.codies1 and  l.codlivr = l1.codlivr
                        INNER JOIN nirstoc  nsi ON  nsi.codnirstoc = l1.codnirstoc
                        LEFT  JOIN nirstoc1 ns1 ON  ns1.codnirstoc = nsi.codnirstoc
                    WHERE COALESCE(ies.anulat, 0) = 0 and  COALESCE(ies.operat, 0) = 1 and  ies1.codcmdint1 = aCodComanda1
                    UNION ALL
                    SELECT
                      i1.cant cantlivr,
                      i1.pu * case when coalesce(i.moneda,0) &gt; 0 then i.curs else 1 end,
                      i1.pu puns,
                      1 tipdoc,
                      0 dirty,
                      0 codnirstoc,
                      0 coefmat
                    from intrari1 i1
                    inner join intrari i on i.codintr = i1.codintr
                    where COALESCE(i.anulat,0) = 0 and nvl(i.operat, 0) = 1 and i1.tiplinie = 'S'
                      and i1.codcmdint1 = aCodComanda1 and exists (
                        select mat.codobiect
                        from prodmat mat
                        inner join cmdprodmat cmd on cmd.codprodmat = mat.codmat
                        inner join comanda1 c1 on c1.codcomanda1 = cmd.codcomanda1
                        where c1.codcomanda1 = aCodComanda1 and mat.tip = 6 and mat.codobiect = i1.codobiect
                        )
                   )
      LOOP
        IF  v_rec.tipdoc = 7 and  v_Rec.dirty = 1 THEN
          aValMat := aValMat + v_Rec.cantlivr * (SELECT PKG_PRETPROD_GetPretNirStoc1Mat.WME_RESULT FROM PKG_PRETPROD_GetPretNirStoc1Mat(NULL,v_rec.codnirstoc,NULL)) * (  1 + v_rec.coefmat) ;
        ELSE
          IF  v_rec.tipdoc = 7 and  v_Rec.dirty = 0 THEN
            aValMat := aValMat + v_Rec.cantlivr * v_rec.pu * (  1 + v_rec.coefmat) ;
          ELSE
            IF  v_Rec.dirty = 1 THEN
              aValMat := aValMat + v_Rec.cantlivr * v_rec.puns * (  1 + v_rec.coefmat) ;
            ELSE
              aValMat := aValMat + v_Rec.cantlivr * v_rec.pu * (  1 + v_rec.coefmat) ;
            END IF;
          END IF;
        END IF;
      END LOOP;
    ELSE
      FOR v_rec IN (SELECT mat.cant, mat.codcmdprodmat FROM cmdprodmat mat WHERE mat.codcomanda1 = aCodComanda1 and  tip = 1) LOOP
        aCant := v_rec.cant;
        FOR v_tmp IN (SELECT l1.cant CANTLIVR, COALESCE(ns1.pretmat, 0) PU, ies1.pu PRETDOC, COALESCE(nsi.pret, 0) - COALESCE(nsi.adaos, 0) PUNS, COALESCE(ns1.tipdoc, 0) TIPDOC, COALESCE(ns1.dirty, 1) DIRTY, nsi.codnirstoc, COALESCE(g.coefcheltmat, 0) COEFMAT
                      FROM iesiri1 ies1
                          INNER JOIN iesiri      ies ON  ies.codies        = ies1.codies
                          INNER JOIN ngest       g   ON  g.codgest         = ies.codgestprod
                          INNER JOIN livr        l   ON  l.codies          = ies.codies
                          INNER JOIN livr1       l1  ON  l1.codies1        = ies1.codies1 and  l.codlivr = l1.codlivr
                          INNER JOIN nirstoc     nsi ON  nsi.codnirstoc    = l1.codnirstoc
                          INNER JOIN iesprodlink l   ON  l.codies1         = ies1.codies1
                          INNER JOIN cmdprodmat  mat ON  mat.codcmdprodmat = l.codcmdprodmat
                          LEFT  JOIN nirstoc1    ns1 ON  ns1.codnirstoc    = nsi.codnirstoc
                      WHERE COALESCE(ies.anulat, 0) = 0 and  COALESCE(ies.operat, 0) = 1 and  mat.codcmdprodmat = v_rec.codcmdprodmat
                      UNION ALL
                    SELECT
                      i1.cant cantlivr,
                      i1.pu * case when coalesce(i.moneda,0) &gt; 0 then i.curs else 1 end,
                      i1.pu pretdoc,
                      i1.pu puns,
                      1 tipdoc,
                      0 dirty,
                      0 codnirstoc,
                      0 coefmat
                    from intrari1 i1
                    inner join intrari i on i.codintr = i1.codintr
                    where COALESCE(i.anulat,0) = 0 and nvl(i.operat, 0) = 1 and i1.tiplinie = 'S'
                      and i1.codcmdint1 = aCodComanda1 and exists (
                        select mat.codobiect
                        from prodmat mat
                        inner join cmdprodmat cmd on cmd.codprodmat = mat.codmat
                        inner join comanda1 c1 on c1.codcomanda1 = cmd.codcomanda1
                        where c1.codcomanda1 = aCodComanda1 and mat.tip = 6 and mat.codobiect = i1.codobiect
                        )
                     )
        LOOP
          IF  aCant = 0 THEN EXIT ; END IF;
          IF  aCant &lt; v_tmp.cantlivr THEN
            IF  v_tmp.tipdoc = 7 and  v_tmp.dirty = 1 THEN
              aValMat := aValMat + aCant * (SELECT PKG_PRETPROD_GetPretNirStoc1Mat.WME_RESULT FROM PKG_PRETPROD_GetPretNirStoc1Mat(NULL,v_tmp.codnirstoc,NULL)) * (  1 + v_tmp.coefmat) ;
            ELSE
              IF  v_tmp.tipdoc = 7 and  v_tmp.dirty = 0 THEN
                aValMat := aValMat + aCant * v_tmp.pu * (  1 + v_tmp.coefmat) ;
              ELSE
                IF  v_tmp.dirty = 1 THEN
                  aValMat := aValMat + aCant * v_tmp.puns * (  1 + v_tmp.coefmat) ;
                ELSE
                  aValMat := aValMat + aCant * v_tmp.pu * (  1 + v_tmp.coefmat) ;
                END IF;
              END IF;
            END IF;

            aCant := 0;
          ELSE
            IF  v_tmp.tipdoc = 7 and  v_tmp.dirty = 1 THEN
              aValMat := aValMat + v_tmp.cantlivr * (SELECT PKG_PRETPROD_GetPretNirStoc1Mat.WME_RESULT FROM PKG_PRETPROD_GetPretNirStoc1Mat(NULL,v_tmp.codnirstoc,NULL)) * (  1 + v_tmp.coefmat) ;
            ELSE
              IF  v_tmp.tipdoc = 7 and  v_tmp.dirty = 0 THEN
                aValMat := aValMat + v_tmp.cantlivr * v_tmp.pu * (  1 + v_tmp.coefmat) ;
              ELSE
                IF  v_tmp.dirty = 1 THEN
                  aValMat := aValMat + v_tmp.cantlivr * v_tmp.puns * (  1 + v_tmp.coefmat) ;
                ELSE
                  aValMat := aValMat + v_tmp.cantlivr * v_tmp.pu * (  1 + v_tmp.coefmat) ;
                END IF;
              END IF;
            END IF;

            aCant := aCant - v_tmp.cantlivr;
          END IF;
        END LOOP;
      END LOOP;
    END IF;
  ELSE
    IF  CuSupliment = 1 THEN
      FOR v_rec IN (SELECT l1.cant CANTLIVR, COALESCE(ns1.pretmat, 0) PU, COALESCE(nsi.pret, 0) - COALESCE(nsi.adaos, 0) PUNS, COALESCE(ns1.tipdoc, 0) TIPDOC, COALESCE(ns1.dirty, 1) DIRTY, nsi.codnirstoc
                    FROM iesiri1 ies1
                        INNER JOIN iesiri   ies ON  ies.codies     = ies1.codies
                        INNER JOIN livr     l   ON  l.codies       = ies.codies
                        INNER JOIN livr1    l1  ON  l1.codies1     = ies1.codies1 and  l.codlivr = l1.codlivr
                        INNER JOIN nirstoc  nsi ON  nsi.codnirstoc = l1.codnirstoc
                        LEFT  JOIN nirstoc1 ns1 ON  ns1.codnirstoc = nsi.codnirstoc
                    WHERE COALESCE(ies.anulat, 0) = 0 and  COALESCE(ies.operat, 0) = 1 and  ies1.codcmdint1 = aCodComanda1
                    UNION ALL
                    SELECT
                      i1.cant cantlivr,
                      i1.pu * case when coalesce(i.moneda,0) &gt; 0 then i.curs else 1 end,
                      i1.pu puns,
                      1 tipdoc,
                      0 dirty,
                      0 codnirstoc
                    from intrari1 i1
                    inner join intrari i on i.codintr = i1.codintr
                    where COALESCE(i.anulat,0) = 0 and nvl(i.operat, 0) = 1 and i1.tiplinie = 'S'
                      and i1.codcmdint1 = aCodComanda1 and exists (
                        select mat.codobiect
                        from prodmat mat
                        inner join cmdprodmat cmd on cmd.codprodmat = mat.codmat
                        inner join comanda1 c1 on c1.codcomanda1 = cmd.codcomanda1
                        where c1.codcomanda1 = aCodComanda1 and mat.tip = 6 and mat.codobiect = i1.codobiect
                        )
                   )
      LOOP
        IF  v_rec.tipdoc = 7 and  v_Rec.dirty = 1 THEN
          aValMat := aValMat + v_Rec.cantlivr * (SELECT PKG_PRETPROD_GetPretNirStoc1Mat.WME_RESULT FROM PKG_PRETPROD_GetPretNirStoc1Mat(NULL,v_rec.codnirstoc,NULL));
        ELSE
          IF  v_rec.tipdoc = 7 and  v_Rec.dirty = 0 THEN
            aValMat := aValMat + v_Rec.cantlivr * v_rec.pu;
          ELSE
            IF  v_Rec.dirty = 1 THEN
              aValMat := aValMat + v_Rec.cantlivr * v_rec.puns;
            ELSE
              aValMat := aValMat + v_Rec.cantlivr * v_rec.pu;
            END IF;
          END IF;
        END IF;
      END LOOP;
    ELSE
      FOR v_rec IN (SELECT mat.cant, mat.codcmdprodmat FROM cmdprodmat mat WHERE mat.codcomanda1 = aCodComanda1 and  tip = 1) LOOP
        aCant := v_rec.cant;
        FOR v_tmp IN (SELECT l1.cant CANTLIVR, COALESCE(ns1.pretmat, 0) PU, ies1.pu PRETDOC, COALESCE(nsi.pret, 0) - COALESCE(nsi.adaos, 0) PUNS, COALESCE(ns1.tipdoc, 0) TIPDOC, COALESCE(ns1.dirty, 1) DIRTY, nsi.codnirstoc
                      FROM iesiri1 ies1
                          INNER JOIN iesiri      ies ON  ies.codies        = ies1.codies
                          INNER JOIN livr        l   ON  l.codies          = ies.codies
                          INNER JOIN livr1       l1  ON  l1.codies1        = ies1.codies1 and  l.codlivr = l1.codlivr
                          INNER JOIN nirstoc     nsi ON  nsi.codnirstoc    = l1.codnirstoc
                          INNER JOIN iesprodlink l   ON  l.codies1         = ies1.codies1
                          INNER JOIN cmdprodmat  mat ON  mat.codcmdprodmat = l.codcmdprodmat
                          LEFT  JOIN nirstoc1    ns1 ON  ns1.codnirstoc    = nsi.codnirstoc
                      WHERE COALESCE(ies.anulat, 0) = 0 and  COALESCE(ies.operat, 0) = 1 and  mat.codcmdprodmat = v_rec.codcmdprodmat
                      UNION ALL
                    SELECT
                      i1.cant cantlivr,
                      i1.pu * case when coalesce(i.moneda,0) &gt; 0 then i.curs else 1 end,
                      i1.pu pretdoc,
                      i1.pu puns,
                      1 tipdoc,
                      0 dirty,
                      0 codnirstoc
                    from intrari1 i1
                    inner join intrari i on i.codintr = i1.codintr
                    where COALESCE(i.anulat,0) = 0 and nvl(i.operat, 0) = 1 and i1.tiplinie = 'S'
                      and i1.codcmdint1 = aCodComanda1 and exists (
                        select mat.codobiect
                        from prodmat mat
                        inner join cmdprodmat cmd on cmd.codprodmat = mat.codmat
                        inner join comanda1 c1 on c1.codcomanda1 = cmd.codcomanda1
                        where c1.codcomanda1 = aCodComanda1 and mat.tip = 6 and mat.codobiect = i1.codobiect
                        )
                     )
        LOOP
          IF  aCant = 0 THEN EXIT ; END IF;
          IF  aCant &lt; v_tmp.cantlivr THEN
            IF  v_tmp.tipdoc = 7 and  v_tmp.dirty = 1 THEN
              aValMat := aValMat + aCant * (SELECT PKG_PRETPROD_GetPretNirStoc1Mat.WME_RESULT FROM PKG_PRETPROD_GetPretNirStoc1Mat(NULL,v_tmp.codnirstoc,NULL));
            ELSE
              IF  v_tmp.tipdoc = 7 and  v_tmp.dirty = 0 THEN
                aValMat := aValMat + aCant * v_tmp.pu;
              ELSE
                IF  v_tmp.dirty = 1 THEN
                  aValMat := aValMat + aCant * v_tmp.puns;
                ELSE
                  aValMat := aValMat + aCant * v_tmp.pu;
                END IF;
              END IF;
            END IF;

            aCant := 0;
          ELSE
            IF  v_tmp.tipdoc = 7 and  v_tmp.dirty = 1 THEN
              aValMat := aValMat + v_tmp.cantlivr * (SELECT PKG_PRETPROD_GetPretNirStoc1Mat.WME_RESULT FROM PKG_PRETPROD_GetPretNirStoc1Mat(NULL,v_tmp.codnirstoc,NULL));
            ELSE
              IF  v_tmp.tipdoc = 7 and  v_tmp.dirty = 0 THEN
                aValMat := aValMat + v_tmp.cantlivr * v_tmp.pu;
              ELSE
                IF  v_tmp.dirty = 1 THEN
                  aValMat := aValMat + v_tmp.cantlivr * v_tmp.puns;
                ELSE
                  aValMat := aValMat + v_tmp.cantlivr * v_tmp.pu;
                END IF;
              END IF;
            END IF;

            aCant := aCant - v_tmp.cantlivr;
          END IF;
        END LOOP;
      END LOOP;
    END IF;
  END IF;

  WME_Result :=  aValMat;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodnet_incarcamancmd1</obj_name>
  <obj_hashval>c353ebd1f71264b6c5459382ec67f6d8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodnet_incarcamancmd1(asubunitatea numeric, acodgest numeric, acodcentru numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAnLuna numeric;
BEGIN
  --Laura 17.12.2021 - sinc. Oracle (17.12.2021)
  --Adina 09.08.2021 - sinc.Oracle din 09.08.2021
  --Adina 09.08.2021 - sinc.Oracle din 06.08.2021 - repunere varianta veche
  --Adina 05.08.2021 - sinc.Oracle din 04.08.2021
  vAnLuna := (SELECT PKG_GLOBALS_GetANLUCRU.WME_RESULT FROM PKG_GLOBALS_GetANLUCRU(NULL,NULL)) * 12 + (SELECT PKG_GLOBALS_GetLUNALUCRU.WME_RESULT FROM PKG_GLOBALS_GetLUNALUCRU(NULL,NULL));
  DELETE FROM comanda1_man;
  DELETE FROM predari_man;
  DELETE FROM consumuri_man;

  IF  aCodCentru &gt; 0 THEN
    INSERT INTO comanda1_man(codcomanda1)
    SELECT codcomanda1
    FROM (
          SELECT c1.codcomanda1
          FROM comanda1 c1 INNER JOIN comanda c ON  c.codcomanda = c1.codcomanda
          WHERE  COALESCE( c.inchisa, 0) = 0
            and  COALESCE( c.blocat , 0) = 0
            and  COALESCE( c.operat , 0) = 1
            and  COALESCE( c.anulat , 0) = 0
            and  c.subunitatea = aSubunitatea
            and (aCodGest = 0 or  c.codgest = aCodGest)
            and  c.an * 12 + c.luna &lt;= vAnLuna
            and  c1.codcentru = aCodCentru
          union ALL
          SELECT c1.codcomanda1
          FROM iesiri i
              INNER JOIN iesiri1     i1  ON  i.codies          = i1.codies
              INNER JOIN iesprodlink l   ON  l.codies1         = i1.codies1
              INNER JOIN cmdprodmat  mat ON  mat.codcmdprodmat = l.codcmdprodmat
              INNER JOIN comanda1    c1  ON  mat.codcomanda1   = c1.codcomanda1
              INNER JOIN comanda     c   ON  c.codcomanda      = c1.codcomanda
          WHERE  COALESCE( c.inchisa, 0) = 1
            and  COALESCE( c.blocat , 0) = 0
            and  COALESCE( c.operat , 0) = 1
            and  COALESCE( c.anulat , 0) = 0
            and  c.subunitatea = aSubunitatea
            and (aCodGest = 0 or  c.codgest = aCodGest)
            and  c.an * 12 + c.luna &lt;= vAnLuna
            and  i.an * 12 + i.luna &gt;= vAnLuna
            and  COALESCE( i.blocat, 0) = 0
            and  COALESCE( i.operat, 0) = 1
            and  COALESCE( i.anulat, 0) = 0
            and  c1.codcentru = aCodCentru
          union ALL
          SELECT c1.codcomanda1
          FROM intrari i
              INNER JOIN intrari1     i1   ON  i.codintr          = i1.codintr
              INNER JOIN intrprodlink l    ON  l.codintr1         = i1.codintr1
              INNER JOIN cmdprodmat   prod ON  prod.codcmdprodmat = l.codliniecomanda
              INNER JOIN comanda1     c1   ON  prod.codcomanda1   = c1.codcomanda1
              INNER JOIN comanda      c    ON  c.codcomanda       = c1.codcomanda
          WHERE  COALESCE( c.inchisa, 0) = 1
            and  COALESCE( c.blocat , 0) = 0
            and  COALESCE( c.operat , 0) = 1
            and  COALESCE( c.anulat , 0) = 0
            and  c.subunitatea = aSubunitatea
            and (aCodGest = 0 or  c.codgest = aCodGest)
            and  c.an * 12 + c.luna &lt;= vAnLuna
            and  i.an * 12 + i.luna &gt;= vAnLuna
            and  COALESCE( i.blocat, 0) = 0
            and  COALESCE( i.operat, 0) = 1
            and  COALESCE( i.anulat, 0) = 0
            and  c1.codcentru = aCodCentru
          union ALL
          SELECT c1.codcomanda1
          FROM raportp rp
              INNER JOIN raportp1    rp1 ON  rp.codraportp     = rp1.codraportp
              INNER JOIN raportp2    rp2 ON  rp1.codraportp1   = rp2.codraportp1
              INNER JOIN manprodlink l   ON  l.codraportp2     = rp2.codraportp2
              INNER JOIN cmdprodman  man ON  man.codcmdprodman = l.codcmdprodman
              INNER JOIN comanda1    c1  ON  man.codcomanda1   = c1.codcomanda1
              INNER JOIN comanda     c   ON  c.codcomanda      = c1.codcomanda
          WHERE  COALESCE( c.inchisa, 0) = 1
            and  COALESCE( c.blocat , 0) = 0
            and  COALESCE( c.operat , 0) = 1
            and  COALESCE( c.anulat , 0) = 0
            and  c.subunitatea = aSubunitatea
            and (aCodGest = 0 or  c.codgest = aCodGest)
            and  c.an * 12 + c.luna &lt;= vAnLuna
            and  rp.an * 12 + rp.luna &gt;= vAnLuna
            and  c1.codcentru = aCodCentru
    ) A_PG;
  ELSE
    INSERT INTO comanda1_man(codcomanda1)
    SELECT codcomanda1
    FROM (
          SELECT c1.codcomanda1
          FROM comanda1 c1 INNER JOIN comanda c ON  c.codcomanda = c1.codcomanda
          WHERE COALESCE( c.inchisa, 0) = 0 and  COALESCE( c.blocat, 0) = 0 and  COALESCE( c.operat, 0) = 1 and  COALESCE( c.anulat, 0) = 0 and  c.subunitatea = aSubunitatea and (   aCodGest = 0 or  c.codgest = aCodGest)  and  c.an * 12 + c.luna &lt;= vAnLuna
          union ALL
          SELECT c1.codcomanda1
          FROM iesiri i
              INNER JOIN iesiri1     i1  ON  i.codies          = i1.codies
              INNER JOIN iesprodlink l   ON  l.codies1         = i1.codies1
              INNER JOIN cmdprodmat  mat ON  mat.codcmdprodmat = l.codcmdprodmat
              INNER JOIN comanda1    c1  ON  mat.codcomanda1   = c1.codcomanda1
              INNER JOIN comanda     c   ON  c.codcomanda      = c1.codcomanda
          WHERE  COALESCE( c.inchisa, 0) = 1
            and  COALESCE( c.blocat , 0) = 0
            and  COALESCE( c.operat , 0) = 1
            and  COALESCE( c.anulat , 0) = 0
            and  c.subunitatea = aSubunitatea
            and (aCodGest = 0 or  c.codgest = aCodGest)
            and  c.an * 12 + c.luna &lt;= vAnLuna
            and  i.an * 12 + i.luna &gt;= vAnLuna
            and  COALESCE( i.blocat, 0) = 0
            and  COALESCE( i.operat, 0) = 1
            and  COALESCE( i.anulat, 0) = 0
          union ALL
          SELECT c1.codcomanda1
          FROM intrari i
              INNER JOIN intrari1     i1   ON  i.codintr          = i1.codintr
              INNER JOIN intrprodlink l    ON  l.codintr1         = i1.codintr1
              INNER JOIN cmdprodmat   prod ON  prod.codcmdprodmat = l.codliniecomanda
              INNER JOIN comanda1     c1   ON  prod.codcomanda1   = c1.codcomanda1
              INNER JOIN comanda      c    ON  c.codcomanda       = c1.codcomanda
          WHERE  COALESCE( c.inchisa, 0) = 1
            and  COALESCE( c.blocat , 0) = 0
            and  COALESCE( c.operat , 0) = 1
            and  COALESCE( c.anulat , 0) = 0
            and  c.subunitatea = aSubunitatea
            and (aCodGest = 0 or  c.codgest = aCodGest)
            and  c.an * 12 + c.luna &lt;= vAnLuna
            and  i.an * 12 + i.luna &gt;= vAnLuna
            and  COALESCE( i.blocat, 0) = 0
            and  COALESCE( i.operat, 0) = 1
            and  COALESCE( i.anulat, 0) = 0
          union ALL
          SELECT c1.codcomanda1
          FROM raportp rp
              INNER JOIN raportp1    rp1 ON  rp.codraportp     = rp1.codraportp
              INNER JOIN raportp2    rp2 ON  rp1.codraportp1   = rp2.codraportp1
              INNER JOIN manprodlink l   ON  l.codraportp2     = rp2.codraportp2
              INNER JOIN cmdprodman  man ON  man.codcmdprodman = l.codcmdprodman
              INNER JOIN comanda1    c1  ON  man.codcomanda1   = c1.codcomanda1
              INNER JOIN comanda     c   ON  c.codcomanda      = c1.codcomanda
          WHERE  COALESCE( c.inchisa, 0) = 1
            and  COALESCE( c.blocat , 0) = 0
            and  COALESCE( c.operat , 0) = 1
            and  COALESCE( c.anulat , 0) = 0
            and  c.subunitatea = aSubunitatea
            and (aCodGest = 0 or  c.codgest = aCodGest)
            and  c.an * 12 + c.luna &lt;= vAnLuna
            and  rp.an * 12 + rp.luna &gt;= vAnLuna
    ) B_PG;
  END IF;

  if coalesce(fnc_GetValConstantaLucru('ProdNetSuplim')::numeric,2) = 1 then
    insert into predari_man
    select mat.cant * sum(il.cant)/prod.cant cant, mat.codcmdprodmat, mat.codobiect, mat.codcomanda1
    from intrprodlink il
         inner join intrari1     i1   on i1.codintr1        = il.codintr1
         inner join intrari      i    on i1.codintr         = i.codintr
         inner join cmdprodmat   prod on il.codliniecomanda = prod.codcmdprodmat
         inner join cmdprodmat   mat  on prod.codcomanda1   = mat.codcomanda1 and mat.tip = 1
         inner join comanda1_man c1   on c1.codcomanda1     = mat.codcomanda1
    where COALESCE(i.blocat,0) = 0 and COALESCE(i.operat,0) = 1 and COALESCE(i.anulat,0) = 0
          and COALESCE(prod.cant,0) &gt; 0 and i.an*12+i.luna &lt;= vAnLuna
    group by mat.codcmdprodmat, mat.cant, prod.cant, mat.codobiect, mat.codcomanda1;

    insert into consumuri_man
    select COALESCE(cant,0) cant, case when COALESCE(cant,0) = 0 then 0 else val/cant end pret, codcmdprodmat, codies1, codobiect, codcomanda1 from (
    select sum(l1.cant*
               case
                 when il.codies1 is null then
                   case
                     when RestDePredat.Rest &gt;= prod.cant then 0
                     else (prod.cant - coalesce(RestDePredat.Rest,0))/prod.cant
                   end
                 else 1
               end) cant,
           sum(l1.cant*
               case
                 when il.codies1 is null then
                   case
                     when RestDePredat.Rest &gt;= prod.cant then 0
                     else (prod.cant - coalesce(RestDePredat.Rest,0))/prod.cant
                   end
                 else 1
               end
               * ns.pret) val, coalesce(il.codcmdprodmat,0) codcmdprodmat, i1.codies1, c1.codcomanda1, i1.codobiect
    from comanda1_man c1
         inner join cmdprodmat prod on c1.codcomanda1 = prod.codcomanda1 and COALESCE(prod.tip,0) = 0
         inner join iesiri1    i1   on i1.codcmdint1  = c1.codcomanda1
         inner join iesiri     i    on i1.codies      = i.codies
         left  join (select sum(ilc.cant) Rest, prodc.codcmdprodmat
                     from comanda1_man cc1
                          inner join cmdprodmat   prodc on cc1.codcomanda1     = prodc.codcomanda1 and COALESCE(prodc.tip,0) = 0
                          inner join intrprodlink ilc   on prodc.codcmdprodmat = ilc.codliniecomanda
                          inner join intrari1     i1c   on ilc.codintr1        = i1c.codintr1
                          inner join intrari      ic    on i1c.codintr         = ic.codintr
                     where COALESCE(ic.blocat,0) = 0 and COALESCE(ic.operat,0) = 1 and COALESCE(ic.anulat,0) = 0 and ic.an*12+ic.luna &lt;= vAnLuna
                     group by prodc.codcmdprodmat
                    ) RestDePredat on RestDePredat.codcmdprodmat = prod.codcmdprodmat
         left  join livr        l  on i.codies      = l.codies
         left  join livr1       l1 on l1.codies1    = i1.codies1 and l.codlivr = l1.codlivr
         left  join nirstoc     ns on l1.codnirstoc = ns.codnirstoc
         left  join centrecost  cc on i1.codcentru  = cc.codcentru
         left  join iesprodlink il on i1.codies1    = il.codies1
         left  JOIN (select c1.codcomanda1, max(i.an*12+i.luna) AnLunaFinal
                     from comanda1_man c1
                          inner join cmdprodmat   prod on c1.codcomanda1     = prod.codcomanda1 and COALESCE(prod.tip,0) = 0
                          inner join intrprodlink il   on prod.codcmdprodmat = il.codliniecomanda
                          inner join intrari1     i1   on il.codintr1        = i1.codintr1
                          inner join intrari      i    on i1.codintr         = i.codintr
                     where prod.rest &lt;=0
                           and COALESCE(i.blocat,0) = 0 and COALESCE(i.operat,0) = 1 and COALESCE(i.anulat,0) = 0
                     group by c1.codcomanda1
                    ) Stinse on Stinse.codcomanda1 = c1.codcomanda1
    where COALESCE(cc.tipaloc,0) = 0
          and ((prod.cant - COALESCE(RestDePredat.Rest,0) &gt; 0) or ((prod.cant - COALESCE(RestDePredat.Rest,0) &lt;= 0) and (Stinse.AnLunaFinal &gt; vAnLuna)))
          and i.an*12+i.luna &lt;= vAnLuna
    group by il.codcmdprodmat, i1.codies1, c1.codcomanda1, i1.codobiect ) A_PG;
  else
    insert into predari_man(cant,codcmdprodmat)
    select mat.cant * sum(il.cant)/prod.cant cant, mat.codcmdprodmat
    from intrprodlink il
         inner join intrari1     i1   on i1.codintr1        = il.codintr1
         inner join intrari      i    on i1.codintr         = i.codintr
         inner join cmdprodmat   prod on il.codliniecomanda = prod.codcmdprodmat
         inner join cmdprodmat   mat  on prod.codcomanda1   = mat.codcomanda1 and mat.tip = 1
         inner join comanda1_man c1   on c1.codcomanda1     = mat.codcomanda1
    where COALESCE(i.blocat,0) = 0 and COALESCE(i.operat,0) = 1 and COALESCE(i.anulat,0) = 0
          and COALESCE(prod.cant,0) &gt; 0 and i.an*12+i.luna &lt;= vAnLuna
    group by mat.codcmdprodmat, mat.cant, prod.cant;

    insert into consumuri_man(cant,pret,codcmdprodmat,codies1,codcomanda1)
    select COALESCE(cant,0) cant, case when COALESCE(cant,0) = 0 then 0 else val/cant end pret, codcmdprodmat, codies1, codcomanda1 from (
    select sum(l1.cant) cant, sum(l1.cant * ns.pret) val, il.codcmdprodmat, i1.codies1, c1.codcomanda1
    from comanda1_man c1
         inner join cmdprodmat prod on c1.codcomanda1 = prod.codcomanda1 and COALESCE(prod.tip,0) = 0
         inner join iesiri1    i1   on i1.codcmdint1  = c1.codcomanda1
         inner join iesiri     i    on i1.codies      = i.codies
         left  join (select sum(ilc.cant) Rest, prodc.codcmdprodmat
                     from comanda1_man cc1
                          inner join cmdprodmat   prodc on cc1.codcomanda1     = prodc.codcomanda1 and COALESCE(prodc.tip,0) = 0
                          inner join intrprodlink ilc   on prodc.codcmdprodmat = ilc.codliniecomanda
                          inner join intrari1     i1c   on ilc.codintr1        = i1c.codintr1
                          inner join intrari      ic    on i1c.codintr         = ic.codintr
                     where COALESCE(ic.blocat,0) = 0 and COALESCE(ic.operat,0) = 1 and COALESCE(ic.anulat,0) = 0 and ic.an*12+ic.luna &lt;= vAnLuna
                     group by prodc.codcmdprodmat
                    ) RestDePredat on RestDePredat.codcmdprodmat = prod.codcmdprodmat
         left  join livr        l  on i.codies      = l.codies
         left  join livr1       l1 on l1.codies1    = i1.codies1 and l.codlivr = l1.codlivr
         left  join nirstoc     ns on l1.codnirstoc = ns.codnirstoc
         left  join centrecost  cc on i1.codcentru  = cc.codcentru
         left  join iesprodlink il on i1.codies1    = il.codies1
         left  JOIN (select c1.codcomanda1, max(i.an*12+i.luna) AnLunaFinal
                     from comanda1_man c1
                          inner join cmdprodmat   prod on c1.codcomanda1     = prod.codcomanda1 and COALESCE(prod.tip,0) = 0
                          inner join intrprodlink il   on prod.codcmdprodmat = il.codliniecomanda
                          inner join intrari1     i1   on il.codintr1        = i1.codintr1
                          inner join intrari      i    on i1.codintr         = i.codintr
                     where prod.rest &lt;=0
                           and COALESCE(i.blocat,0) = 0 and COALESCE(i.operat,0) = 1 and COALESCE(i.anulat,0) = 0
                     group by c1.codcomanda1
                    ) Stinse on Stinse.codcomanda1 = c1.codcomanda1
    where COALESCE(cc.tipaloc,0) = 0
          and ((prod.cant - COALESCE(RestDePredat.Rest,0) &gt; 0) or ((prod.cant - COALESCE(RestDePredat.Rest,0) &lt;= 0) and (Stinse.AnLunaFinal &gt; vAnLuna)))
          and i.an*12+i.luna &lt;= vAnLuna
    group by il.codcmdprodmat, i1.codies1, c1.codcomanda1 ) A_PG;
  end if;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_tras_setjoinuri</obj_name>
  <obj_hashval>69c64f2912fdad87b5d6f5e341a76bea</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_tras_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Adina iulie 2020
PERFORM Pkg_List_Struct_SetTableSpec( current_setting('PKG_LIST_BASE_TRAS.gSuplCols', true));
PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_traseelivrare_setjoinuri</obj_name>
  <obj_hashval>810968e4b6e248136cbcea3b65eb14ea</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_traseelivrare_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 16.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec('');
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_trasinc_setjoinuri</obj_name>
  <obj_hashval>909a7e70ef39d27b45ddda5cbf28f985</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_trasinc_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 16.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_TRASINC.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_trasinc_setparams</obj_name>
  <obj_hashval>e5a5d2c523e07474b2ac255f4dee9d63</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_trasinc_setparams(pcoddistrib numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 16.10.2020
  perform set_config('PKG_LIST_BASE_TRASINC.vCodDistrib',(pCodDistrib)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_traspart_setjoinuri</obj_name>
  <obj_hashval>2c4d02b07ddd77a74c75c30aeb328213</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_traspart_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 16.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_TRASPART.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmarire_predari_setjoinuri</obj_name>
  <obj_hashval>f5288fa294e540c053941a153fe1ed7d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmarire_predari_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 15.09.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_URMARIRE_PREDARI.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmarireincasari_setjoinuri</obj_name>
  <obj_hashval>b1c7417a6be92bac4e4940d11a3eade8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmarireincasari_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 02.09.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_URMARIREINCASARI.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmrealdez_processlist</obj_name>
  <obj_hashval>d0e0fc5cadee8f2cc13b1779e0725f2e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmrealdez_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sWith           varchar := '';
  sSelect         varchar := '';
  sCondGest       varchar := '';
  sCondProd       varchar := '';
  gSuplCols        VARCHAR := 'INTRARI INTR, INTRARI1 INTR1, CMDPRODMAT MAT, NGEST G, NARTOBJ OBJMAT, NART ARTMAT, NUM UM, NARTOBJ OBJRET, NART ARTRET,  NUM UMRET';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 19.10.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_URMREALDEZ.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  perform set_config('PKG_LIST_BASE_URMREALDEZ.vAllGest'  ,current_setting('PKG_LIST_SELECTGESTART.vAllGest'  , true),false);
  perform set_config('PKG_LIST_BASE_URMREALDEZ.vAllArt'   ,current_setting('PKG_LIST_SELECTGESTART.vAllArt'   , true),false);
  perform set_config('PKG_LIST_BASE_URMREALDEZ.vDataStart',current_setting('PKG_LIST_SELECTGESTART.vDataStart', true),false);
  perform set_config('PKG_LIST_BASE_URMREALDEZ.vDataFin'  ,current_setting('PKG_LIST_SELECTGESTART.vDataFin'  , true),false);

  sCondGest := '';

  IF  NOT current_setting('PKG_LIST_BASE_URMREALDEZ.vAllGest', true)::boolean THEN
    sCondGest := 'inner join tmp_manevra_liste tmp on g.codgest::varchar = tmp.valoare and upper(tmp.filtru) = ''CODGEST'' ';
  END IF;

  sCondProd := '';

  IF  NOT current_setting('PKG_LIST_BASE_URMREALDEZ.vAllArt', true)::boolean THEN
    sCondProd := 'inner join tmp_manevra_liste tmp on g.codgest::varchar = tmp.valoare and upper(tmp.filtru) = ''CODPRODCOMP'' ';
  END IF;

  sInsert :=
  'INSERT INTO ' || TMPNAME || '
        (Articol,
         UM,
         Pret,
         CantCom,
         CantReal,
         DifCant,
         ValCom,
         ValReal,
         DifVal,
         NrBon,
         DataBon,
         Sectie,
         Produs,
         UMProdus,
         CantComProd,
         ValProd,
         PretProd
         ' || gUserFields || ') ';

  sWith := 'with
             predari as (
             select
               mat.codcmdprodmat,
               i1.codintr,
               i1.cant cant
             from cmdprodmat mat
                  inner join intrprodlink intrlink on mat.codcmdprodmat = intrlink.codliniecomanda
                  inner join intrari1 i1           on intrlink.codintr1 = i1.codintr1
             )
            ';
--AA: select-ul nu e complet si nu functioneaza
  sSelect :=
  'SELECT
         objmat.DENUMIRE,
         um.den_um,
         mat.pret,
         mat.cant,
         predari.cant,
         coalesce(mat.cant, 0) - coalesce(consumuri.cant, 0),
         sum(round(coalesce(mat.cant, 0) * coalesce(mat.pret, 0), 2)),
         sum(round(coalesce(consumuri.cant, 0) * coalesce(mat.pret, 0), 2)),
         sum(round(mat.cant * mat.pret, 2) - round(consumuri.cant * mat.pret, 2)),
         BC.NrDoc,
         BC.DataDoc,
         NG.Den_gest,
         ObjRet.denumire,
         umret.den_um,
         realizari.cant,
         realizari.val,
         realizari.pret ' || gUserAlias || '
  FROM   intrari intr
        INNER JOIN intrari1 intr1         ON intr.codintr      = intr1.codintr
        INNER JOIN intrprodlink intrlink   ON c1.codcomanda     = c.codcomanda
        LEFT  JOIN cmdprodmat mat         ON c.carnetdoc       = cdoc.codcarnet
        INNER JOIN ngest            g     ON c.codgest         = g.codgest
        INNER JOIN NARTOBJ     OBJmat     ON mat.codobiect     = objmat.codobiect ' || sCondgest || '
        INNER JOIN NART        ArtMat     ON objmat.codarticol = artmat.codarticol
        INNER JOIN NUM             UM     ON artmat.um         = um.codum
        INNER JOIN NARTOBJ     ObjRet     ON c1.codobiect      = objret.codobiect
        INNER JOIN NART        ArtRet     ON objret.codarticol = artret.codarticol
        INNER JOIN NUM          UMret     ON artret.um         = umret.codum
        LEFT  JOIN realizari               on mat.codcmdprodmat = realizari.codcmdprodmat
        LEFT  JOIN consumuri               on mat.codcmdprodmat = consumuri.codcmdprodmat' || gSuplJoins || '
  WHERE mat.tip = 1 and c.tipdoc = 53 and INTR.datadoc between to_date(''' || coalesce(current_setting('PKG_LIST_BASE_URMREALDEZ.vDataStart', true),'') || ''', ''DD.MM.YYYY'') and to_date(''' || coalesce(current_setting('PKG_LIST_BASE_URMREALDEZ.vDataFin', true),'') || ''', ''DD.MM.YYYY'') ';

  IF  getSUBUNITATE() &gt; 1 THEN
    sSelect := sSelect || ' and INTR.subunitatea = ' || coalesce(getSUBUNITATE()::varchar,'');
  END IF;

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmvirinterne_processlist</obj_name>
  <obj_hashval>13511b625f893578d319f567691875a0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmvirinterne_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sSelect     varchar;
  sCursRef    varchar;
  aSitV       numeric;
  aBancaV     numeric;
  aMonedaV    numeric;
  gSuplCols   varchar := 'TREZOR1 T1, TREZOR T, NBANKCONT NBC, NBANK NB, NMONEDE MON, NSUBUNIT SUB, TREZOR1 T1_B, TREZOR T_B, NBANKCONT NBC_B, NBANK NB_B, NMONEDE MON_B, NSUBUNIT SUB_B, NCONT CVIR ';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  v_LunaStart numeric;
  v_LunaStop  numeric;
  wmeRes      boolean;
BEGIN
  --Stef - 02.06.2025 - corectie
  --Florin - 14.04.2021 - sincronizat Oracle (40191)
  --Adina 19.02.2021 - GetInfoSitValuta
  --Florin 01.09.2020
  v_LunaStart = getanlucru() * 12 + coalesce(current_setting('PKG_LIST_SELECTLUNA.vLunaStart', true)::numeric, 0);
  v_LunaStop  = getanlucru() * 12 + coalesce(current_setting('PKG_LIST_SELECTLUNA.vLunaFin'  , true)::numeric, 0);
  call pkg_list_struct_startsuplcols();

  call pkg_list_struct_addsupltabs(gSuplCols, '', '', '', NULL);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config('PKG_LIST_BASE_NOMPART.gSuplCols', gSuplCols, false);

  SELECT pkg_list_base_utils_GetInfoSitValuta.wme_result, psitvaluta, pbancavaluta, pmonedavaluta
  INTO wmeRes, aSitV, aBancaV, aMonedaV
  FROM pkg_list_base_utils_GetInfoSitValuta(NULL, aSitV, aBancaV, aMonedaV);

  IF wmeRes   --(SELECT FNC_GetInfoSitValuta.wme_result FROM FNC_GetInfoSitValuta())
  THEN
    --SELECT FNC_GetInfoSitValuta.pBancaValuta, FNC_GetInfoSitValuta.pMonedaValuta INTO aBancaV, aMonedaV FROM FNC_GetInfoSitValuta();
    sCursRef := ', (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.wme_result FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL,' || coalesce(aMonedaV, 0) || ',' || coalesce(aBancaV, 0) || ',to_char(t1.datadoc, ''dd.mm.yyyy'')))';
  ELSE
    sCursRef := ', 1';
  END IF;
  sInsert := 'INSERT INTO ' || tmpName || '(
    NAV_CodDoc,NAV_CodDoc1,NAV_TipDoc,
    SimbOp, DenOp, DenContOp, NrContOp,
    TipTranz,
    Document_URMV, TipDoc, NrDoc, Data_URMV,
    Moneda, Curs, Valoare, Subunitatea,
    Luna,
    Rest,
    SimbBenef, DenBenef, NrContBenef, DenContBenef,
    B_Document, B_TipDoc, B_NrDoc, B_Data,
    B_Moneda, B_Curs, B_Valoare, B_Subunitatea,
    B_Luna,
    CONTVIR,
    CURS_REF ' || gUserFields || ')';
  sSelect := ' SELECT
        (Case  When T1.INITIALIZARI = 1 then NULL else T.CODTREZOR end), (Case  When T1.INITIALIZARI = 1 then NULL else T1.CODTREZOR1 end),
        (Case  When T1.INITIALIZARI = 1 then NULL else G.TIPDOC end),
        NB.SIMBOL, NB.DENUMIRE, NBC.DEN_CONT, NBC.NRCONT,
        (Case When O.SEMNIFICATIE = 800 then ''PLATA'' else ''INCASARE'' end) TIPTRANZ,
        T1.DOC||T1.NRDOC||''/''||to_char(T1.DATADOC, ''dd.mm.yyyy'') Doc, T1.DOC TipDoc, T1.NRDOC, T1.DATADOC,
        MON.SIMBOL MONEDA, (Case  When T1.CURS IS NULL then 1 When T1.CURS = 0 then 1 else T1.CURS end) CURS, T1.VALDOC, SUB.DEN_SUBUNIT,
        to_char(T1.An,''fm0000'')||''.''||to_char(T1.LUNA,''fm00'')||''.''|| pkg_list_base_utils_decode_luna(T1.LUNA),
        (O.VALOARE - CASE WHEN T1_B.CODTREZOR1 IS NULL THEN 0 ELSE S.VALOARE END) * (Case  When O.SEMNIFICATIE = 801 then 1 else -1 end) REST,
        NB_B.SIMBOL, NB_B.DENUMIRE, NBC_B.NRCONT, NBC_B.DEN_CONT,
        (Case  When T1_B.CODTREZOR1 IS NULL then NULL else T1_B.DOC || T1_B.NRDOC || ''/'' || to_char(T1_B.DATADOC, ''dd.mm.yyyy'') end) Doc, T1_B.DOC TipDoc, T1_B.NRDOC, T1_B.DATADOC,
        MON_B.SIMBOL MONEDA, (Case When T1_B.CURS is NULL then 1 When T1_B.CURS = 0 then 1 else T1_B.CURS end) CURS, T1_B.VALDOC, SUB_B.DEN_SUBUNIT,
        (Case  When T1_B.CODTREZOR1 IS NULL then NULL else to_char(T1_B.An,''fm0000'')||''.''||to_char(T1_B.LUNA,''fm00'')||''.''||pkg_list_base_utils_decode_luna(T1_B.LUNA) end),
        CVIR.SIMBOL' || coalesce(sCursRef,'') || gUserAlias || '
    FROM  OBLIGPIF O
          INNER JOIN GENERAL   G     ON O.CODGENERAL      = G.CODGENERAL AND G.TIPDOC IN (29,30)
          INNER JOIN TREZOR1   T1    ON T1.CODTREZOR1     = G.CODDOC
          INNER JOIN TREZOR    T     ON T.CODTREZOR       = T1.CODTREZOR
          LEFT  JOIN NBANKCONT NBC   ON NBC.CODBANKCONT   = T.CODBANCA
          LEFT  JOIN NBANK     NB    ON NB.CODBANK        = NBC.CODBANK
          LEFT  JOIN NMONEDE   MON   ON MON.CODMONEDA     = NBC.CODMONEDA
          LEFT  JOIN NSUBUNIT  SUB   ON SUB.CODSUBUNIT    = T.SUBUNITATEA
          LEFT  JOIN STINGERE  S     ON S.CODSTINSPIF     = O.CODOBLIGPIF
          LEFT  JOIN OBLIGPIF  O_B   ON O_B.CODOBLIGPIF   = S.CODSTINGATORPIF
          LEFT  JOIN GENERAL   G_B   ON G_B.CODGENERAL    = O_B.CODGENERAL
          LEFT  JOIN TREZOR1   T1_B  ON T1_B.CODTREZOR1   = G_B.CODDOC AND G_B.TIPDOC IN (29,30) AND (T1_B.AN * 12 + T1_B.LUNA) &lt;= ' || v_LunaStop || '
          LEFT  JOIN TREZOR    T_B   ON T_B.CODTREZOR     = T1_B.CODTREZOR
          LEFT  JOIN NBANKCONT NBC_B ON NBC_B.CODBANKCONT = T1.CODPART
          LEFT  JOIN NBANK     NB_B  ON NB_B.CODBANK      = NBC_B.CODBANK
          LEFT  JOIN NMONEDE   MON_B ON MON_B.CODMONEDA   = NBC_B.CODMONEDA
          LEFT  JOIN NSUBUNIT  SUB_B ON SUB_B.CODSUBUNIT  = T_B.SUBUNITATEA
          LEFT  JOIN NCONT     CVIR  ON CVIR.CODCONT = coalesce(fnc_GetValConstanta(''CViramenteInterne'' , T1.AN, T1.LUNA)::numeric, 0)' || gSuplJoins || '
    WHERE O.SEMNIFICATIE IN (800,801)
          AND O.CONTBANKTRANZACTIE IS NOT NULL ' || coalesce((select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'T',NULL,NULL,NULL))::varchar,'')
     || 'AND (T1.AN * 12 + T1.LUNA) &gt;= '||v_LunaStart|| ' AND (T1.AN * 12 + T1.LUNA) &lt;= ' || v_LunaStop || '
          AND ((O.VALOARE - coalesce(S.VALOARE,0)) &lt;&gt; 0 OR (T1.AN * 12 + T1.LUNA) &gt;= ' || v_LunaStart
     || ' OR coalesce(T1_B.AN * 12 + T1_B.LUNA,0) &gt;= ' || v_LunaStart || ')';
--  insert into x(view_name, test) values ('urm', sselect);
   PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_decode_tipdoc</obj_name>
  <obj_hashval>a5ea8f495225f37d053799bc4d2351a2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_decode_tipdoc(vtip numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult varchar;
BEGIN
  --Adina 04 septembrie 2020
  --Bogdan 08.01.2020
  BEGIN
    SELECT NUMEEXT into strict sResult FROM tmp_machete   WHERE vTip = CodMacheta;
  EXCEPTION WHEN others THEN
    sResult := '-';
  END;

  RETURN sResult;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_get_codcontt</obj_name>
  <obj_hashval>300696530a7629cba97e81569261cef3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_get_codcontt(INOUT wme_result numeric, INOUT v_codcont numeric, INOUT v_an numeric, INOUT v_luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
v_cod numeric;
begin
  --Florin 13.02.2022 - sinc. Oracle (29.12.2021)
  --Bogdan 31.07.2020
  BEGIN
    SELECT Coalesce(c1.conttertiar,0) INTO v_cod
    FROM ncont1 c1
    WHERE c1.codcont = v_codcont AND v_an*12+v_luna BETWEEN c1.ALSTART AND c1.ALSTOP;
  EXCEPTION WHEN OTHERS THEN
    v_cod := 0;
  END;
  WME_Result :=  v_cod;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_get_umsec</obj_name>
  <obj_hashval>9d718bf41662f61624d5e47c7cc813ed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_get_umsec(INOUT wme_result character varying, INOUT v_codum numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_den varchar;
begin
  SELECT Coalesce( den_um1, 'nedef.') INTO v_den FROM num1 WHERE v_codum = codum1;
  WME_Result :=  v_den;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getcodartcli</obj_name>
  <obj_hashval>c32359668b1a31e998a24c16031ce645</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getcodartcli(pcodobiect numeric, pcodpart numeric, pcodclasep numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vRes numeric;
BEGIN
  --Stef 03.08.2022
  vRes := 0;
  vRes := 0;
  IF  Coalesce( pCodObiect, 0) &lt;&gt; 0 AND  Coalesce( pCodPart, 0) &lt;&gt; 0 THEN
    SELECT Coalesce( Min( CodArtCli), 0) INTO vRes FROM nartcli WHERE codobiect = pCodObiect AND codpart = pCodPart;
  END IF;

  IF  Coalesce( pCodObiect, 0) &lt;&gt; 0 AND  Coalesce( pCodClaseP, 0) &lt;&gt; 0 AND  vRes = 0 THEN
    SELECT Coalesce( Min( CodArtCli), 0) INTO vRes FROM nartcli WHERE codobiect = pCodObiect AND codclasep = pCodClaseP;
  END IF;

  RETURN vRes;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getsimbolcont</obj_name>
  <obj_hashval>2a95c355183185a298b02bf73741af6f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getsimbolcont(INOUT wme_result character varying, INOUT vcodcont numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vSIMBOL varchar;
begin
  BEGIN
    SELECT Coalesce( SIMBOL, 'nedef.') INTO vSIMBOL FROM NCONT WHERE CODCONT = vCODCONT;
  EXCEPTION WHEN no_data_found THEN
    vSimbol := 'nedef.';
  END;
  WME_Result :=  vSIMBOL;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvpj5tva</obj_name>
  <obj_hashval>4e7682a1b73bfbc15a066c76e8285f59</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvpj5tva(avpj5tva numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vPj5TVA',to_char(avPj5TVA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvpuma1</obj_name>
  <obj_hashval>c3a95025ffb4a3c884f64cb4b1489146</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvpuma1(avpuma1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vPUMA1',avPUMA1::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_umple_tmp_medex1_lst</obj_name>
  <obj_hashval>fcab3b21e032c387804f1deabe3119b7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_umple_tmp_medex1_lst()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Florin 20.10.2025 - fixat 67022
  DELETE FROM TMP_MEDEX1_LST;
  BEGIN
    EXECUTE 'CREATE INDEX idx_tmp_medex1_lst ON TMP_MEDEX1_LST (codcim)';
  EXCEPTION WHEN OTHERS THEN
    NULL;
  END;

  INSERT INTO TMP_MEDEX1_LST
  SELECT CODMEDEX1, CODMEDEX, CODCIM, DENUMIRE, PREZENTARE, NARCOTIC, FRACTIONAL, SPECIAL, AREBIOECHIVALENT, CANT, PRETAM, PRETRID, PRESCRIERE, VALIDDELA, VALIDPANALA, DCI, CONC, FORMAFARM, PRODUCATOR, TARA, GRUPA
  FROM (SELECT CODMEDEX1, CODMEDEX, CODCIM, DENUMIRE, PREZENTARE, NARCOTIC, FRACTIONAL, SPECIAL, AREBIOECHIVALENT, CANT, PRETAM, PRETRID, PRESCRIERE, VALIDDELA, VALIDPANALA, DCI, CONC, FORMAFARM, PRODUCATOR, TARA, GRUPA, Row_Number() OVER (PARTITION BY CODCIM ORDER BY CODMEDEX1 DESC) XNR
        FROM MEDEX1
       ) A_PG
  WHERE XNR = 1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_verif_imp_intr_setjoinuri</obj_name>
  <obj_hashval>701018eaf861c9a19effe350dee94f26</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_verif_imp_intr_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 16.08.2024
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_VERIF_IMP_INTR.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_voucherdoc_setjoinuri</obj_name>
  <obj_hashval>a5f77f15ef8a9168f97ae8cec5fa74ed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_voucherdoc_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 05.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_voucherdoc.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_config_get_sid_header</obj_name>
  <obj_hashval>ea1c085f5808691529bd97c1a6ad3b8d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_config_get_sid_header()
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
begin
  return '200';
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_config_getnvlclause</obj_name>
  <obj_hashval>12ce9ae007308b68431d52e434a8bf74</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_config_getnvlclause(INOUT tab character varying, INOUT scol character varying, INOUT snvl_header character varying, INOUT snvl_footer character varying, INOUT swhere character varying, INOUT stype character varying, INOUT desc_ boolean DEFAULT false)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sidnull varchar := '9999999999999999999';
begin
  --Stef 29.07.2020 -- adaugat AS pentru a gestiona corect cuvinte rezervate
  --Florin 18.02.2021 - adaugat time
  --Florin 03.03.2021 - adaugat bytea
  select (pkg_list_config_GET_COL_TYPE.wme_result) into sType from pkg_list_config_GET_COL_TYPE(null, sCol,tab);
  if strpos(sType, 'char') &lt;&gt; 0 then
    sNVL_header := 'Coalesce(' || sCol || ',CHR(1)::character varying ) AS ';
    sNVL_footer := 'Coalesce(' || sCol || ',CHR(255)::character varying ) AS ';
    if desc_   then sWhere := '= CHR(255)::character varying AND';  else sWhere := '= CHR(1)::character varying AND';  end if;
  elsif sType = 'numeric' or sType = 'integer' then
    sNVL_header := 'Coalesce(' || sCol || ',-'||sidnull||') AS ';
    sNVL_footer := 'Coalesce(' || sCol || ', '||sidnull||') AS ';
    if desc_ then sWhere := '= '||sidnull||' AND';  else sWhere := '=-'||sidnull||' AND';  end if;
  elsif sType = 'date' then
    sNVL_header :='Coalesce('||sCol||',TO_DATE(''1/1/1000'',''dd/mm/yyyy'')) AS ';
    sNVL_footer :='Coalesce('||sCol||',TO_DATE(''1/1/9999'',''dd/mm/yyyy'')) AS ';
    IF desc_
    THEN sWhere := '=TO_DATE(''1/1/9999'',''dd/mm/yyyy'') AND';
    ELSE sWhere := '=TO_DATE(''1/1/1000'',''dd/mm/yyyy'') AND';end if;
  elsif  strpos(sType, 'time') &lt;&gt; 0 then
    sNVL_header :='Coalesce('||sCol||',TO_DATE(''1/1/1000 00:00:00'',''dd/mm/yyyy hh24:mi:ss'')) AS ';
    sNVL_footer :='Coalesce('||sCol||',TO_DATE(''1/1/9999 00:00:00'',''dd/mm/yyyy hh24:mi:ss'')) AS ';
    IF desc_
    THEN sWhere := '=TO_DATE(''1/1/9999 00:00:00'',''dd/mm/yyyy hh24:mi:ss'') AND';
    ELSE sWhere := '=TO_DATE(''1/1/1000 00:00:00'',''dd/mm/yyyy hh24:mi:ss'') AND';end if;
  elsif  strpos(sType, 'bytea') &lt;&gt; 0 then
     sWhere := ' IS NULL AND';
     sNVL_header := sCol||' AS ';
    sNVL_footer := sCol||' AS ';
  ELSE
    sWhere := ' IS NULL AND';
  end if;
end;

$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectgest2_toategest</obj_name>
  <obj_hashval>96facb1301a92cc413901129f5efa887</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectgest2_toategest(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  --Adina iulie 2020
WME_Result :=  (current_setting('PKG_LIST_SELECTGEST2.vAllGest', true)::boolean);
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectioart_setparams</obj_name>
  <obj_hashval>fa106c5ae51a8828af6702c67afc6bd7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectioart_setparams(ptoateioart numeric, pextra numeric DEFAULT 0, pextra2 numeric DEFAULT 1)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 31.08.2022 - sinc. Oracle
  --Florin 10.09.2020
  PERFORM set_config('PKG_LIST_SELECTIOART.vToateIOArt', pToateIOArt::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTIOART.vExtra'     , pExtra     ::varchar, FALSE);
  PERFORM set_config('PKG_LIST_SELECTIOART.vExtra2'    , pExtra2    ::varchar, FALSE);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscad_extra1</obj_name>
  <obj_hashval>81dad915d41c4492043bda86a5c2179d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscad_extra1(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_LIST_SELECTSCAD.vExtra1', true)::boolean);
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_p_listid</obj_name>
  <obj_hashval>2113dd9f96f0548621f82ab8cfc56f18</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_p_listid(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_LIST_SELFISAMAG.p_ListID',true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_p_rezum1</obj_name>
  <obj_hashval>35beaed5995698a4fc5724a75b5c729d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_p_rezum1(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_SELFISAMAG.p_RezUM1',true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selpartart_isextra1</obj_name>
  <obj_hashval>ca476163b6474a2051b2930a970bda39</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selpartart_isextra1()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 08.09.2020
  return current_setting ('PKG_LIST_SELPARTART.gExtra1', true)::numeric = 1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selpartart_isextra2</obj_name>
  <obj_hashval>50d40984a9e36efa14cfc147f8a0f603</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selpartart_isextra2()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 0809.2020
  return current_setting ('PKG_LIST_SELPARTART.gExtra2', true)::numeric = 1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selperagent_datafin</obj_name>
  <obj_hashval>f05db72a182dac9255eb904b34109e63</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selperagent_datafin()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.09.2020
  return to_date(current_setting ('PKG_LIST_SELPERAGENT.vDataFin', true),'dd.mm.yyyy');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_getcreatetemp</obj_name>
  <obj_hashval>bf8ed8df6c0a82e67cdd6a1b3343ad2d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_getcreatetemp(INOUT wme_result character varying, INOUT tmpname character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult varchar;
begin
  --Stef   24.03.2022 - CREATE TEMPORARY (scosGLOBAL fiindca e obsolete si apare/incurca in loguri de BD)
  sResult    := 'CREATE TEMPORARY TABLE ' || TMPNAME || ' ON COMMIT PRESERVE ROWS UNRECOVERABLE AS ';
  WME_Result :=  sResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_utilfisacont_get_infobaza</obj_name>
  <obj_hashval>ac98bd188195129407b78fe3e8b345b5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_utilfisacont_get_infobaza(ptipbaza numeric, pcodbaza numeric, pindexlocal numeric, pan numeric, pluna numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
declare
  vResult varchar;

begin
  -- BogdanL 27.07.2020
  if pTipBaza = current_setting('PKG_LIST_UTILFISACONT.TBJCONST', true)::numeric then vResult := (
    SELECT PKG_CATEGCONST_GETVALCONSTBYCODE.WME_RESULT FROM PKG_CATEGCONST_GETVALCONSTBYCODE(null, pCodBaza, pAn, pLuna)
  );

  elsif pTipBaza = current_setting('PKG_LIST_UTILFISACONT.TBJART', true)::numeric then
    SELECT denumire INTO vResult FROM nartobj WHERE codobiect = pCodBaza;
  end if;

  return vResult;
end;

$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_medex_sp_lockrecord</obj_name>
  <obj_hashval>afd06012988d8c45694e26465f4e7c6a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_medex_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodMedex INTO Tmp FROM MEDEX WHERE CodMedex = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mfclasif_sp_gotorecord</obj_name>
  <obj_hashval>ce1592dcef7a877bb14dfdb48b07d46d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mfclasif_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_MFCLASIF
  SELECT * FROM MFCLASIF WHERE CODCLASIF = RECID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mifix_updateresponsabil</obj_name>
  <obj_hashval>3bac8d82d7bf234afe133246cd2726f3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mifix_updateresponsabil(codpers numeric, codmifix numeric, an numeric, luna numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sSQL        varchar;
  BEGIN
    sSQL := 'update mifix1 set codpers = ' || codPers::varchar || ' where codmifix = '|| codMifix::varchar || ' and anstart * 12 + lunastart &gt;= ' || (an * 12 + luna)::varchar;
   EXECUTE sSQL;
  END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_carnetdoc_i</obj_name>
  <obj_hashval>9d00718607432e7021ce049af157d8b7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_carnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_MISCARI_INTERNE.CARNETDOC_I', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_motive_sp_insertrecord</obj_name>
  <obj_hashval>13aa420c74f8488afb6a66d7e829872a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_motive_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_MOTIVE (CodMOTIV, Tip) VALUES(0, 0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nimob_sp_postrecords</obj_name>
  <obj_hashval>d48133ca6b7fa761eed166cd7fcb88f1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nimob_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    UPDATE NIMOB
    SET
    (codnimob, denumire, datastart, datastop) = (SELECT codnimob, denumire, datastart, datastop FROM TMP_NIMOB)
    WHERE
     codnimob = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_NIMOB_CODNIMOB') INTO RecId;

    INSERT INTO NIMOB(codnimob, denumire, datastart, datastop)
    SELECT RecId, denumire, datastart, datastop FROM TMP_NIMOB;
  END IF;

  PERFORM NotifyModif( Operation, RecId, 'NIMOB');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_analiza_implicit</obj_name>
  <obj_hashval>3b6060075e78a62f044f4e927f89b856</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_analiza_implicit(INOUT wme_result numeric, INOUT implicitsursa numeric, INOUT doarcategsursa numeric, INOUT codcatsursa numeric, INOUT codcatdestimplicita numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  DoarCategSursa = 0 THEN
    WME_Result :=  IMPLICITSURSA;
    RETURN;
  ELSE
    IF  CODCATDESTIMPLICITA = 0 THEN
      WME_Result :=  IMPLICITSURSA;
      RETURN;
    ELSE
      IF  CODCATSURSA = CODCATDESTIMPLICITA THEN
        WME_Result :=  1;
        RETURN;
      ELSE
        WME_Result :=  0;
        RETURN;
      END IF;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_gcodobiect</obj_name>
  <obj_hashval>214753d33cfe5f59930739cb06539eb2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_gcodobiect(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOM_ARTICOL.gCodObiect')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_get_next_codobiect1</obj_name>
  <obj_hashval>731bd4fe01a3e6922db46758822b7e96</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_get_next_codobiect1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
NextValue numeric;
begin
SELECT NEXTVAL('SEQ_NARTOBJ1_CODOBIECT1')
INTO NextValue;
WME_Result :=  NextValue;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_sp_postrecords</obj_name>
  <obj_hashval>4870872f5dc1838e4c3d89619e1bccbd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  V_REC               RECORD;
  V_REC_PRETM         RECORD;
  V_OBJ               RECORD;
  V_LANG              RECORD;
  VREC                RECORD;
  V_COM               RECORD;
  V_CMD               RECORD;
  v_sub               RECORD;
  vCod                numeric;
  aCODOBIECT          numeric;
  aINDEXLOCAL         numeric;
  aDENARTICOL         varchar          := '';
  aPARITATE           double precision := 1;
  aNr                 numeric;
  aCODPRETM           numeric;
  aCODAMB             numeric;
  aCODOPT             numeric;
  aDenTrad            varchar;
  aDoc                varchar;
  CaractObiectGENERIC varchar;
  ATRIBUTE            numeric := 0;
  CODOBIECTGENERIC    numeric := 0;
  aRelatieUM1         numeric;
  aD1                 double precision;
  aD2                 double precision;
  aD3                 double precision;
  aParD1              double precision;
  aParD2              double precision;
  aParD3              double precision;
  Tmp                 numeric;
  aMemo               varchar(10);
  aCheck              varchar(10);
  aCount              NUMERIC(10);
  aCodCatPret         NUMERIC(20);
  sSQL                TEXT;
BEGIN
  --Florin 04.12.2025 - sinc. Oracle
  --Stef 10.12.2024
  perform pkg_nom_articol_setct_monitor('MON_6');
  BEGIN
    SELECT fnc_getvalconstantalucru('MemoModiPret') INTO aMemo;
    EXCEPTION WHEN OTHERS THEN aMemo := '0';
  END;
  BEGIN
    SELECT fnc_getvalconstantalucru('SyncPretRetail') INTO aCheck;
    EXCEPTION WHEN OTHERS THEN aCheck := '0';
  END;
  BEGIN
    SELECT fnc_getvalconstantalucru('CatPretArt') INTO aCodCatPret;
    EXCEPTION WHEN OTHERS THEN aMemo := '0';
  END;

  BEGIN
    SELECT DEN_ARTICOL, COALESCE (RelatieUM1, 0) , D1, D2, D3, ParitateD1, ParitateD2, ParitateD3
    INTO  aDENARTICOL, aRelatieUM1, aD1, aD2, aD3, aParD1, aParD2, aParD3
    FROM TMP_NART;
  EXCEPTION
  WHEN OTHERS THEN
    aDENARTICOL := '';
  END;
  aDoc := coalesce ('Articol "' || coalesce (aDENARTICOL,'') ,'') || '"';
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT (501);

  IF OPERATION = 0 then

    IF (SELECT WME_RESULT FROM winmadmin.PKG_USERFIRME_ValidPostLog(NULL, current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_NOM_ARTICOL.CT_MONITOR', true)))
    THEN
      PERFORM winmadmin.pkg_userfirme_postlogcucommit( 'NART', current_setting('PKG_GLOBALS.USERNAME', true), 'M', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), TO_NUMBER(current_setting('PKG_GLOBALS.SUBUNITATE', true),'999999999999999999'), null, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;
    SELECT CodArticol INTO RecId FROM TMP_NART;

    UPDATE NART
    SET
      (
        Den_Articol,
        UM,
        Clasa,
        TipSerie,
        TipArticol,
        AreTG,
        ContImplicit,
        GestImplicita,
        Certificat,
        EvolutiePret,
        UM1,
        UM2,
        ContServiciu,
        INCREMENTSERIE,
        RELATIEUM1,
        RELATIEUM2,
        CASADEMARCAT,
        CODCENTRU,
        D1,
        D2,
        D3,
        ParitateD1,
        ParitateD2,
        ParitateD3,
        CLASASTATIST,
        COMENZIONLINE,
        CODEXTERNART,
        SUFIXCODEXTERN,
        RESTNEGLIJCMD,
        NRZILESTOCMEDIU,
        MUSAICALITATE,
        Culoare,
        DCI,
        ClasaW, CHECKISAUTENTIC, PROCPerisab, codmasca, constructienoua, riscfiscal,  TIPSTOC)
      = (SELECT Den_Articol,
          UM,
          Clasa,
          TipSerie,
          TipArticol,
          AreTG,
          ContImplicit,
          GestImplicita,
          Certificat,
          EvolutiePret,
          UM1,
          UM2,
          ContServiciu,
          INCREMENTSERIE,
          RELATIEUM1,
          RELATIEUM2,
          CASADEMARCAT,
          CODCENTRU,
          D1,
          D2,
          D3,
          ParitateD1,
          ParitateD2,
          ParitateD3,
          CLASASTATIST,
          COMENZIONLINE,
          CODEXTERNART,
          SUFIXCODEXTERN,
          RESTNEGLIJCMD,
          NRZILESTOCMEDIU,
          MUSAICALITATE,
          Culoare,
          DCI,
          ClasaW, CHECKISAUTENTIC, PROCPerisab, codmasca, constructienoua, riscfiscal,  TIPSTOC
        FROM TMP_NART)
    WHERE
      CodArticol = RecId;

    DELETE FROM NART1 A1
    WHERE
      CodArticol = RecId
      and NOT EXISTS (SELECT CodArticol1 FROM TMP_NART1 WHERE CODARTICOL1 = A1.CODARTICOL1);

    INSERT INTO NART1 ( CodArticol1,CodArticol,CodTVA,CodAccize,TaxCode, codtaxa1,CodTaxa2,anstart,lunastart,CodAccizeDVI )
    SELECT  Nextval('seq_NART1_CodArticol1'), RecId ,CodTVA,CodAccize,TaxCode, codtaxa1,CodTaxa2,anstart,lunastart,CodAccizeDVI
        FROM TMP_NART1 WHERE CodArticol1 &lt; 0;
    FOR v_rec IN (SELECT * FROM TMP_NART1 WHERE COALESCE (CodArticol1, -1) &gt; 0 ORDER BY CodArticol1) LOOP
      UPDATE NART1
      SET
        CodTVA       = v_rec.CodTVA,
        CodAccize    = v_rec.CodAccize,
        CodAccizeDVI = v_rec.CodAccizeDVI,
        TaxCode      = v_rec.TaxCode,
        CodTaxa1     = v_rec.CodTaxa1,
        CodTaxa2     = v_rec.CodTaxa2
      WHERE
        CodArticol1 = v_rec.CodArticol1;
    END LOOP;

    DELETE FROM NARTIMPLICITE AI
    WHERE
      CodArticol = RecId
      AND NOT EXISTS (SELECT CODIMPLICIT FROM TMP_NARTIMPLICITE WHERE CODIMPLICIT = AI.CODIMPLICIT);

    INSERT INTO NARTIMPLICITE (CODIMPLICIT,
        CODARTICOL,
        CODSUBUNIT,
        CONTIMPLICIT,
        GESTIMPLICITA,
        LOCATIEIMPLICITA,
        NEVANDABIL)
    SELECT NEXTVAL ('SEQ_NARTIMPLICITE_CODIMPLICIT') ,
      RecId,
      CODSUBUNIT,
      CONTIMPLICIT,
      GESTIMPLICITA,
      LOCATIEIMPLICITA,
      NEVANDABIL
    FROM TMP_NARTIMPLICITE
    WHERE
      CODIMPLICIT &lt; 0;

    FOR v_rec IN (SELECT * FROM TMP_NARTIMPLICITE WHERE COALESCE (CODIMPLICIT, -1) &gt; 0) LOOP
      UPDATE NARTIMPLICITE
      SET
        CODSUBUNIT       = v_rec.CODSUBUNIT,
        GESTIMPLICITA    = v_rec.GESTIMPLICITA,
        CONTIMPLICIT     = v_rec.CONTIMPLICIT,
        LOCATIEIMPLICITA = v_rec.LOCATIEIMPLICITA,
        NEVANDABIL       = v_rec.NEVANDABIL
      WHERE
        CODIMPLICIT = v_rec.CODIMPLICIT;
    END LOOP;

    FOR V_REC IN (SELECT * FROM NARTOBJ O WHERE CODARTICOL = RECID AND NOT EXISTS (SELECT CODOBIECT FROM TMP_NARTOBJ WHERE CODOBIECT = O.CODOBIECT))
    LOOP
      DELETE FROM NATROBJ WHERE CODOBIECT = V_REC.CODOBIECT;
      DELETE FROM NARTOBJSUBUNIT WHERE CODOBIECT = V_REC.CODOBIECT;

      FOR V_REC_PRETM IN (SELECT * FROM PRETM WHERE CODOBIECT = V_REC.CODOBIECT) LOOP
        DELETE FROM PRETMAMB WHERE CODPRETM = V_REC_PRETM.CODPRETM;
        DELETE FROM PRETM    WHERE CODPRETM = V_REC_PRETM.CODPRETM;
      END LOOP;

      DELETE FROM NARTCLI  WHERE CODOBIECT = V_REC.CODOBIECT;
      DELETE FROM NARTOBJ1 WHERE CODOBIECT = V_REC.CODOBIECT;

      DELETE FROM NARTOBJTRAD WHERE CodObiect = V_REC.CodObiect;

      DELETE FROM DISCPROMORETAIL WHERE CodObiect = V_REC.CodObiect;

      DELETE FROM NARTOBJIMP   WHERE CODOBIECT = V_REC.CODOBIECT;
      DELETE FROM NECHIV       WHERE CODOBIECT = V_REC.CODOBIECT;
      DELETE FROM NARTAMB      WHERE CODOBIECT = V_REC.CODOBIECT OR CODOBIECTRETURN = V_REC.CODOBIECT;
      DELETE FROM NARTOPT      WHERE CODOBIECT = V_REC.CODOBIECT OR codobiectopt = V_REC.CODOBIECT;
      DELETE FROM NARTOBJCOLET WHERE CODOBIECT = V_REC.CODOBIECT;
      DELETE FROM CODEXTALT    WHERE CODOBIECT = V_REC.CODOBIECT;
      DELETE FROM CODINTALT    WHERE CODOBIECT = V_REC.CODOBIECT;

      DELETE FROM DISCART DA
      WHERE
        (SELECT CR.PECLASE
          FROM CRITERIIDISC CR,
               DISCOUNT     DI
          WHERE DI.CODDISCOUNT = DA.CODDISCOUNT AND CR.CODCRITERIU = DI.CODCRITERIU
        )
        = 1
        AND CODOBIECT = V_REC.CODOBIECT;

      BEGIN --TABELA DINAMICA PT. LISTE CU VALORILE ANUMITOR ATRIBUTE
        EXECUTE 'DELETE FROM NARTOBJATR WHERE CODOBIECT = '||V_REC.CODOBIECT;
      EXCEPTION
        WHEN OTHERS THEN NULL; -- PROBABIL NU EXISTA TABELA
      END;

      DELETE FROM NARTOBJ WHERE CODOBIECT = V_REC.CODOBIECT;
    END LOOP;

    FOR v_rec IN (SELECT * FROM TMP_NARTOBJ WHERE COALESCE (CodObiect, -1) &lt; 0 ORDER BY CodObiect) LOOP
      SELECT NEXTVAL ('SEQ_NARTOBJ_CODOBIECT') INTO vCod;

      UPDATE TMP_NARTOBJ1 SET CODOBIECT = vCod WHERE CodOBIECT = v_Rec.CodObiect;
      UPDATE TMP_NARTDIM   SET CodObiect = vCod WHERE COALESCE (CodObiect, 0) = COALESCE (v_rec.CodObiect, 0);

      UPDATE TMP_NARTOBJTRAD SET CodObiect = vCod WHERE CodObiect = v_Rec.CodObiect;

      UPDATE TMP_DISCPROMORETAIL SET CodObiect = vCod WHERE CodObiect = v_Rec.CodObiect;

      UPDATE TMP_NARTOBJIMP     SET CODOBIECT = vCod WHERE CodOBIECT = v_Rec.CodObiect;
      UPDATE TMP_NATROBJ        SET CODOBIECT = vCod WHERE CodOBIECT = v_Rec.CodObiect;

      UPDATE TMP_PRETM          SET CODOBIECT = vCod WHERE CodOBIECT = v_Rec.CodObiect;
      UPDATE TMP_NARTOBJIMP     SET CODOBIECT = vCod WHERE CodOBIECT = v_Rec.CodObiect;
      UPDATE TMP_DISCART        SET CODOBIECT = vCod WHERE CodOBIECT = v_Rec.CodObiect;
      UPDATE TMP_NARTCLI        SET CODOBIECT = vCod WHERE CodOBIECT = v_Rec.CodObiect;
      UPDATE TMP_NARTAMB        SET CODOBIECT = vCod WHERE CodOBIECT = v_Rec.CodObiect;
      UPDATE TMP_NARTOPT        SET CODOBIECT = vCod WHERE CodOBIECT = v_Rec.CodObiect;
      UPDATE TMP_NECHIV         SET CODOBIECT = vCod WHERE CodOBIECT = v_Rec.CodObiect;
      UPDATE TMP_NARTOBJSUBUNIT SET CODOBIECT = vCod WHERE CodOBIECT = v_Rec.CodObiect;

      UPDATE TMP_NARTOBJCOLET SET CODOBIECT = vCod WHERE CodOBIECT = v_Rec.CodObiect;

      UPDATE TMP_CODEXTALT SET CODOBIECT = vCod WHERE CodOBIECT = v_Rec.CodObiect;
      UPDATE TMP_CODINTALT SET CODOBIECT = vCod WHERE CodOBIECT = v_Rec.CodObiect;

       INSERT INTO NARTOBJ (
        CodObiect, CodArticol,CodExtern,CodIntern, StocMin,StocMed, INACTIVCMDONLINE, AUTORIZATIE,EXPIRAREAUTORIZ, TRADUCARTGENERIC, MESAJINACTIV, StocMax,
        Masa,Volum,CodProducator,CodVamal,Returnabil,LuniGarantie,Obs,TARAORIGINE,
        ZILEVALABIL, ZILEDISTRIB, CODPERISABIL,ProcAdaosNir,Rotunjire, UMAmbalare, PRETMINIM,
        TERMENPLATA, DATAADAUGARII, CODPLU, USESTOCMED, NEFACTURABIL, GREUTSPECIFICA, BLOCAT,
        DURMAXAPROV, CODCNAS, CODCARACT, CODD394, INACTIV, FARACMDFURN, FARANIVELAPROB, DESCARCAREINTEGRALA, FARASTOC, CODCATEGARTTI,
        AdaosExceptie, Promotie, DiscPromo, ROTVALUTA, PRODUSPROPRIU,
        DENUMIRE,
        COEFCNAS, RAPCNAS, ANTIBIOTIC, EXPORTEMCS, CODNC, CODCPV, EXCLUSLISTARECM, CODACCIZABIL,
        LANSIMP,
        EXPORTKLG, CODANALIZANOD, SAFT_EXPORT, CANTVANZ, CERTIF_DDS )
      VALUES (
        vCod, v_Rec.CodArticol, v_Rec.CodExtern, v_Rec.CodIntern, v_Rec.StocMin, v_Rec.StocMed, V_REC.INACTIVCMDONLINE, v_rec.AUTORIZATIE,v_rec.EXPIRAREAUTORIZ,V_REC.TRADUCARTGENERIC, V_REC.MESAJINACTIV, v_Rec.StocMax,
        v_Rec.Masa, v_Rec.Volum, v_Rec.CodProducator, v_Rec.CodVamal, v_Rec.Returnabil, v_Rec.LuniGarantie, v_Rec.Obs, v_Rec.TARAORIGINE,
        v_rec.ZILEVALABIL, v_rec.ZILEDISTRIB,  V_REC.CODPERISABIL, v_Rec.ProcAdaosNir, v_Rec.Rotunjire, V_REC.UMAmbalare, V_REC.PRETMINIM,
        V_REC.TERMENPLATA, V_REC.DATAADAUGARII, V_REC.CODPLU, V_REC.USESTOCMED, v_rec.NEFACTURABIL, v_rec.GREUTSPECIFICA, V_REC.BLOCAT,
        V_REC.DURMAXAPROV, V_REC.CODCNAS, V_REC.CODCARACT, v_rec.CODD394, V_REC.INACTIV, V_REC.FARACMDFURN, V_REC.FARANIVELAPROB,  V_REC.DESCARCAREINTEGRALA, V_REC.FARASTOC, V_REC.CODCATEGARTTI,
        v_Rec.AdaosExceptie, v_Rec.Promotie, v_rec.discpromo, V_REC.ROTVALUTA, v_rec.PRODUSPROPRIU,
        CASE
          WHEN (SELECT COUNT(*) FROM TMP_NATROBJ WHERE CODOBIECT = VCOD) &gt; 0 THEN aDENARTICOL || ' ' || V_REC.DENOBIECT
          ELSE aDENARTICOL
        END,
        V_REC.COEFCNAS, V_REC.RAPCNAS, V_REC.ANTIBIOTIC, V_REC.EXPORTEMCS, V_REC.CODNC, V_REC.CODCPV, V_REC.EXCLUSLISTARECM, V_REC.CODACCIZABIL,
        CASE
           WHEN
             COALESCE(V_REC.PRODUSPROPRIU,0) = 0 THEN 0
            ELSE
              V_REC.LANSIMP
        END,
        V_REC.EXPORTKLG, V_REC.CODANALIZANOD, V_REC.SAFT_EXPORT, V_REC.CANTVANZ, V_REC.CERTIF_DDS
       );

--      IF fnc_tmpexists ('TMP_NARTOBJEXT') THEN
--        EXECUTE ' UPDATE TMP_NARTOBJEXT SET CODOBIECT = ' || VCOD::varchar || ' WHERE CODOBIECT = ' || V_REC.CODOBIECT::varchar;
--      END IF;
      PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('NARTOBJ', VCOD, V_REC.CODOBIECT);
      if aCheck = '1' then
        PERFORM pkg_nom_articol_CHECKMODIFPRETRETAIL (vCod);
      end if;
      if aMemo = '1' then
        PERFORM pkg_nom_articol_MEMOMODIPRET(vCod);
      end if;
    END LOOP;

    FOR v_rec IN ( SELECT * FROM TMP_NARTOBJ where CodObiect &gt; 0 ORDER BY CodObiect ) LOOP
      UPDATE NARTOBJ
      SET
        CodArticol          = RecId,
        CodExtern           = case when v_rec.CodExtern = '' then null else v_rec.CodExtern end,
        CodIntern           = case when v_rec.CodIntern = '' then null else v_rec.CodIntern end,
        StocMin             = v_rec.StocMin,
        StocMed             = v_rec.StocMed,
        INACTIVCMDONLINE    = V_REC.INACTIVCMDONLINE,
        AUTORIZATIE         = v_rec.AUTORIZATIE,
        EXPIRAREAUTORIZ     = v_rec.EXPIRAREAUTORIZ,
        TRADUCARTGENERIC    = V_REC.TRADUCARTGENERIC,
        MESAJINACTIV        = V_REC.MESAJINACTIV,
        StocMax             = v_rec.StocMax,
        Masa                = v_rec.Masa,
        Volum               = v_rec.Volum,
        CodProducator       = v_rec.CodProducator,
        CodVamal            = v_rec.CodVamal,
        Returnabil          = v_rec.Returnabil,
        LuniGarantie        = v_rec.LuniGarantie,
        Obs                 = v_rec.Obs,
        TARAORIGINE         = v_rec.TARAORIGINE,
        ZILEVALABIL         = v_rec.ZILEVALABIL,
        ZILEDISTRIB         = v_rec.ZILEDISTRIB,
        CODPERISABIL        = V_REC.CODPERISABIL,
        ProcAdaosNir        = v_rec.ProcAdaosNir,
        Rotunjire           = v_rec.Rotunjire,
        UMAmbalare          = v_rec.UMAmbalare,
        PRETMINIM           = V_REC.PRETMINIM,
        TERMENPLATA         = V_REC.TERMENPLATA,
        DATAADAUGARII       = V_REC.DATAADAUGARII,
        CODPLU              = V_REC.CODPLU,
        USESTOCMED          = V_REC.USESTOCMED,
        NEFACTURABIL        = v_rec.NEFACTURABIL,
        GREUTSPECIFICA      = v_rec.GREUTSPECIFICA,
        BLOCAT              = V_REC.BLOCAT,
        DURMAXAPROV         = V_REC.DURMAXAPROV,
        CODCNAS             = V_REC.CODCNAS,
        CODCARACT           = V_REC.CODCARACT,
        CODD394             = v_rec.CODD394,
        INACTIV             = V_REC.INACTIV,
        FARACMDFURN         = V_REC.FARACMDFURN,
        FARANIVELAPROB      = V_REC.FARANIVELAPROB,
        DESCARCAREINTEGRALA = V_REC.DESCARCAREINTEGRALA,
        FARASTOC            = V_REC.FARASTOC,
        CODCATEGARTTI       = V_REC.CODCATEGARTTI,
        ROTVALUTA           = v_rec.ROTVALUTA,
        PRODUSPROPRIU       = v_rec.PRODUSPROPRIU,
        DENUMIRE            =
        CASE
          WHEN (SELECT COUNT ( *) FROM TMP_NATROBJ WHERE CODOBIECT = V_REC.CODOBIECT) &gt; 0 THEN coalesce (coalesce (aDENARTICOL,'')|| ' ','')|| coalesce (V_REC.DENOBIECT,'')
          ELSE aDENARTICOL
        END ,
        AdaosExceptie = v_rec.AdaosExceptie,
        Promotie      = v_rec.Promotie,
        DiscPromo     = v_rec.discpromo,
        COEFCNAS      = v_rec.COEFCNAS,
        RAPCNAS       = v_rec.RAPCNAS,
        ANTIBIOTIC    = v_rec.ANTIBIOTIC,
        CERTIF_DDS       = v_rec.CERTIF_DDS,
        EXPORTEMCS    = V_REC.EXPORTEMCS,
        CODNC         = V_REC.CODNC,
        CODCPV       = V_REC.CODCPV,
        EXCLUSLISTARECM  = v_rec.EXCLUSLISTARECM,
        CODACCIZABIL  = V_REC.CODACCIZABIL,
        LANSIMP       =
        CASE
          WHEN COALESCE (V_REC.PRODUSPROPRIU, 0) = 0 THEN 0
          ELSE V_REC.LANSIMP
        END ,
        EXPORTKLG     = V_REC.EXPORTKLG,
        CODANALIZANOD = V_REC.CODANALIZANOD,
        SAFT_EXPORT   = V_REC.SAFT_EXPORT,
        CANTVANZ      = V_REC.CANTVANZ
      WHERE CodObiect = v_rec.CodObiect;

      if aCheck = '1' then
        PERFORM pkg_nom_articol_CHECKMODIFPRETRETAIL (v_rec.CodObiect);
      end if;
      if aMemo = '1' then
        PERFORM pkg_nom_articol_MEMOMODIPRET(v_rec.CodObiect);
      end if;
    END LOOP;

    DELETE FROM NARTOBJSUBUNIT S WHERE CODS IN (SELECT CODS FROM TMP_NARTOBJSUBUNIT_INI) AND CODS NOT IN (SELECT CODS FROM TMP_NARTOBJSUBUNIT);

    FOR V_REC IN (SELECT * FROM TMP_NARTOBJSUBUNIT) LOOP
      IF V_REC.CODS &lt; 0 THEN
        INSERT INTO NARTOBJSUBUNIT (CODS,
            CODOBIECT,
            SUBUNITATE,
            STOCMIN,
            STOCMAX,
            STOCMED,
            PROCSTOCMIN,
            PROCSTOCMAX,
            PROCSTOCMED,
            CODGEST)
          VALUES (NEXTVAL ('SEQ_NARTOBJSUBUNIT_CODS') ,
            V_REC.CODOBIECT,
            V_REC.SUBUNITATE,
            V_REC.STOCMIN,
            V_REC.STOCMAX,
            V_REC.STOCMED,
            V_REC.PROCSTOCMIN,
            V_REC.PROCSTOCMAX,
            V_REC.PROCSTOCMED,
            V_REC.CODGEST);
      ELSE
        UPDATE NARTOBJSUBUNIT
        SET
          STOCMIN = V_REC.STOCMIN,
          STOCMAX = V_REC.STOCMAX,
          STOCMED = V_REC.STOCMED,
          PROCSTOCMIN = V_REC.PROCSTOCMIN,
          PROCSTOCMAX = V_REC.PROCSTOCMAX,
          PROCSTOCMED = V_REC.PROCSTOCMED,
          CODGEST = V_REC.CODGEST
        WHERE
          CODS = V_REC.CODS;
      END IF;
    END LOOP;

    DELETE FROM NARTOBJ1 O1
    WHERE
      EXISTS (SELECT CODOBIECT FROM NARTOBJ WHERE CODARTICOL = RECID AND CODOBIECT = O1.CODOBIECT)
      AND NOT EXISTS (SELECT CODOBIECT1 FROM TMP_NARTOBJ1 WHERE CODOBIECT1 = O1.CODOBIECT1);

    DELETE FROM NARTOBJTRAD O1
    WHERE
      EXISTS (SELECT CodObiect FROM NArtObj WHERE CodArticol = RecId AND CodObiect = O1.CodObiect)
      AND NOT EXISTS (SELECT CodObiectTrad FROM TMP_NARTOBJTRAD WHERE CodObiectTrad = O1.CodObiectTrad);

    DELETE FROM NARTOBJIMP O1
    WHERE
      EXISTS (SELECT CODOBIECT FROM NARTOBJ WHERE CODARTICOL = RECID AND CODOBIECT = O1.CODOBIECT)
      AND NOT EXISTS (SELECT CODOBJIMP FROM TMP_NARTOBJIMP WHERE CODOBJIMP = O1.CODOBJIMP);

    DELETE FROM DISCPROMORETAIL O1
    WHERE
      EXISTS (SELECT CodObiect FROM NArtObj WHERE CodArticol = RecId AND CodObiect = O1.CodObiect)
      AND NOT EXISTS (SELECT COD FROM TMP_DISCPROMORETAIL WHERE Cod = O1.Cod);

    DELETE FROM NARTOBJCOLET O1
    WHERE
      EXISTS (SELECT CODOBIECT FROM NARTOBJ WHERE CODARTICOL = RECID AND CODOBIECT = O1.CODOBIECT)
      AND NOT EXISTS (SELECT CODOBJCOLET FROM TMP_NARTOBJCOLET WHERE CODOBJCOLET = O1.CODOBJCOLET);

    DELETE FROM CODEXTALT O1
    WHERE
      EXISTS (SELECT CODOBIECT FROM NARTOBJ WHERE CODARTICOL = RECID AND CODOBIECT = O1.CODOBIECT)
      AND NOT EXISTS (SELECT COD FROM TMP_CODEXTALT WHERE COD = O1.COD);

    DELETE FROM CODINTALT O1
    WHERE
      EXISTS (SELECT CODOBIECT FROM NARTOBJ WHERE CODARTICOL = RECID AND CODOBIECT = O1.CODOBIECT)
      AND NOT EXISTS (SELECT COD FROM TMP_CODINTALT WHERE COD = O1.COD);

    FOR v_rec IN (SELECT * FROM TMP_NARTOBJ1 ORDER BY CodObiect1) LOOP
      IF (v_Rec.CodObiect1 &lt; 0) THEN
        BEGIN
          INSERT INTO NARTOBJ1 (CodObiect1,
              CodObiect,
              PretMaximal,
              ProcAdaosMaximal,
              PRETREFERINTA,
              TIPPRETMAX,
              COMPENSAT,
              TIPCOMPENSARE,
              GRUPA,
              uplift,
              codmoneda,
              AdaosLa,
              PUNCTE,
              Umiditate,
              CORPURI_STRAINE,
              PUNCTESECTIE,
              Incoltit,
              Hectolitrica,
              Gluten,
              Fuzaritate,
              Cadere,
              Deformare,
              Sticlozitate,
              Sparturi,
              anstart,
              lunastart,
              tippret,
              ValMat,
              ValMan,
              ValRegie,
              D390Exclus,
              Cost,
              Cantservauto,
              proteina,
              aflatoxina,
              atac_plosnita,
              continut_ulei,
              aciditate,
              sistave,
              refractie,
              indice_w,
              toxina_don,
              boabe_toxice,
              MAX_UMIDITATE,MAX_CORPURI_STRAINE,MAX_INCOLTIT,MAX_HECTOLITRICA,MAX_GLUTEN,MAX_FUZARITATE,MAX_CADERE,MAX_DEFORMARE,
              MAX_STICLOZITATE,MAX_SPARTURI,MAX_PROTEINA,MAX_AFLATOXINA,MAX_ATAC_PLOSNITA,MAX_CONTINUT_ULEI,MAX_ACIDITATE,MAX_SISTAVE,
              MAX_REFRACTIE,MAX_INDICE_W,MAX_TOXINA_DON,MAX_BOABE_TOXICE,
              MIN_UMIDITATE,MIN_CORPURI_STRAINE,MIN_INCOLTIT,MIN_HECTOLITRICA,MIN_GLUTEN,MIN_FUZARITATE,MIN_CADERE,MIN_DEFORMARE,MIN_STICLOZITATE,MIN_SPARTURI,
              MIN_PROTEINA,MIN_AFLATOXINA,MIN_ATAC_PLOSNITA,MIN_CONTINUT_ULEI,MIN_ACIDITATE,MIN_SISTAVE,MIN_REFRACTIE,MIN_INDICE_W,MIN_TOXINA_DON,MIN_BOABE_TOXICE, PRETPROD)
            VALUES (NEXTVAL ('SEQ_NARTOBJ1_CODOBIECT1') ,
              v_rec.CodObiect,
              v_Rec.PretMaximal,
              v_Rec.ProcAdaosMaximal,
              V_REC.PRETREFERINTA,
              V_REC.TIPPRETMAX,
              V_REC.COMPENSAT,
              V_REC.TIPCOMPENSARE,
              V_REC.GRUPA,
              v_rec.uplift,
              v_rec.codmoneda,
              v_Rec.AdaosLa,
              v_Rec.PUNCTE,
              v_Rec.Umiditate,
              v_Rec.CORPURI_STRAINE,
              v_Rec.PUNCTESECTIE,
              v_Rec.Incoltit,
              v_Rec.Hectolitrica,
              v_Rec.Gluten,
              v_Rec.Fuzaritate,
              v_Rec.Cadere,
              v_Rec.Deformare,
              v_Rec.Sticlozitate,
              v_Rec.Sparturi,
              v_Rec.anstart,
              v_Rec.lunastart,
              v_rec.tippret,
              v_rec.ValMat,
              v_rec.ValMan,
              v_rec.ValRegie,
              v_rec.D390Exclus,
              v_rec.cost,
              v_rec.Cantservauto,
              v_Rec.proteina,
              v_Rec.aflatoxina,
              v_Rec.atac_plosnita,
              v_Rec.continut_ulei,
              v_Rec.aciditate,
              v_Rec.sistave,
              v_Rec.refractie,
              v_Rec.indice_w,
              v_Rec.toxina_don,
              v_Rec.boabe_toxice,
              v_Rec.MAX_UMIDITATE,v_Rec.MAX_CORPURI_STRAINE,v_Rec.MAX_INCOLTIT,v_Rec.MAX_HECTOLITRICA,v_Rec.MAX_GLUTEN,v_Rec.MAX_FUZARITATE,v_Rec.MAX_CADERE,v_Rec.MAX_DEFORMARE,
              v_Rec.MAX_STICLOZITATE,v_Rec.MAX_SPARTURI,v_Rec.MAX_PROTEINA,v_Rec.MAX_AFLATOXINA,v_Rec.MAX_ATAC_PLOSNITA,v_Rec.MAX_CONTINUT_ULEI,v_Rec.MAX_ACIDITATE,v_Rec.MAX_SISTAVE,
              v_Rec.MAX_REFRACTIE,v_Rec.MAX_INDICE_W,v_Rec.MAX_TOXINA_DON,v_Rec.MAX_BOABE_TOXICE,
              v_Rec.MIN_UMIDITATE,v_Rec.MIN_CORPURI_STRAINE,v_Rec.MIN_INCOLTIT,v_Rec.MIN_HECTOLITRICA,v_Rec.MIN_GLUTEN,v_Rec.MIN_FUZARITATE,v_Rec.MIN_CADERE,v_Rec.MIN_DEFORMARE,v_Rec.MIN_STICLOZITATE,v_Rec.MIN_SPARTURI,
              v_Rec.MIN_PROTEINA,v_Rec.MIN_AFLATOXINA,v_Rec.MIN_ATAC_PLOSNITA,v_Rec.MIN_CONTINUT_ULEI,v_Rec.MIN_ACIDITATE,v_Rec.MIN_SISTAVE,v_Rec.MIN_REFRACTIE,v_Rec.MIN_INDICE_W,v_Rec.MIN_TOXINA_DON,v_Rec.MIN_BOABE_TOXICE, V_REC.PRETPROD);
        END;
      ELSE
        BEGIN
          UPDATE NARTOBJ1
          SET
            CodObiect        = v_Rec.CodObiect,
            PretMaximal      = v_Rec.PretMaximal,
            ProcAdaosMaximal = v_Rec.ProcAdaosMaximal,
            PRETREFERINTA    = V_REC.PRETREFERINTA,
            TIPPRETMAX       = V_REC.TIPPRETMAX,
            COMPENSAT        = V_REC.COMPENSAT,
            TIPCOMPENSARE    = V_REC.TIPCOMPENSARE,
            GRUPA            = V_REC.GRUPA,
            uplift           = v_rec.uplift,
            PUNCTE           = v_Rec.PUNCTE,
            Umiditate        = v_Rec.Umiditate,
            CORPURI_STRAINE  = v_Rec.CORPURI_STRAINE,
            PUNCTESECTIE     = v_Rec.PUNCTESECTIE,
            Incoltit         = V_REC.Incoltit,
            Hectolitrica     = V_REC.Hectolitrica,
            Gluten           = V_REC.Gluten,
            Fuzaritate       = V_REC.Fuzaritate,
            Cadere           = V_REC.Cadere,
            Deformare        = v_rec.Deformare,
            Sticlozitate     = V_REC.Sticlozitate,
            Sparturi         = V_REC.Sparturi,
            codmoneda        = v_rec.codmoneda,
            AdaosLa          = v_Rec.AdaosLA,
            Anstart          = v_Rec.AnStart,
            lunastart        = v_Rec.LunaStart,
            tippret          = v_rec.tippret,
            ValMat           = v_rec.ValMat,
            ValMan           = v_rec.ValMan,
            ValRegie         = v_rec.ValRegie,
            D390Exclus       = v_rec.D390Exclus,
            Cost             = v_rec.Cost,
            CantServAuto     = v_rec.CantServAuto,
            proteina         = v_rec.proteina,
            aflatoxina       = v_rec.aflatoxina,
            atac_plosnita    = v_rec.atac_plosnita,
            continut_ulei    = v_rec.continut_ulei,
            aciditate        = v_rec.aciditate,
            sistave          = v_rec.sistave,
            refractie        = v_rec.refractie,
            indice_w         = v_rec.indice_w,
            toxina_don       = v_rec.toxina_don,
            boabe_toxice     = v_rec.boabe_toxice,
            MAX_UMIDITATE       = v_rec.MAX_UMIDITATE       ,
           MAX_CORPURI_STRAINE = v_rec.MAX_CORPURI_STRAINE ,
           MAX_INCOLTIT        = v_rec.MAX_INCOLTIT        ,
           MAX_HECTOLITRICA    = v_rec.MAX_HECTOLITRICA    ,
           MAX_GLUTEN          = v_rec.MAX_GLUTEN          ,
           MAX_FUZARITATE      = v_rec.MAX_FUZARITATE      ,
           MAX_CADERE          = v_rec.MAX_CADERE          ,
           MAX_DEFORMARE       = v_rec.MAX_DEFORMARE       ,
           MAX_STICLOZITATE    = v_rec.MAX_STICLOZITATE    ,
           MAX_SPARTURI        = v_rec.MAX_SPARTURI        ,
           MAX_PROTEINA        = v_rec.MAX_PROTEINA        ,
           MAX_AFLATOXINA      = v_rec.MAX_AFLATOXINA      ,
           MAX_ATAC_PLOSNITA   = v_rec.MAX_ATAC_PLOSNITA   ,
           MAX_CONTINUT_ULEI   = v_rec.MAX_CONTINUT_ULEI   ,
           MAX_ACIDITATE       = v_rec.MAX_ACIDITATE       ,
           MAX_SISTAVE         = v_rec.MAX_SISTAVE         ,
           MAX_REFRACTIE       = v_rec.MAX_REFRACTIE       ,
           MAX_INDICE_W        = v_rec.MAX_INDICE_W        ,
           MAX_TOXINA_DON      = v_rec.MAX_TOXINA_DON      ,
           MAX_BOABE_TOXICE    = v_rec.MAX_BOABE_TOXICE    ,
           MIN_UMIDITATE       = v_rec.MIN_UMIDITATE       ,
           MIN_CORPURI_STRAINE = v_rec.MIN_CORPURI_STRAINE ,
           MIN_INCOLTIT        = v_rec.MIN_INCOLTIT        ,
           MIN_HECTOLITRICA    = v_rec.MIN_HECTOLITRICA    ,
           MIN_GLUTEN          = v_rec.MIN_GLUTEN          ,
           MIN_FUZARITATE      = v_rec.MIN_FUZARITATE      ,
           MIN_CADERE          = v_rec.MIN_CADERE          ,
           MIN_DEFORMARE       = v_rec.MIN_DEFORMARE       ,
           MIN_STICLOZITATE    = v_rec.MIN_STICLOZITATE    ,
           MIN_SPARTURI        = v_rec.MIN_SPARTURI        ,
           MIN_PROTEINA        = v_rec.MIN_PROTEINA        ,
           MIN_AFLATOXINA      = v_rec.MIN_AFLATOXINA      ,
           MIN_ATAC_PLOSNITA   = v_rec.MIN_ATAC_PLOSNITA   ,
           MIN_CONTINUT_ULEI   = v_rec.MIN_CONTINUT_ULEI   ,
           MIN_ACIDITATE       = v_rec.MIN_ACIDITATE       ,
           MIN_SISTAVE         = v_rec.MIN_SISTAVE         ,
           MIN_REFRACTIE       = v_rec.MIN_REFRACTIE       ,
           MIN_INDICE_W        = v_rec.MIN_INDICE_W        ,
           MIN_TOXINA_DON      = v_rec.MIN_TOXINA_DON      ,
           MIN_BOABE_TOXICE    = v_rec.MIN_BOABE_TOXICE    ,
           PretProd            = v_Rec.PretProd
          WHERE CodObiect1 = v_rec.CodObiect1;
        END;
      END IF;
    END LOOP;

    FOR v_rec IN (SELECT * FROM TMP_NARTOBJTRAD ORDER BY CodObiectTrad) LOOP
      IF v_Rec.CodObiectTrad &lt; 0 THEN
        INSERT INTO NARTOBJTRAD (CodObiectTrad,
            CodObiect,
            CodLimba,
            DenumireTrad,
            Avertizare,
            descriere)
          VALUES (NEXTVAL ('SEQ_NARTOBJTRAD_CODOBIECTTRAD') ,
            v_rec.CodObiect,
            v_rec.CodLimba,
            v_rec.DenumireTrad,
            v_rec.Avertizare,
            v_rec.descriere);
      ELSE
        UPDATE NARTOBJTRAD
        SET
          CodObiect    = v_rec.CodObiect,
          CodLimba     = v_rec.CodLimba,
          DenumireTrad = v_rec.DenumireTrad,
          descriere    = v_rec.descriere,
          Avertizare   = v_rec.Avertizare
        WHERE
          CodObiectTrad = v_rec.CodObiectTrad;
      END IF;
    END LOOP;

    FOR v_rec IN (SELECT * FROM TMP_DISCPROMORETAIL) LOOP
      IF (COALESCE (v_Rec.Cod, 0) &lt; 0) THEN
        INSERT INTO DISCPROMORETAIL (COD,
            CODPOSTRETAIL,
            CODOBIECT,
            DISCPROMO)
          VALUES (NEXTVAL ('SEQ_DISCPROMORETAIL_COD') ,
            V_REC.CODPOSTRETAIL,
            V_REC.CODOBIECT,
            V_REC.DISCPROMO);
      ELSE
        UPDATE DISCPROMORETAIL
        SET
          CodObiect     = v_rec.CodObiect,
          CodPOSTRETAIL = v_rec.CODPOSTRETAIL,
          DISCPROMO     = v_rec.DISCPROMO
        WHERE
          COALESCE (Cod, 0) = COALESCE (v_rec.Cod, 0);
      END IF;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_CODEXTALT) LOOP
      IF V_REC.COD &lt; 0 THEN
        INSERT INTO CODEXTALT (COD,
            CODOBIECT,
            CODEXTERN, CODPART)
          VALUES (NEXTVAL ('SEQ_CODEXTALT_COD') ,
            V_REC.CODOBIECT,
            V_REC.CODEXTERN,
            V_REC.CODPART);
      ELSE
        UPDATE CODEXTALT
        SET CODEXTERN = V_REC.CODEXTERN,
            CODPART = V_REC.CODPART
        WHERE
          COD = V_REC.COD;
      END IF;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_CODINTALT) LOOP
      IF V_REC.COD &lt; 0 THEN
        INSERT INTO CODINTALT (COD,
            CODOBIECT,
            CODINTERN, CODPART)
          VALUES (NEXTVAL ('SEQ_CODINTALT_COD') ,
            V_REC.CODOBIECT,
            V_REC.CODINTERN,
            V_REC.CODPART
          );
      ELSE
        UPDATE CODINTALT
        SET CODINTERN = V_REC.CODINTERN,
            CODPART = V_REC.CODPART
        WHERE
          COD = V_REC.COD;
      END IF;
    END LOOP;

    FOR v_rec IN (SELECT * FROM TMP_NARTOBJCOLET ORDER BY CodObiect, INDEXLOCAL) LOOP
      IF (COALESCE (v_Rec.CODOBJCOLET, 0) &lt; 0) THEN
        BEGIN
          INSERT INTO NARTOBJCOLET (CODOBJCOLET,
              CODOBIECT,
              INDEXLOCAL,
              CONTINUT,
              IDCOLET,
              D1,
              D2,
              D3)
            VALUES (NEXTVAL ('SEQ_NARTOBJCOLET_COD') ,
              v_rec.CodObiect,
              v_Rec.IndexLocal,
              V_REC.CONTINUT,
              CASE
                WHEN COALESCE (V_REC.IDCOLET, '0') = '0' THEN TRIM (TO_CHAR (NEXTVAL ('SEQ_ETICHCOLET_COD') , '0000000009'))
                ELSE V_REC.IDCOLET
              END ,
              V_REC.D1,
              V_REC.D2,
              V_REC.D3);
        END;
      ELSE
        BEGIN
          UPDATE NARTOBJCOLET
          SET
            INDEXLOCAL = V_REC.INDEXLOCAL,
            CONTINUT   = V_REC.CONTINUT,
            IDCOLET    = V_REC.IDCOLET,
            D1 = V_REC.D1,
            D2 = V_REC.D2,
            D3 = V_REC.D3
          WHERE
            COALESCE (CodOBJCOLET, 0) = COALESCE (v_rec.CODOBJCOLET, 0);
        END;
      END IF;
    END LOOP;

    FOR V_REC IN (SELECT DA.CodDiscArt
                  FROM DISCART      DA,
                       DISCOUNT     D,
                       CRITERIIDISC CR
                  WHERE
                    (D.CODDISCOUNT = DA.CODDISCOUNT)
                    AND (CR.CODCRITERIU = D.CODCRITERIU)
                    AND (CR.PECLASE = 0)
                    AND (DA.CODOBIECT IN (SELECT CODOBIECT FROM TMP_NARTOBJ))
                 )
    LOOP
      DELETE FROM DISCART WHERE CODDISCART = V_REC.CODDISCART AND CODDISCART NOT IN (SELECT CODDISCART FROM TMP_DISCART);
    END LOOP;

    INSERT INTO DISCART (CODDISCART, CODDISCOUNT, CODOBIECT, GRUPA)
    SELECT NEXTVAL ('SEQ_DISCART_CODDISCART'), CODDISCOUNT, CODOBIECT, GRUPA
    FROM TMP_DISCART
    WHERE
      CODDISCART &lt; 0;

    DELETE FROM NARTCLI O1
    WHERE
      EXISTS (SELECT CODOBIECT FROM NARTOBJ WHERE CODARTICOL = RECID AND CODOBIECT = O1.CODOBIECT)
      AND NOT EXISTS (SELECT CODARTCLI FROM TMP_NARTCLI WHERE CODARTCLI = O1.CODARTCLI);

    FOR v_rec IN (SELECT * FROM TMP_NARTCLI ORDER BY CodArtCli) LOOP
      IF (COALESCE (v_Rec.CodArtCli, 0) &lt; 0) THEN
        BEGIN
          INSERT INTO NARTCLI (CodArtCli,
              CodObiect,
              CodPart,
              Denumire,
              CodExtern,
              UMSec,
              UMCorelat,
              CODMONEDA,
              PRET,
              tipcodafisat,
              CodLaClient,
              CODINTERN,
              IMPLICIT,
              CODCLASEP,
              CODGAMA,
              OBS,
              OBS2,
              UMSECIMPDOC,
              Duratatr,
              Zilestoc,
              GLN,
              IDspecific)
            VALUES (NEXTVAL ('SEQ_NARTCLI_CODARTCLI') ,
              v_rec.CodObiect,
              v_Rec.CodPart,
              v_Rec.Denumire,
              v_Rec.CodExtern,
              v_Rec.UMSec,
              v_rec.UMCorelat,
              v_Rec.CODMONEDA,
              v_Rec.PRET,
              v_Rec.tipcodafisat,
              v_rec.CodLaClient,
              v_rec.codintern,
              v_rec.IMPLICIT,
              V_REC.CODCLASEP,
              V_REC.CODGAMA,
              V_REC.OBS,
              V_REC.OBS2,
              V_REC.UMSECIMPDOC,
              v_rec.duratatr,
              v_rec.zilestoc,
              v_rec.GLN,
              v_rec.IDspecific);
        END;
      ELSE
        BEGIN
          UPDATE NARTCLI
          SET CodObiect  = v_Rec.CodObiect,
            CodPart      = v_Rec.CodPart,
            Denumire     = v_Rec.Denumire,
            CodExtern    = v_Rec.CodExtern,
            UMSec        = v_Rec.UMSec,
            UMCorelat    = v_Rec.UMCorelat,
            CODMONEDA    = v_Rec.CODMONEDA,
            PRET         = v_Rec.PRET,
            tipcodafisat = v_Rec.tipcodafisat,
            CodLaClient  = v_Rec.CodLaClient,
            CodIntern    = v_rec.Codintern,
            CODCLASEP    = V_REC.CODCLASEP,
            CODGAMA      = V_REC.CODGAMA,
            OBS          = V_REC.OBS,
            OBS2         = V_REC.OBS2,
            UMSECIMPDOC  = V_REC.UMSECIMPDOC,
            IMPLICIT     = v_Rec.IMPLICIT,
            DURATATR     = V_REC.DURATATR,
            ZILESTOC     = V_REC.ZILESTOC,
            GLN          = V_REC.GLN,
            IDspecific   = V_REC.IDspecific
          WHERE
            COALESCE (CodArtCli, 0) = COALESCE (v_rec.CodArtCli, 0);
        END;
      END IF;
    END LOOP;

    FOR V_REC IN (SELECT * FROM PRETM PM
                  WHERE CODOBIECT IN (SELECT CODOBIECT FROM TMP_NARTOBJ)
                        AND
                        COALESCE (PM.SUBUNITATEA, 1) = CASE
                                                         WHEN (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE (NULL,NULL)) = 1 THEN COALESCE (PM.SUBUNITATEA, 1)
                                                         ELSE (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE (NULL,NULL))
                                                       END
                        AND CODPRETM NOT IN (SELECT CODPRETM FROM TMP_PRETM))
    LOOP
      DELETE FROM PRETMAMB WHERE CODPRETM = V_REC.CODPRETM;
      DELETE FROM PRETM    WHERE CODPRETM = V_REC.CODPRETM;
    END LOOP;

    DELETE FROM PRETMAMB PMAMB
    WHERE
      EXISTS (SELECT * FROM TMP_PRETM WHERE CODPRETM = PMAMB.CODPRETM)
      AND NOT EXISTS (SELECT * FROM TMP_PRETMAMB WHERE CODPRETMAMB = PMAMB.CODPRETMAMB);

    aCODOBIECT  := 0;
    aINDEXLOCAL := 0;

    FOR V_REC IN (SELECT * FROM TMP_PRETM ORDER BY CODOBIECT, INDEXLOCAL) LOOP
      IF aCODOBIECT &lt;&gt; V_REC.CODOBIECT THEN
        aCODOBIECT  := V_REC.CODOBIECT;
        aINDEXLOCAL := 0;
      END IF;

      aINDEXLOCAL := aINDEXLOCAL + 1;
      IF COALESCE (V_REC.CODPRETM, 0) &lt; 0 THEN
        BEGIN
          SELECT NEXTVAL ('SEQ_PRETM_CODPRETM') INTO aCODPRETM;

          UPDATE TMP_PRETMAMB
          SET CODPRETM = aCODPRETM
          WHERE
            CODPRETM = V_REC.CODPRETM;

          INSERT INTO PRETM (CODPRETM,
              CODOBIECT,
              CODCATPRET,
              LEI,
              VALUTA,
              IMPLICIT,
              GRUPA,
              MONEDA,
              PROC,
              INDEXLOCAL,
              SUBUNITATEA,
              ROTUNJIRE,
              SUMAFIXAIMPLICIT)
            VALUES (aCODPRETM,
              V_REC.CODOBIECT,
              V_REC.CODCATPRET,
              V_REC.LEI,
              V_REC.VALUTA,
              V_REC.IMPLICIT,
              V_REC.GRUPA,
              V_REC.MONEDA,
              V_REC.PROC,
              CASE
                WHEN TO_NUMBER (current_setting ('PKG_GLOBALS.SUBUNITATE', true) ,'999999999999999999') &lt;&gt; 1 THEN aINDEXLOCAL
                ELSE V_REC.INDEXLOCAL
              END ,
              V_REC.SUBUNITATEA,
              V_REC.ROTUNJIRE,
              V_REC.SUMAFIXAIMPLICIT);
        END;
      ELSE
        BEGIN
          UPDATE PRETM
          SET
            CODOBIECT  = V_REC.CODOBIECT,
            CODCATPRET = V_REC.CODCATPRET,
            LEI        = V_REC.LEI,
            VALUTA     = V_REC.VALUTA,
            IMPLICIT   = V_REC.IMPLICIT,
            GRUPA      = V_REC.GRUPA,
            MONEDA     = V_REC.MONEDA,
            PROC       = V_REC.PROC,
            INDEXLOCAL = CASE
                           WHEN TO_NUMBER (current_setting ('PKG_GLOBALS.SUBUNITATE', true) ,'999999999999999999') &lt;&gt; 1 THEN aINDEXLOCAL
                           ELSE V_REC.INDEXLOCAL
                         END ,
            SUBUNITATEA = V_REC.SUBUNITATEA,
            ROTUNJIRE   = V_REC.ROTUNJIRE,
            SUMAFIXAIMPLICIT = V_REC.SUMAFIXAIMPLICIT
          WHERE
            CODPRETM = V_REC.CODPRETM;
        END;
      END IF;
    END LOOP;

    DELETE FROM NArtDim WHERE (CodArticol = RecId AND CodArtDim NOT IN (SELECT CodArtDim FROM TMP_NArtDim WHERE COALESCE (CodArtDim, 0) &gt; 0));

    FOR v_rec IN (SELECT * FROM TMP_NArtDim WHERE CodArtDim &lt; 0 and COALESCE (D1, 0) + COALESCE (D2, 0) + COALESCE (D3, 0) &gt; 0 ORDER BY CodArtDim)
    LOOP
      SELECT NEXTVAL ('SEQ_NARTDIM_CODARTDIM') INTO vCod;

      INSERT INTO NArtDim (CodArtDim,
          CodObiect,
          CodArticol,
          Tip,
          D1,
          D2,
          D3)
        VALUES (vCod,
          v_rec.CodObiect,
          RecId,
          v_Rec.Tip,
          v_Rec.D1,
          v_Rec.D2,
          v_Rec.D3);
    END LOOP;

    FOR v_rec IN (SELECT * FROM TMP_NArtDim WHERE COALESCE (CodArtDim, -1) &gt; 0 and COALESCE (D1, 0) + COALESCE (D2, 0) + COALESCE (D3, 0) &gt; 0 ORDER BY CodArtDim)
    LOOP
      UPDATE NArtDim
      SET
        CodArticol = RecId,
        Tip        = v_rec.Tip,
        D1         = v_rec.D1,
        D2         = v_rec.D2,
        D3         = v_rec.D3
      WHERE
        CodArtDim = v_rec.CodArtDim;
    END LOOP;

    DELETE FROM NARTATR WHERE (CodArticol = RecId AND CodArtAtr NOT IN (SELECT CodArtAtr FROM TMP_NARTATR WHERE COALESCE (CodArtAtr, 0) &lt;&gt; 0));

    FOR v_rec IN (SELECT * FROM TMP_NARTATR WHERE CodArtAtr &lt; 0 ORDER BY CodArtAtr) LOOP
      SELECT NEXTVAL ('SEQ_NARTATR_CODARTATR') INTO vCod;

      INSERT INTO NARTATR (CodArtAtr,
          CodArticol,
          CodAtribut,
          Activ,
          CodValPredef,
          Obligatoriu,
          OBS,
          Selectie,
          Facturabil,
          INDEXLOCAL)
        VALUES (vCod,
          RecId,
          v_Rec.CodAtribut,
          v_Rec.Activ,
          v_Rec.CodValPredef,
          v_Rec.Obligatoriu,
          V_REC.OBS,
          v_Rec.Selectie,
          v_Rec.Facturabil,
          V_REC.INDEXLOCAL);

      UPDATE TMP_NATROBJ SET CODARTATR = vCod WHERE CODARTATR = v_Rec.CODARTATR;
    END LOOP;

    FOR v_rec IN (SELECT * FROM TMP_NARTATR WHERE COALESCE (CodArtAtr, -1) &gt; 0 ORDER BY CodArtAtr) LOOP
      UPDATE NARTATR
      SET
        CodArticol   = RecId,
        CodAtribut   = v_rec.CodAtribut,
        Activ        = v_rec.Activ,
        CodValPredef = v_rec.CodValPredef,
        Obligatoriu  = v_rec.Obligatoriu,
        OBS          = V_REC.OBS,
        Selectie     = v_rec.Selectie,
        Facturabil   = v_rec.Facturabil,
        INDEXLOCAL   = v_rec.Indexlocal
      WHERE
        CodArtAtr = v_rec.CodArtAtr;
    END LOOP;

    FOR V_REC IN (SELECT AO.* FROM NATROBJ AO, NARTOBJ  O
                  WHERE
                        AO.CODOBIECT = O.CODOBIECT
                        AND O.CODARTICOL = RECID
                        AND AO.CODATROBJ NOT IN (SELECT CODATROBJ FROM TMP_NATROBJ)
                 )
    LOOP
      DELETE FROM NATROBJ WHERE CODATROBJ = V_REC.CODATROBJ;
    END LOOP;


    FOR v_rec IN (SELECT * FROM TMP_NARTOBJIMP) LOOP
      IF v_rec.codobjimp &gt; 0 THEN
        UPDATE NARTOBJIMP
        SET
          CodObiect        = v_rec.CodObiect,
          CodSubunit       = v_rec.CodSubunit,
          GestImplicita    = v_rec.GestImplicita,
          LocatieImplicita = v_rec.LocatieImplicita,
          DurMaxAprov      = v_rec.DurMaxAprov,
          ContImplicit     = v_rec.ContImplicit
        WHERE
          CodObjImp = v_rec.CodObjImp;
      ELSE
        INSERT INTO nartobjimp (codobjimp,
            codobiect,
            codsubunit,
            gestimplicita,
            locatieimplicita,
            durmaxaprov, contimplicit)
          VALUES (NEXTVAL ('SEQ_NARTOBJIMP_CODOBJIMP') ,
            v_rec.codobiect,
            v_rec.codsubunit,
            v_rec.gestimplicita,
            v_rec.locatieimplicita,
            v_rec.durmaxaprov, v_rec.contimplicit);
      END IF;
    END LOOP;


    INSERT INTO NATROBJ (CodObiect, CodAtrOBJ, CodArtAtr, CodValAtr, INDEXLOCAL)
    SELECT CodObiect, NEXTVAL ('SEQ_NATROBJ_CODATROBJ'), CodArtAtr, CodValAtr, INDEXLOCAL
    FROM TMP_NATROBJ
    WHERE CodAtrOBJ &lt; 0;

    FOR v_rec IN (SELECT * FROM TMP_NATROBJ WHERE COALESCE (CodAtrOBJ, 0) &gt; 0 ORDER BY CodAtrOBJ) LOOP
      UPDATE NATROBJ
      SET
        CodObiect  = v_rec.CodObiect,
        CodArtAtr  = v_rec.CodArtAtr,
        CodValAtr  = v_rec.CodValAtr,
        INDEXLOCAL = v_rec.INDEXLOCAL
      WHERE
        CodAtrOBJ = v_rec.CodAtrOBJ;
    END LOOP;


    DELETE FROM NARTOPT A
    WHERE
      CODOBIECT IN (SELECT CODOBIECT FROM NARTOBJ WHERE CODARTICOL = RECID)
      AND NOT EXISTS (SELECT CODOPT FROM TMP_NARTOPT WHERE CODOPT = A.CODOPT);

    FOR V_REC IN (SELECT * FROM TMP_NARTOPT) LOOP
      IF V_REC.CODOPT &lt; 0 THEN
        SELECT NEXTVAL ('SEQ_NARTOPT_CODOPT') INTO ACODOPT;

        INSERT INTO NARTOPT (CODOPT,
            CODOBIECT,
            codobiectopt,
            CodTipLocatie,
            ForceLei,
            CANT,
            STANDARD,
            OBS)
          VALUES (ACODOPT,
            V_REC.CODOBIECT,
            V_REC.codobiectopt,
            V_REC.CodTipLocatie,
            V_REC.ForceLei,
            V_REC.CANT,
            V_REC.STANDARD,
            V_REC.OBS);
      ELSE
        UPDATE NARTOPT
        SET
          CODOBIECT     = V_REC.CODOBIECT,
          codobiectopt  = V_REC.codobiectopt,
          CodTipLocatie = V_REC.CodTipLocatie,
          ForceLei      = V_REC.ForceLei,
          CANT          = V_REC.CANT,
          STANDARD      = V_REC.STANDARD,
          OBS           = V_REC.OBS
        WHERE
          CODOPT = V_REC.CODOPT;
      END IF;
    END LOOP;


    DELETE FROM NARTAMB A
    WHERE
      CODOBIECT IN (SELECT CODOBIECT FROM NARTOBJ WHERE CODARTICOL = RECID)
      AND NOT EXISTS (SELECT CODAMB FROM TMP_NARTAMB WHERE CODAMB = A.CODAMB);

    FOR V_REC IN (SELECT * FROM TMP_NARTAMB) LOOP
      IF V_REC.CODAMB &lt; 0 THEN
        SELECT NEXTVAL ('SEQ_NARTAMB_CODAMB') INTO ACODAMB;

        UPDATE TMP_PRETMAMB
        SET CODAMB = aCODAMB
        WHERE
          CODAMB = V_REC.CODAMB;

        INSERT INTO NARTAMB (CODAMB,
            CODOBIECT,
            CODOBIECTRETURN,
            CANT,
            CANTMIN,
            UMSEC,
            CODEXTERN,
            CODPLU,
            CODINTERN,
            MASA,
            LUNGIME,
            LATIME,
            INALTIME,
            LXLAT,
            LXH,
            LATXH,
            GREUTSPECIFICA,
            IMPLICITTIPDOC,
            TIP,
            nr_randuri, AdMax, returnabil)
          VALUES (ACODAMB,
            V_REC.CODOBIECT,
            V_REC.CODOBIECTRETURN,
            V_REC.CANT,
            V_REC.CANTMIN,
            V_REC.UMSEC,
            V_REC.CODEXTERN,
            V_REC.CODPLU,
            V_REC.CODINTERN,
            V_REC.MASA,
            V_REC.LUNGIME,
            V_REC.LATIME,
            V_REC.INALTIME,
            V_REC.LXLAT,
            V_REC.LXH,
            V_REC.LATXH,
            V_REC.GREUTSPECIFICA,
            V_REC.IMPLICITTIPDOC,
            V_REC.TIP,
            V_REC.nr_randuri, V_REC.AdMax, V_REC.returnabil);
      ELSE
        UPDATE NARTAMB
        SET CODOBIECT     = V_REC.CODOBIECT,
          CODOBIECTRETURN = V_REC.CODOBIECTRETURN,
          CANT            = V_REC.CANT,
          CANTMIN         = V_REC.CANTMIN,
          UMSEC           = V_REC.UMSEC,
          CODEXTERN       = V_REC.CODEXTERN,
          CODPLU          = V_REC.CODPLU,
          CODINTERN       = V_REC.CODINTERN,
          MASA            = V_REC.MASA,
          LUNGIME         = V_REC.LUNGIME,
          LATIME          = V_REC.LATIME,
          INALTIME        = V_REC.INALTIME,
          LXLAT           = V_REC.LXLAT,
          LXH             = V_REC.LXH,
          LATXH           = V_REC.LATXH,
          GREUTSPECIFICA  = V_REC.GREUTSPECIFICA,
          IMPLICITTIPDOC  = V_REC.IMPLICITTIPDOC,
          TIP             = V_REC.TIP,
          nr_randuri      = V_REC.nr_randuri,
          AdMax           = V_REC.AdMax,
          returnabil      = V_REC.returnabil
        WHERE
          CODAMB = V_REC.CODAMB;
      END IF;
    END LOOP;


    FOR V_REC IN (SELECT * FROM TMP_PRETMAMB) LOOP
      IF V_REC.CODPRETMAMB &lt; 0 THEN
        INSERT INTO PRETMAMB (CODPRETMAMB,
            CODPRETM,
            CODAMB,
            LEI,
            VALUTA)
          VALUES (NEXTVAL ('SEQ_PRETMAMB_CODPRETMAMB') ,
            V_REC.CODPRETM,
            V_REC.CODAMB,
            V_REC.LEI,
            V_REC.VALUTA);
      ELSE
        UPDATE PRETMAMB
        SET LEI = V_REC.LEI,
          VALUTA = V_REC.VALUTA
        WHERE
          CODPRETMAMB = V_REC.CODPRETMAMB;
      END IF;
    END LOOP;

  ELSE  -- INSERT------------------------------------------------------
    SELECT NEXTVAL ('SEQ_NART_CODARTICOL') INTO RecId;

    INSERT INTO NART (CodArticol,
        Den_Articol,
        UM,
        Clasa,
        TipSerie,
        TipArticol,
        AreTG,
        ContImplicit,
        GestImplicita,
        Certificat,
        EvolutiePret,
        UM1,
        UM2,
        ContServiciu,
        INCREMENTSERIE,
        RELATIEUM1,
        RELATIEUM2,
        CASADEMARCAT,
        CODCENTRU,
        D1,
        D2,
        D3,
        ParitateD1,
        ParitateD2,
        ParitateD3,
        CLASASTATIST,
        COMENZIONLINE,
        CODEXTERNART,
        SUFIXCODEXTERN,
        RESTNEGLIJCMD,
        NRZILESTOCMEDIU,
        MUSAICALITATE,
        Culoare,
        DCI,
        ClasaW, CHECKISAUTENTIC, PROCPerisab, codmasca, constructienoua, riscfiscal,  TIPSTOC )
    SELECT RecId,
      Den_Articol,
      UM,
      Clasa,
      TipSerie,
      TipArticol,
      AreTG,
      ContImplicit,
      GestImplicita,
      Certificat,
      EvolutiePret,
      UM1,
      UM2,
      ContServiciu,
      INCREMENTSERIE,
      RELATIEUM1,
      RELATIEUM2,
      CASADEMARCAT,
      CODCENTRU,
      D1,
      D2,
      D3,
      ParitateD1,
      ParitateD2,
      ParitateD3,
      CLASASTATIST,
      COMENZIONLINE,
      CODEXTERNART,
      SUFIXCODEXTERN,
      RESTNEGLIJCMD,
      NRZILESTOCMEDIU,
      MUSAICALITATE,
      Culoare,
      DCI,
      ClasaW, CHECKISAUTENTIC, PROCPerisab, codmasca, constructienoua, riscfiscal,  TIPSTOC
    FROM TMP_NART;

--      IF (SELECT WME_RESULT FROM winmadmin.PKG_USERFIRME_ValidPostLog(NULL, current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_NOM_ARTICOL.CT_MONITOR', true)))
--      THEN
--        PERFORM winmadmin.pkg_userfirme_postlogcucommit( 'NART', current_setting('PKG_GLOBALS.USERNAME', true), 'A', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), TO_NUMBER(current_setting('PKG_GLOBALS.SUBUNITATE', true),'999999999999999999'), null, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
--      END IF;

    FOR V_REC IN (SELECT * FROM TMP_NART1) LOOP
      SELECT NEXTVAL ('SEQ_NART1_CODARTICOL1') INTO VCOD;

   perform pkg_nom_articol_setct_monitor('MON_6');

   IF (SELECT WME_RESULT FROM winmadmin.PKG_USERFIRME_ValidPostLog(NULL, current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_NOM_ARTICOL.CT_MONITOR', true)))
     then
   PERFORM winmadmin.pkg_userfirme_postlogcucommit( 'NART', current_setting('PKG_GLOBALS.USERNAME', true), 'A', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), TO_NUMBER(current_setting('PKG_GLOBALS.SUBUNITATE', true),'999999999999999999'), null, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
   END IF;

     INSERT INTO NART1 ( CodArticol1,CodArticol,CodTVA,CodAccize,TaxCode, codtaxa1,CodTaxa2,anstart,lunastart, CodAccizeDVI )
     VALUES ( VCOD, RecId, V_REC.CodTVA,V_REC.CodAccize, V_REC.TaxCode, V_REC.codtaxa1, V_REC.CodTaxa2, V_REC.anstart, V_REC.lunastart, v_rec.CodAccizeDVI);
   END LOOP;

   INSERT INTO TMP_NART_LUNA (CODARTICOL1, CODARTICOL, CODTVA, CODACCIZE, TaxCode, codtaxa1, CODTAXA2, ANSTART, LUNASTART, CODACCIZEDVI)
   SELECT
     CODARTICOL1, CODARTICOL, CODTVA, CODACCIZE, TaxCode, codtaxa1, CODTAXA2, ANSTART, LUNASTART, CODACCIZEDVI
   FROM NART1 A1
    WHERE
      A1.CODARTICOL = RECID
      AND A1.ANSTART * 12 + A1.LUNASTART = (SELECT MAX (A2.ANSTART * 12 + A2.LUNASTART)
                                            FROM NART1 A2
                                            WHERE
                                              A2.ANSTART * 12 + A2.LUNASTART &lt;= (select pkg_globals_anlunalucru.wme_result from pkg_globals_anlunalucru (null, null))
                                              AND A2.CODARTICOL = RECID
                                           );

    FOR v_rec IN (SELECT * FROM TMP_NARTOBJ ORDER BY CodObiect) LOOP
      SELECT NEXTVAL ('SEQ_NARTOBJ_CODOBIECT') INTO vCod;

      UPDATE TMP_NATROBJ  SET CodObiect = vCod WHERE COALESCE (CodObiect, 0) = COALESCE (v_rec.CodObiect, 0);
      UPDATE TMP_NARTAMB  SET CodObiect = vCod WHERE COALESCE (CodObiect, 0) = COALESCE (v_rec.CodObiect, 0);
      UPDATE TMP_NARTOPT  SET CodObiect = vCod WHERE COALESCE (CodObiect, 0) = COALESCE (v_rec.CodObiect, 0);
      UPDATE TMP_NARTOBJ1 SET CodObiect = vCod WHERE COALESCE (CodObiect, 0) = COALESCE (v_rec.CodObiect, 0);
      UPDATE TMP_NARTDIM  SET CodObiect = vCod WHERE COALESCE (CodObiect, 0) = COALESCE (v_rec.CodObiect, 0);

      UPDATE TMP_NARTOBJTRAD SET CodObiect = vCod WHERE COALESCE (CodObiect, 0) = COALESCE (v_rec.CodObiect, 0);

      UPDATE TMP_DISCPROMORETAIL SET CodObiect = vCod WHERE COALESCE (CodObiect, 0) = COALESCE (v_rec.CodObiect, 0);

      UPDATE TMP_PRETM          SET CodObiect      = vCod WHERE COALESCE (CodObiect, 0)      = COALESCE (v_rec.CodObiect, 0);
      UPDATE TMP_DISCART        SET CodObiect      = vCod WHERE COALESCE (CodObiect, 0)      = COALESCE (v_rec.CodObiect, 0);
      UPDATE TMP_NARTCLI        SET CodObiect      = vCod WHERE COALESCE (CodObiect, 0)      = COALESCE (v_rec.CodObiect, 0);
      UPDATE TMP_NECHIV         SET CodObiect      = vCod WHERE COALESCE (CodObiect, 0)      = COALESCE (v_rec.CodObiect, 0);
      UPDATE TMP_NECHIV         SET CODOBIECTECHIV = vCod WHERE COALESCE (CodOBIECTECHIV, 0) = COALESCE (v_Rec.CodObiect, 0);
      UPDATE TMP_NARTOBJSUBUNIT SET CodObiect      = vCod WHERE COALESCE (CodObiect, 0)      = COALESCE (v_rec.CodObiect, 0);

      UPDATE TMP_NARTOBJCOLET SET CodObiect = vCod WHERE COALESCE (CodObiect, 0) = COALESCE (v_rec.CodObiect, 0);
      UPDATE TMP_CODEXTALT SET CodObiect = vCod WHERE COALESCE (CodObiect, 0) = COALESCE (v_rec.CodObiect, 0);
      UPDATE TMP_CODINTALT SET CodObiect = vCod WHERE COALESCE (CodObiect, 0) = COALESCE (v_rec.CodObiect, 0);

--      IF fnc_tmpexists ('TMP_NARTOBJEXT') = 1 THEN
--        EXECUTE ' UPDATE TMP_NARTOBJEXT SET CODOBIECT = '|| VCOD::varchar|| ' WHERE CODOBIECT = '||V_REC.CODOBIECT::varchar;
--      END IF;
      PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('NARTOBJ', vCod, v_rec.CodObiect);

   INSERT INTO NARTOBJ (
      CodObiect,CodArticol,CodExtern,CodIntern, StocMin,StocMed, INACTIVCMDONLINE, AUTORIZATIE,EXPIRAREAUTORIZ, TRADUCARTGENERIC, MESAJINACTIV, StocMax,Masa,Volum,
      CodProducator,CodVamal,Returnabil,LuniGarantie,Obs,TARAORIGINE, ZILEVALABIL, ZILEDISTRIB,
      CODPERISABIL,ProcAdaosNir,Rotunjire, UMAmbalare, PRETMINIM, TERMENPLATA, DATAADAUGARII,
      CODPLU, USESTOCMED, NEFACTURABIL, GREUTSPECIFICA, BLOCAT, DURMAXAPROV, CODCNAS, CODCARACT, CODD394, INACTIV, FARACMDFURN, FARANIVELAPROB, DESCARCAREINTEGRALA, FARASTOC, CODCATEGARTTI,
      AdaosExceptie, Promotie, ROTVALUTA, discpromo,
      DENUMIRE, produspropriu, COEFCNAS, RAPCNAS, ANTIBIOTIC, EXPORTEMCS, CODNC, CODCPV, EXCLUSLISTARECM, CODACCIZABIL, LANSIMP, EXPORTKLG, CODANALIZANOD, SAFT_EXPORT, CANTVANZ, CERTIF_DDS )
    VALUES (
      vCod, RecId, v_rec.CodExtern, v_rec.CodIntern,  v_rec.StocMin, v_rec.StocMed, V_REC.INACTIVCMDONLINE, v_rec.AUTORIZATIE,v_rec.EXPIRAREAUTORIZ, V_REC.TRADUCARTGENERIC, V_REC.MESAJINACTIV, v_rec.StocMax, v_rec.Masa, v_rec.Volum,
      v_rec.CodProducator, v_rec.CodVamal, v_rec.Returnabil, v_rec.LuniGarantie, v_rec.Obs, v_rec.TARAORIGINE, v_rec.ZILEVALABIL, v_rec.ZILEDISTRIB,
      V_REC.CODPERISABIL, v_rec.ProcAdaosNir, v_rec.Rotunjire, v_rec.UMAmbalare, V_REC.PRETMINIM, V_REC.TERMENPLATA, V_REC.DATAADAUGARII,
      V_REC.CODPLU, V_REC.USESTOCMED, v_rec.NEFACTURABIL, v_rec.GREUTSPECIFICA, V_REC.BLOCAT, V_REC.DURMAXAPROV, V_REC.CODCNAS, V_REC.CODCARACT, v_rec.CODD394, V_REC.INACTIV, V_REC.FARACMDFURN,
      V_REC.FARANIVELAPROB, V_REC.DESCARCAREINTEGRALA, V_REC.FARASTOC, V_REC.CODCATEGARTTI,
      v_rec.AdaosExceptie,  v_rec.Promotie, V_REC.ROTVALUTA, v_rec.discpromo,
      CASE
        WHEN (SELECT COUNT(*) FROM TMP_NATROBJ WHERE CODOBIECT = VCOD) &gt; 0 THEN aDENARTICOL || ' ' || V_REC.DENOBIECT
        ELSE aDENARTICOL
      END, v_Rec.produspropriu, V_REC.COEFCNAS, V_REC.RAPCNAS, V_REC.ANTIBIOTIC, V_REC.EXPORTEMCS, V_REC.CODNC, V_REC.CODCPV, V_REC.EXCLUSLISTARECM, V_REC.CODACCIZABIL,
      CASE WHEN COALESCE(V_REC.PRODUSPROPRIU,0) = 0 THEN 0 ELSE V_REC.LANSIMP END,
      V_REC.EXPORTKLG, V_REC.CODANALIZANOD, V_REC.SAFT_EXPORT, V_REC.CANTVANZ, V_REC.CERTIF_DDS
    );

    if aCheck = '1' then
      PERFORM pkg_nom_articol_CHECKMODIFPRETRETAIL (vCod);
    end if;
    if aMemo = '1' then
      PERFORM pkg_nom_articol_MEMOMODIPRET(vCod);
    END IF;
   END LOOP;

   if (aCodCatPret &gt; 0) and (GETSUBUNITATE() &gt; 1) THEN
    for v_sub in (select codsubunit from nsubunit where codsubunit &lt;&gt; GETSUBUNITATE() and codsubunit &gt; 1)
    LOOP
      insert into pretm(codpretm,codobiect,codcatpret,implicit,subunitatea,indexlocal,moneda)
      values(nextval('seq_pretm_codpretm'),vCod,aCodCatPret,1,v_sub.codsubunit,1,0);
    END LOOP;
   END IF;

    INSERT INTO NARTOBJSUBUNIT (CODS,
        CODOBIECT,
        SUBUNITATE,
        STOCMIN,
        STOCMED,
        STOCMAX,
        PROCSTOCMIN,
        PROCSTOCMED,
        PROCSTOCMAX,
        CODGEST)
    SELECT NEXTVAL ('SEQ_NARTOBJSUBUNIT_CODS') ,
      CODOBIECT,
      SUBUNITATE,
      STOCMIN,
      STOCMED,
      STOCMAX,
      PROCSTOCMIN,
      PROCSTOCMED,
      PROCSTOCMAX,
      CODGEST
    FROM TMP_NARTOBJSUBUNIT;

    FOR V_REC IN (SELECT * FROM TMP_NARTOPT) LOOP
      SELECT NEXTVAL ('SEQ_NARTOPT_CODOPT') INTO ACODOPT;

      INSERT INTO NARTOPT (CODOPT,
          CODOBIECT,
          codobiectopt,
          CodTipLocatie,
          ForceLei,
          CANT,
          STANDARD,
          OBS)
        VALUES (ACODOPT,
          V_REC.CODOBIECT,
          V_REC.codobiectopt,
          V_REC.CodTipLocatie,
          V_REC.ForceLei,
          V_REC.CANT,
          V_REC.STANDARD,
          V_REC.OBS);
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_NARTAMB) LOOP
      SELECT NEXTVAL ('SEQ_NARTAMB_CODAMB') INTO ACODAMB;

      UPDATE TMP_PRETMAMB
      SET CODAMB = aCODAMB
      WHERE
        CODAMB = V_REC.CODAMB;

      INSERT INTO NARTAMB (CODAMB,
          CODOBIECT,
          CODOBIECTRETURN,
          CANT,
          CANTMIN,
          UMSEC,
          CODEXTERN,
          CODPLU,
          CODINTERN,
          MASA,
          LUNGIME,
          LATIME,
          INALTIME,
          LXLAT,
          LXH,
          LATXH,
          GREUTSPECIFICA,
          IMPLICITTIPDOC,
          TIP,
          nr_randuri, AdMax, returnabil)
        VALUES (aCODAMB,
          vCOD,
          V_REC.CODOBIECTRETURN,
          V_REC.CANT,
          V_REC.CANTMIN,
          V_REC.UMSEC,
          V_REC.CODEXTERN,
          V_REC.CODPLU,
          V_REC.CODINTERN,
          V_REC.MASA,
          V_REC.LUNGIME,
          V_REC.LATIME,
          V_REC.INALTIME,
          V_REC.LXLAT,
          V_REC.LXH,
          V_REC.LATXH,
          V_REC.GREUTSPECIFICA,
          V_REC.IMPLICITTIPDOC,
          V_REC.TIP,
          V_REC.nr_randuri, V_REC.AdMax, V_REC.returnabil);
    END LOOP;

    FOR v_rec IN (SELECT * FROM TMP_NArtDim WHERE COALESCE (D1, 0) + COALESCE (D2, 0) + COALESCE (D3, 0) &gt; 0 ORDER BY CodArtDim) LOOP
      SELECT NEXTVAL ('SEQ_NARTDIM_CODARTDIM') INTO vCod;

      INSERT INTO NArtDim (CodArtDim,
          CodObiect,
          CodArticol,
          Tip,
          D1,
          D2,
          D3)
        VALUES (vCod,
          v_rec.CodObiect,
          RecId,
          v_Rec.Tip,
          v_Rec.D1,
          v_Rec.D2,
          v_Rec.D3);
    END LOOP;

    FOR v_rec IN (SELECT * FROM TMP_NARTATR ORDER BY CodArtAtr) LOOP
      SELECT NEXTVAL ('SEQ_NARTATR_CODARTATR') INTO vCod;

      INSERT INTO NARTATR (CodArtAtr,
          CodArticol,
          CodAtribut,
          Activ,
          CodValPredef,
          Obligatoriu,
          OBS,
          Selectie,
          Facturabil,
          INDEXLOCAL)
        VALUES (vCod,
          RecId,
          v_Rec.CodAtribut,
          v_Rec.Activ,
          v_Rec.CodValPredef,
          v_Rec.Obligatoriu,
          V_REC.OBS,
          v_Rec.Selectie,
          v_Rec.Facturabil,
          V_REC.INDEXLOCAL);

      UPDATE TMP_NATROBJ
      SET CodArtAtr = vCod
      WHERE
        CodArtAtr = v_rec.CodArtAtr;
    END LOOP;

    INSERT INTO NATROBJ (CodObiect,
        CodAtrOBJ,
        CodArtAtr,
        CodValAtr,
        INDEXLOCAL)
    (SELECT CodObiect,
          NEXTVAL ('SEQ_NATROBJ_CODATROBJ') ,
          CodArtAtr,
          CodValAtr,
          INDEXLOCAL
      FROM TMP_NATROBJ);

    FOR V_REC IN (SELECT * FROM TMP_CODEXTALT) LOOP
      INSERT INTO CODEXTALT (COD, CODOBIECT, CODEXTERN, CODPART)
      VALUES (NEXTVAL ('SEQ_CODEXTALT_COD'), V_REC.CODOBIECT, V_REC.CODEXTERN, V_REC.CODPART);
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_CODINTALT) LOOP
      INSERT INTO CODINTALT (COD, CODOBIECT, CODINTERN, CODPART)
      VALUES (NEXTVAL ('SEQ_CODINTALT_COD'), V_REC.CODOBIECT, V_REC.CODINTERN, V_REC.CODPART);
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_NARTOBJCOLET ORDER BY CODOBIECT, INDEXLOCAL) LOOP
      INSERT INTO NARTOBJCOLET (CODOBJCOLET,
          CODOBIECT,
          INDEXLOCAL,
          CONTINUT,
          IDCOLET,
          D1,
          D2,
          D3)
        VALUES (NEXTVAL ('SEQ_NARTOBJCOLET_COD') ,
          V_REC.CodObiect,
          V_REC.IndexLocal,
          V_REC.CONTINUT,
          CASE
            WHEN COALESCE (V_REC.IDCOLET, 0) = 0 THEN TRIM (TO_CHAR (NEXTVAL ('SEQ_ETICHCOLET_COD') , '00009'))
            ELSE V_REC.IDCOLET
          END ,
          V_REC.D1,
          V_REC.D2,
          V_REC.D3);
    END LOOP;

    aCODOBIECT  := 0;
    aINDEXLOCAL := 0;
    FOR V_REC IN (SELECT * FROM TMP_PRETM ORDER BY CODOBIECT, INDEXLOCAL) LOOP
      SELECT NEXTVAL ('SEQ_PRETM_CODPRETM') INTO aCODPRETM;

      UPDATE TMP_PRETMAMB
      SET CODPRETM = aCODPRETM
      WHERE
        CODPRETM = V_REC.CODPRETM;

      IF aCODOBIECT &lt;&gt; V_REC.CODOBIECT THEN
        aCODOBIECT  := V_REC.CODOBIECT;
        aINDEXLOCAL := 0;
      END IF;

      aINDEXLOCAL := aINDEXLOCAL + 1;
      INSERT INTO PRETM (CODPRETM,
          CODOBIECT,
          CODCATPRET,
          LEI,
          VALUTA,
          MONEDA,
          IMPLICIT,
          GRUPA,
          PROC,
          INDEXLOCAL,
          SUBUNITATEA,
          ROTUNJIRE,
          SUMAFIXAIMPLICIT)
        VALUES (aCODPRETM,
          V_REC.CODOBIECT,
          V_REC.CODCATPRET,
          V_REC.LEI,
          V_REC.VALUTA,
          V_REC.MONEDA,
          V_REC.IMPLICIT,
          V_REC.GRUPA,
          V_REC.PROC,
          CASE
            WHEN TO_NUMBER (current_setting ('PKG_GLOBALS.SUBUNITATE', true) ,'999999999999999999') &lt;&gt; 1 THEN aINDEXLOCAL
            ELSE V_REC.INDEXLOCAL
          END ,
          V_REC.SUBUNITATEA,
          V_REC.ROTUNJIRE,
          V_REC.SUMAFIXAIMPLICIT);
    END LOOP;


    INSERT INTO PRETMAMB (CODPRETMAMB, CODPRETM, CODAMB, LEI, VALUTA)
    (SELECT NEXTVAL ('SEQ_PRETMAMB_CODPRETMAMB'), CODPRETM, CODAMB, LEI, VALUTA FROM TMP_PRETMAMB);

    INSERT INTO NARTOBJ1 (CodObiect1,
        CodObiect,
        PretMaximal,
        ProcAdaosMaximal,
        PRETREFERINTA,
        TIPPRETMAX,
        COMPENSAT,
        TIPCOMPENSARE,
        GRUPA,
        uplift,
        AdaosLa,
        PUNCTE,
        Umiditate,
        CORPURI_STRAINE,
        PUNCTESECTIE,
        Incoltit,
        Hectolitrica,
        Gluten,
        Fuzaritate,
        Cadere,
        Deformare,
        Sticlozitate,
        Sparturi,
        Anstart,
        Lunastart,
        codmoneda,
        tippret,
        ValMat,
        ValMan,
        ValRegie,
        D390Exclus,
        Cost,
        Cantservauto,
        proteina,
        aflatoxina,
        atac_plosnita,
        continut_ulei,
        aciditate,
        sistave,
        refractie,
        indice_w,
        toxina_don,
        boabe_toxice,
        MAX_UMIDITATE,MAX_CORPURI_STRAINE,MAX_INCOLTIT,MAX_HECTOLITRICA,MAX_GLUTEN,MAX_FUZARITATE,MAX_CADERE,MAX_DEFORMARE,
    MAX_STICLOZITATE,MAX_SPARTURI,MAX_PROTEINA,MAX_AFLATOXINA,MAX_ATAC_PLOSNITA,MAX_CONTINUT_ULEI,MAX_ACIDITATE,MAX_SISTAVE,
    MAX_REFRACTIE,MAX_INDICE_W,MAX_TOXINA_DON,MAX_BOABE_TOXICE,
    MIN_UMIDITATE,MIN_CORPURI_STRAINE,MIN_INCOLTIT,MIN_HECTOLITRICA,MIN_GLUTEN,MIN_FUZARITATE,MIN_CADERE,MIN_DEFORMARE,MIN_STICLOZITATE,MIN_SPARTURI,
    MIN_PROTEINA,MIN_AFLATOXINA,MIN_ATAC_PLOSNITA,MIN_CONTINUT_ULEI,MIN_ACIDITATE,MIN_SISTAVE,MIN_REFRACTIE,MIN_INDICE_W,MIN_TOXINA_DON,MIN_BOABE_TOXICE, PretProd)
    SELECT NEXTVAL ('SEQ_NARTOBJ1_CODOBIECT1') ,
      CodObiect,
      PretMaximal,
      ProcAdaosMaximal,
      PRETREFERINTA,
      TIPPRETMAX,
      COMPENSAT,
      TIPCOMPENSARE,
      GRUPA,
      uplift,
      AdaosLa,
      PUNCTE,
      Umiditate,
      CORPURI_STRAINE,
      PUNCTESECTIE,
      Incoltit,
      Hectolitrica,
      Gluten,
      Fuzaritate,
      Cadere,
      Deformare,
      Sticlozitate,
      Sparturi,
      Anstart,
      Lunastart,
      codmoneda,
      tippret,
      ValMat,
      ValMan,
      ValRegie,
      D390Exclus,
      Cost,
      CantServAuto,
      proteina,
      aflatoxina,
      atac_plosnita,
      continut_ulei,
      aciditate,
      sistave,
      refractie,
      indice_w,
      toxina_don,
      boabe_toxice,
       MAX_UMIDITATE,MAX_CORPURI_STRAINE,MAX_INCOLTIT,MAX_HECTOLITRICA,MAX_GLUTEN,MAX_FUZARITATE,MAX_CADERE,MAX_DEFORMARE,
    MAX_STICLOZITATE,MAX_SPARTURI,MAX_PROTEINA,MAX_AFLATOXINA,MAX_ATAC_PLOSNITA,MAX_CONTINUT_ULEI,MAX_ACIDITATE,MAX_SISTAVE,
    MAX_REFRACTIE,MAX_INDICE_W,MAX_TOXINA_DON,MAX_BOABE_TOXICE,
    MIN_UMIDITATE,MIN_CORPURI_STRAINE,MIN_INCOLTIT,MIN_HECTOLITRICA,MIN_GLUTEN,MIN_FUZARITATE,MIN_CADERE,MIN_DEFORMARE,MIN_STICLOZITATE,MIN_SPARTURI,
    MIN_PROTEINA,MIN_AFLATOXINA,MIN_ATAC_PLOSNITA,MIN_CONTINUT_ULEI,MIN_ACIDITATE,MIN_SISTAVE,MIN_REFRACTIE,MIN_INDICE_W,MIN_TOXINA_DON,MIN_BOABE_TOXICE, PretProd
    FROM TMP_NARTOBJ1;

    INSERT INTO NARTOBJTRAD (CodObiectTrad,
        CodObiect,
        CodLimba,
        DenumireTrad,
        Avertizare,
        descriere)
    (SELECT NEXTVAL ('SEQ_NARTOBJTRAD_CODOBIECTTRAD') ,
          CodObiect,
          CodLimba,
          DenumireTrad,
          Avertizare,
          descriere
     FROM TMP_NARTOBJTRAD);

    INSERT INTO DISCPROMORETAIL (COD, CODPOSTRETAIL, CODOBIECT, DISCPROMO)
    (   SELECT NEXTVAL ('SEQ_DISCPROMORETAIL_COD'), CODPOSTRETAIL, CODOBIECT, DISCPROMO
        FROM TMP_DISCPROMORETAIL);

    INSERT INTO NARTCLI (CodArtCli,
        CodObiect,
        CodPart,
        Denumire,
        CodExtern,
        UMSec,
        UMCorelat,
        CODMONEDA,
        PRET,
        tipcodafisat,
        CodLaClient,
        CodIntern,
        IMPLICIT,
        CODCLASEP,
        CODGAMA,
        OBS,
        OBS2,
        UMSECIMPDOC,
        DurataTr,
        ZileStoc,
        GLN,
        IDspecific)
    SELECT NEXTVAL ('SEQ_NARTCLI_CODARTCLI') ,
      CodObiect,
      CodPart,
      Denumire,
      CodExtern,
      UMSec,
      UMCorelat,
      CODMONEDA,
      PRET,
      tipcodafisat,
      CodLaClient,
      CODINTERN,
      IMPLICIT,
      CODCLASEP,
      CODGAMA,
      OBS,
      OBS2,
      UMSECIMPDOC,
      DurataTr,
      ZileStoc,
      GLN,
      IDspecific
    FROM TMP_NARTCLI;

    INSERT INTO DISCART (CODDISCART, CODDISCOUNT, CODOBIECT)
    SELECT NEXTVAL ('SEQ_DISCART_CODDISCART'), CODDISCOUNT, CODOBIECT FROM TMP_DISCART;

    INSERT INTO NARTOBJIMP (CODOBJIMP,
        CODOBIECT,
        CODSUBUNIT,
        GESTIMPLICITA,
        LOCATIEIMPLICITA,
        DURMAXAPROV,CONTIMPLICIT)
    SELECT NEXTVAL ('SEQ_NARTOBJIMP_CODOBJIMP') ,
      CODOBIECT,
      CODSUBUNIT,
      GESTIMPLICITA,
      LOCATIEIMPLICITA,
      DURMAXAPROV,CONTIMPLICIT
    FROM TMP_NARTOBJIMP;

    INSERT INTO NARTIMPLICITE (CODIMPLICIT,
        CODARTICOL,
        CODSUBUNIT,
        CONTIMPLICIT,
        GESTIMPLICITA,
        LOCATIEIMPLICITA,
        NEVANDABIL)
    SELECT NEXTVAL ('SEQ_NARTIMPLICITE_CODIMPLICIT') ,
      RecId,
      CODSUBUNIT,
      CONTIMPLICIT,
      GESTIMPLICITA,
      LOCATIEIMPLICITA,
      NEVANDABIL
    FROM TMP_NARTIMPLICITE;
  ----------------------------------END Update / Insert
  END IF;


  FOR V_REC IN (SELECT * FROM TMP_NECHIV WHERE COALESCE (CodGrupa, 0) = 0) LOOP
    DELETE FROM NECHIV WHERE CODOBIECT = V_REC.CodObiect;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_NECHIV WHERE COALESCE (CodGrupa, 0) &gt; 0) LOOP
    IF COALESCE (V_REC.PARITATE, 0) = 0 THEN
      aPARITATE := 1;
    ELSE
      aPARITATE := V_REC.PARITATE;
    END IF;

    SELECT COUNT ( *) INTO aNr FROM NECHIV WHERE COALESCE (CODOBIECT, 0) = V_REC.CODOBIECT;

    IF aNr = 0 THEN
      INSERT INTO NECHIV (CODECHIV,
          CODOBIECT,
          PARITATE,
          CODGRUPA,
          Generic,
          indexlocal,
          Ind)
      (SELECT NEXTVAL ('SEQ_NECHIV_CODECHIV') ,
            V_REC.CODOBIECT,
            V_REC.PARITATE,
            V_REC.CODGRUPA,
            v_rec.generic,
            (SELECT max (indexlocal) + 1 FROM nechiv a WHERE a.codgrupa = v_rec.codgrupa) ,
            V_REC.Ind);
    ELSE
      UPDATE NECHIV
      SET
        PARITATE = aPARITATE,
        CODGRUPA = V_REC.CODGRUPA,
        IND      = V_REC.IND
      WHERE
        CODOBIECT = V_REC.CODOBIECT;
    END IF;
  END LOOP;

  FOR v_obj IN (SELECT CodObiect FROM NARTOBJ WHERE CodArticol = RecId AND COALESCE (TraducArtGeneric, 0) = 1) LOOP
    FOR v_lang IN (SELECT CodLimba FROM NLIMBA WHERE CodLimba &gt; 0 AND ExtLink &lt;&gt; 'RO') LOOP
      BEGIN
        SELECT DenumireTrad INTO aDenTrad
        FROM NARTOBJ              O
             LEFT JOIN NARTOBJTRAD T ON T.CodObiect = O.CodObiect
        WHERE (SELECT COUNT ( *) FROM NATROBJ A WHERE A.CodObiect = O.CodObiect) = 0
              AND O.CodArticol = RecId
              AND T.CodLimba = v_lang.CodLimba;
      EXCEPTION
      WHEN NO_DATA_FOUND THEN
        aDenTrad := NULL;
      END;

      IF aDenTrad IS NOT NULL THEN
        SELECT COUNT ( *) INTO aNr
        FROM NARTOBJTRAD
        WHERE
          CodObiect = v_obj.CodObiect
          AND CodLimba = v_lang.CodLimba;

        IF aNr = 0 THEN
          INSERT INTO NARTOBJTRAD (CodObiectTrad, CodObiect, CodLimba, DenumireTrad)
            VALUES (NEXTVAL ('SEQ_NARTOBJTRAD_CODOBIECTTRAD'), v_obj.CodObiect, v_lang.CodLimba,
                    coalesce (coalesce (aDenTrad,'') || ' ','')
                     || coalesce ( (SELECT PKG_SELECTARTICOLE_GET_JUST_DENOBIECT.WME_RESULT FROM PKG_SELECTARTICOLE_GET_JUST_DENOBIECT (NULL, v_obj.CodObiect)) ,'')
                   );
        END IF;
      END IF;
    END LOOP;
  END LOOP;
  -----------------
  IF pkg_nomatribute_am_date_nartobjatr(1, RecId) = 1 THEN
    BEGIN
      EXECUTE 'DELETE FROM NARTOBJATR WHERE CODOBIECT IN (SELECT CODOBIECT FROM NARTOBJ WHERE CODARTICOL = '||RecId||')';
      PERFORM PKG_NOMATRIBUTE_REPARA_NARTOBJATR(1, RecId);
    EXCEPTION WHEN OTHERS THEN
      PERFORM PKG_NOMATRIBUTE_REPARA_NARTOBJATR(0, NULL);
    END;
  END IF;

  select count(*) into aCount
    from cfgtables cfg
  inner join cfgtables1 cfg1 on cfg.codcfgtable = cfg1.codcfgtable
  where cfg.numetabela = 'NARTOBJEXT';

--  if fnc_tmpexists ('NARTOBJEXT') = 1 and fnc_tmpexists ('TMP_NARTOBJEXT') = 1 and acount &gt; 0
--  then
--     EXECUTE 'DELETE FROM NARTOBJEXT WHERE CODOBIECT IN (SELECT CODOBIECT FROM NARTOBJ WHERE CODARTICOL = ' || TO_CHAR(RECID) || ')  ';
--     EXECUTE 'UPDATE TMP_NARTOBJEXT SET CODNARTOBJEXT = NEXTVAL(''SEQ_NARTOBJEXT_CODNARTOBJEXT'')  WHERE CODNARTOBJEXT &lt; 0';
--     EXECUTE 'INSERT INTO NARTOBJEXT SELECT * FROM TMP_NARTOBJEXT ';
--  end if;
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS(501);

  if fnc_tmpexists ('NARTOBJEXT') &gt; 0 and acount &gt; 0 then
    BEGIN
      select Coalesce(fnc_getvalconstantalucru('CaractObiectGeneric'), '?') INTO CaractObiectGeneric;

    exception
    when others then
      CaractObiectGENERIC := '0';
    end;
    -----------------
    BEGIN
      SELECT COUNT ( *) INTO ATRIBUTE FROM NARTOBJ WHERE CODARTICOL = RECID;

    EXCEPTION
    WHEN OTHERS THEN
      ATRIBUTE := 0;
    END;

    IF CaractObiectGENERIC = '1' AND ATRIBUTE       &gt; 1 THEN
      BEGIN
        CODOBIECTGENERIC := (SELECT PKG_NOM_ARTICOL_GetCodObiectGeneric.WME_RESULT FROM PKG_NOM_ARTICOL_GetCodObiectGeneric (NULL, RecID));
      EXCEPTION
      WHEN OTHERS THEN
        CODOBIECTGENERIC := 0;
      END;

      IF CODOBIECTGENERIC &gt; 0 THEN
        PERFORM PKG_NOM_ARTICOL_CloneazaNArtObjEXT (CODOBIECTGENERIC, RECID);
      END IF;
    END IF;
  END IF;


  IF (SELECT PKG_CATEGCONST_GetValConstanta.WME_RESULT
      FROM PKG_CATEGCONST_GetValConstanta (NULL, 'UpdateDuriPeRetete',
                                           (SELECT PKG_GLOBALS_GetANLUCRU.WME_RESULT FROM PKG_GLOBALS_GetANLUCRU (NULL,NULL)) ,
                                           (SELECT PKG_GLOBALS_GetLUNALUCRU.WME_RESULT FROM PKG_GLOBALS_GetLUNALUCRU (NULL,NULL))
                                          )
     ) = '1'
  THEN
    FOR v_rec IN (SELECT pc.codprodcomp FROM prodcomp pc
                  WHERE EXISTS (SELECT obj.codobiect FROM nartobj obj WHERE pc.codobiect = obj.codobiect and obj.codarticol = recid))
    LOOP
      BEGIN
        SELECT CodProdComp INTO Tmp
        FROM prodcomp
        WHERE
          CodProdComp = v_rec.codprodcomp FOR UPDATE NOWAIT;

        UPDATE prodcomp pc
        SET
          D1 = aD1,
          D2 = aD2,
          D3 = aD3
        WHERE
          pc.codprodcomp = v_Rec.Codprodcomp;

        UPDATE prodcomp pc
        SET cantum1 = round ( (
              CASE
                WHEN aRELATIEUM1 IN (1, 7) AND COALESCE (aD1, 0) &lt;&gt; 0                                         THEN cant / D1
                WHEN aRELATIEUM1 IN (2, 8) AND COALESCE (aD1, 0) * COALESCE (aD2, 0) &lt;&gt; 0                     THEN cant / (COALESCE (aD1, 0) * COALESCE (aD2, 0))
                WHEN aRELATIEUM1 IN (3, 9) AND COALESCE (aD1, 0) * COALESCE (aD2, 0) * COALESCE (aD3, 0) &lt;&gt; 0 THEN cant / (COALESCE (aD1, 0) * COALESCE (aD2, 0) * COALESCE (aD3, 0))
                WHEN aRELATIEUM1 IN (4, 10) THEN cant * COALESCE (aD1, 0)
                WHEN aRELATIEUM1 IN (5, 11) THEN cant * COALESCE (aD1, 0) * COALESCE (aD2, 0)
                WHEN aRELATIEUM1 IN (6, 12) THEN cant * COALESCE (aD1, 0) * COALESCE (aD2, 0) * COALESCE (aD3, 0)
              END)
            ::numeric, 7)
        WHERE
          EXISTS (SELECT obj.codobiect FROM nartobj obj WHERE pc.codobiect = obj.codobiect and obj.codarticol = recid);

      EXCEPTION
      WHEN others THEN
        null;
      END;
    END LOOP;


    FOR v_rec IN (SELECT pm.codprodcomp, pm.codmat FROM prodmat pm
                  WHERE EXISTS (SELECT obj.codobiect FROM nartobj obj WHERE pm.codobiect = obj.codobiect and obj.codarticol = recid))
    LOOP
      BEGIN
        SELECT CodProdComp INTO Tmp FROM prodcomp WHERE CodProdComp = v_rec.codprodcomp FOR UPDATE NOWAIT;

        UPDATE prodmat pc
        SET
          D1 = aD1,
          D2 = aD2,
          D3 = aD3
        WHERE
          codmat = v_rec.codmat;

        UPDATE prodmat pc
        SET cantum1 = round ( (
              CASE
                WHEN aRELATIEUM1 IN (1, 7) AND COALESCE (aD1, 0) &lt;&gt; 0                                         THEN cant / D1
                WHEN aRELATIEUM1 IN (2, 8) AND COALESCE (aD1, 0) * COALESCE (aD2, 0) &lt;&gt; 0                     THEN cant / (COALESCE (aD1, 0) * COALESCE (aD2, 0))
                WHEN aRELATIEUM1 IN (3, 9) AND COALESCE (aD1, 0) * COALESCE (aD2, 0) * COALESCE (aD3, 0) &lt;&gt; 0 THEN cant / (COALESCE (aD1, 0) * COALESCE (aD2, 0) * COALESCE (aD3, 0))
                WHEN aRELATIEUM1 IN (4, 10) THEN cant * COALESCE (aD1, 0)
                WHEN aRELATIEUM1 IN (5, 11) THEN cant * COALESCE (aD1, 0) * COALESCE (aD2, 0)
                WHEN aRELATIEUM1 IN (6, 12) THEN cant * COALESCE (aD1, 0) * COALESCE (aD2, 0) * COALESCE (aD3, 0)
              END)
            ::numeric, 7)
        WHERE
          codmat = v_rec.codmat;

      EXCEPTION
      WHEN others THEN
        null;
      END;
    END LOOP;


    FOR v_rec IN (SELECT pm.codprodcomp, pm.codrez FROM prodrez pm
                  WHERE EXISTS (SELECT obj.codobiect FROM nartobj obj WHERE pm.codobiect = obj.codobiect and obj.codarticol = recid))
    LOOP
      BEGIN
        SELECT CodProdComp INTO Tmp FROM prodcomp WHERE CodProdComp = v_rec.codprodcomp FOR UPDATE NOWAIT;

        UPDATE prodrez pc
        SET
          D1 = aD1,
          D2 = aD2,
          D3 = aD3
        WHERE
          codrez = v_rec.codrez;

        UPDATE prodrez pc
        SET cantum1 = round ( (
              CASE
                WHEN aRELATIEUM1 IN (1, 7) AND COALESCE (aD1, 0) &lt;&gt; 0 THEN cant / D1
                WHEN aRELATIEUM1 IN (2, 8) AND COALESCE (aD1, 0) * COALESCE (aD2, 0) &lt;&gt; 0 THEN cant / (COALESCE (aD1, 0) * COALESCE (aD2, 0))
                WHEN aRELATIEUM1 IN (3, 9) AND COALESCE (aD1, 0) * COALESCE (aD2, 0) * COALESCE (aD3, 0) &lt;&gt; 0 THEN cant / (COALESCE (aD1, 0) * COALESCE (aD2, 0) * COALESCE (aD3, 0))
                WHEN aRELATIEUM1 IN (4, 10) THEN cant * COALESCE (aD1, 0)
                WHEN aRELATIEUM1 IN (5, 11) THEN cant * COALESCE (aD1, 0) * COALESCE (aD2, 0)
                WHEN aRELATIEUM1 IN (6, 12) THEN cant * COALESCE (aD1, 0) * COALESCE (aD2, 0) * COALESCE (aD3, 0)
              END)
            ::numeric, 7)
        WHERE
          codrez = v_rec.codrez;

      EXCEPTION
      WHEN others THEN
        null;
      END;
    END LOOP;


    FOR v_rec IN (SELECT pm.codprodcomp, pm.codnormemat FROM normemat pm
                  WHERE EXISTS (SELECT obj.codobiect FROM nartobj obj WHERE pm.codobiect = obj.codobiect and obj.codarticol = recid))
    LOOP
      BEGIN
        SELECT CodProdComp INTO Tmp FROM prodcomp WHERE CodProdComp = v_rec.codprodcomp FOR UPDATE NOWAIT;

        UPDATE normemat pc
        SET
          D1 = aD1,
          D2 = aD2,
          D3 = aD3
        WHERE
          codnormemat = v_rec.codnormemat;

        UPDATE normemat pc
        SET cantum1 = round ( (
              CASE
                WHEN aRELATIEUM1 IN (1, 7) AND COALESCE (aD1, 0) &lt;&gt; 0 THEN cant / D1
                WHEN aRELATIEUM1 IN (2, 8) AND COALESCE (aD1, 0) * COALESCE (aD2, 0) &lt;&gt; 0 THEN cant / (COALESCE (aD1, 0) * COALESCE (aD2, 0))
                WHEN aRELATIEUM1 IN (3, 9) AND COALESCE (aD1, 0) * COALESCE (aD2, 0) * COALESCE (aD3, 0) &lt;&gt; 0 THEN cant / (COALESCE (aD1, 0) * COALESCE (aD2, 0) * COALESCE (aD3, 0))
                WHEN aRELATIEUM1 IN (4, 10) THEN cant * COALESCE (aD1, 0)
                WHEN aRELATIEUM1 IN (5, 11) THEN cant * COALESCE (aD1, 0) * COALESCE (aD2, 0)
                WHEN aRELATIEUM1 IN (6, 12) THEN cant * COALESCE (aD1, 0) * COALESCE (aD2, 0) * COALESCE (aD3, 0)
              END)
            ::numeric, 7)
        WHERE
          codnormemat = v_rec.codnormemat;

      EXCEPTION
      WHEN others THEN
        null;
      END;
    END LOOP;


    FOR v_com IN (SELECT  DISTINCT codcomanda
                  FROM (SELECT c1.codcomanda
                        FROM comanda1             c1
                             INNER JOIN cmdprodmat cmd ON c1.codcomanda1 = cmd.codcomanda1
                        WHERE EXISTS (SELECT obj.codobiect FROM nartobj obj WHERE obj.codobiect = cmd.codobiect and obj.codarticol = recid)
                              and cmd.rest &gt; 0
                       ) A_PG
                 )
    LOOP
      BEGIN
        SELECT CodComanda INTO Tmp FROM comanda WHERE codcomanda = v_com.codcomanda FOR UPDATE NOWAIT;

        FOR v_cmd IN (SELECT cmd.codcmdprodmat, cmd.codcomanda1, cmd.tip
                       FROM comanda1              c1
                            INNER JOIN cmdprodmat cmd ON cmd.codcomanda1 = c1.codcomanda1
                       WHERE
                            c1.codcomanda = v_com.codcomanda
                            and cmd.rest &gt; 0
                            and EXISTS (SELECT obj.codobiect FROM nartobj obj WHERE obj.codobiect = cmd.codobiect and obj.codarticol = recid)
                     )
        LOOP
          UPDATE cmdprodmat
          SET
            D1 = aD1,
            D2 = aD2,
            D3 = aD3
          WHERE
            codcmdprodmat = v_cmd.codcmdprodmat;

          UPDATE cmdprodmat
          SET cantum1 = round ( (
                CASE
                  WHEN aRELATIEUM1 IN (1, 7) AND COALESCE (aD1, 0) &lt;&gt; 0 THEN cant / D1
                  WHEN aRELATIEUM1 IN (2, 8) AND COALESCE (aD1, 0) * COALESCE (aD2, 0) &lt;&gt; 0 THEN cant / (COALESCE (aD1, 0) * COALESCE (aD2, 0))
                  WHEN aRELATIEUM1 IN (3, 9) AND COALESCE (aD1, 0) * COALESCE (aD2, 0) * COALESCE (aD3, 0) &lt;&gt; 0 THEN cant / (COALESCE (aD1, 0) * COALESCE (aD2, 0) * COALESCE (aD3, 0))
                  WHEN aRELATIEUM1 IN (4, 10) THEN cant * COALESCE (aD1, 0)
                  WHEN aRELATIEUM1 IN (5, 11) THEN cant * COALESCE (aD1, 0) * COALESCE (aD2, 0)
                  WHEN aRELATIEUM1 IN (6, 12) THEN cant * COALESCE (aD1, 0) * COALESCE (aD2, 0) * COALESCE (aD3, 0)
                END)
              ::numeric, 7)
          WHERE
            codcmdprodmat = v_cmd.codcmdprodmat;

          IF v_cmd.tip IN (0, 2) THEN
            UPDATE comanda1
            SET
              D1 = aD1,
              D2 = aD2,
              D3 = aD3
            WHERE
              codcomanda1 = v_cmd.codcomanda1;

            UPDATE comanda1
            SET acceptum1 = round ( (
                  CASE
                    WHEN aRELATIEUM1 IN (1, 7) AND COALESCE (aD1, 0) &lt;&gt; 0 THEN cantacceptat / D1
                    WHEN aRELATIEUM1 IN (2, 8) AND COALESCE (aD1, 0) * COALESCE (aD2, 0) &lt;&gt; 0 THEN cantacceptat / (COALESCE (aD1, 0) * COALESCE (aD2, 0))
                    WHEN aRELATIEUM1 IN (3, 9) AND COALESCE (aD1, 0) * COALESCE (aD2, 0) * COALESCE (aD3, 0) &lt;&gt; 0 THEN cantacceptat / (COALESCE (aD1, 0) * COALESCE (aD2, 0) * COALESCE (aD3, 0))
                    WHEN aRELATIEUM1 IN (4, 10) THEN cantacceptat * COALESCE (aD1, 0)
                    WHEN aRELATIEUM1 IN (5, 11) THEN cantacceptat * COALESCE (aD1, 0) * COALESCE (aD2, 0)
                    WHEN aRELATIEUM1 IN (6, 12) THEN cantacceptat * COALESCE (aD1, 0) * COALESCE (aD2, 0) * COALESCE (aD3, 0)
                  END)
                ::numeric, 7)
            WHERE
              codcomanda1 = v_cmd.codcomanda1;

          END IF;
        END LOOP;
      EXCEPTION
      WHEN others THEN
        null;
      END;
    END LOOP;
  END IF;

  select count(*) into aCount from nartobj where codarticol = recid;
  CALL PRC_AL_REFRESH('nart1', RECID);
  if acount &lt;= 10 then
    FOR vRec IN (SELECT CODOBIECT FROM NARTOBJ WHERE CODARTICOL = RECID) LOOP
      CALL PRC_AL_REFRESH('nartobj1', VRec.CODOBIECT);
      END LOOP;
  ELSE
    CALL PRC_AL_REFRESH('NARTOBJ1');
  END IF;

    PERFORM NotifyModif (OPERATION, RECID, 'NART');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_updatenartobj1integer</obj_name>
  <obj_hashval>45ad69ff49db19ba1d9a71ddca3f760d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_updatenartobj1integer(camp character varying, pvaloare numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 12.03.2021 - sinc.Oracle
  PERFORM pkg_nom_articol_updatenartobj1string(camp, pvaloare::varchar);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_parcaut_getct_monitor</obj_name>
  <obj_hashval>525806c0996fc6b6f1eb91d38d0006c4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_parcaut_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_NOM_PARCAUT.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_72';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomactivit_sp_lockrecord</obj_name>
  <obj_hashval>c09263241a9fb3136d5e87c4ce5a21b4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomactivit_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT codactivit INTO Tmp FROM NACTIVIT WHERE codactivit = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomautorizatiiauto_sp_deleterecord</obj_name>
  <obj_hashval>44ebcd81bac94337514ab56f8947572d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomautorizatiiauto_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_NOMAUTORIZATIIAUTO_SP_LOCKRECORD( RecId);
  DELETE FROM nautorizatiiauto WHERE codautorizatii = RecId;
  PERFORM NotifyModif( 2, RECID, 'NAUTORIZATIIAUTO');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_get_part_curent_cf</obj_name>
  <obj_hashval>ec65778e8fc981fa9efe3e207a168555</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_get_part_curent_cf(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  current_setting('PKG_NOMPART.PARTENER_CURENT_CF',true)::numeric;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_make_curs_general_luna</obj_name>
  <obj_hashval>8de5b021106d999b8a44063fbbb7a065</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_make_curs_general_luna(INOUT wme_result numeric, INOUT adata character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  --Florin 06.10.2025 - fixat 6649
  DELETE FROM TMP_CURS_REGULARIZAT_LUNA;
  insert into x (view_name, test) values ('adata1', adata);
  INSERT INTO TMP_CURS_REGULARIZAT_LUNA (CODGENERAL, CURS)
  SELECT DISTINCT ON (R1.CODGENERAL)
      R1.CODGENERAL,
      R.CURS
  FROM REG R
  INNER JOIN REG1 R1 ON R1.CODREG = R.CODREG
  WHERE R.TIPREG = 46
      AND R.DATADOC &lt;= TO_DATE(aDATA, 'dd.mm.yyyy')
  ORDER BY R1.CODGENERAL, R.DATADOC DESC;
/*
  SELECT R1.CODGENERAL, Max(R.CURS) KEEP (Dense_Rank LAST ORDER BY R.DATADOC) CURS
  FROM REG R
    INNER JOIN REG1 R1 ON R1.CODREG = R.CODREG
  WHERE R.TIPREG = 46
    AND R.DATADOC &lt;= TO_DATE(aDATA, 'dd.mm.yyyy')
  GROUP BY R1.CODGENERAL;
*/
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_make_curs_moneda_luna</obj_name>
  <obj_hashval>5e6ceb6d81700e7a344498b826ef6c61</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_make_curs_moneda_luna(adata character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
/*
DELETE FROM TMP_CURS_MONEDA_REG;
INSERT INTO TMP_CURS_MONEDA_REG
(
CODMONEDA, CURS
)
SELECT M1.CODMONEDA, M1.CURS
FROM REG M1
WHERE
   M1.TIPREG = 46 AND  M1.DATADOC = (
SELECT MAX( DATADOC)
FROM REG M2
WHERE
   M1.TIPREG = 46 AND  M1.CODMONEDA = M2.CODMONEDA AND  M2.DATADOC &lt;= TO_DATE( aDATA, 'dd.mm.yyyy')
);
*/
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_note_credit_updatecentralizare</obj_name>
  <obj_hashval>e950572aebd79119b9f680baa41532bb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_note_credit_updatecentralizare(acodies numeric, acodnc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  vtipdoc numeric;
BEGIN
  --Florin 19.09.2023 - fixat 59477
  --Florin 11.09.2023 - sinc. Oracle
  SELECT TipDoc INTO vTipDoc FROM notecredit WHERE codncredit = acodnc;

  IF vTipDoc = 58 THEN
    FOR v_rec IN (SELECT COALESCE (i1.codobiect, 0) CODOBIECT, COALESCE (i1.codobiectorig, 0) CODOBIECTORIG,
                         CASE WHEN art.tiparticol::numeric = 0 THEN i1.cant
                              ELSE CASE WHEN i.tipdoc = 21 THEN I1.Cant * I1.PU - I1.TVA
                                        ELSE I1.Cant * I1.PU
                                   END
                         END  VALOARE
                  FROM iesiri1         i1
                    INNER JOIN iesiri  i   ON i.codies       = i1.codies
                    INNER JOIN nartobj obj ON i1.codobiect   = obj.codobiect
                    INNER JOIN nart    art ON obj.codarticol = art.codarticol
                  WHERE
                    i1.codies = abs(aCodIes))
    LOOP
      UPDATE centralizarenc
      SET
        diferente = nvl(diferente,0) - Sign(aCodIes) * v_Rec.valoare,
        facturat  = nvl(facturat,0) + Sign(aCodIes) * v_rec.valoare
      WHERE
        COALESCE (codobiect, 0) = v_Rec.codobiect
        and COALESCE (codobiectasoc, 0) = v_Rec.codobiectorig
        and codncredit = aCodNC;

      UPDATE tmp_centralizarenc
      SET
        diferente = nvl(diferente,0) - Sign(aCodIes) * v_Rec.valoare,
        facturat  = nvl(facturat,0) + Sign(aCodIes) * v_rec.valoare
      WHERE
        COALESCE (codobiect, 0) = v_rec.codobiect
        and COALESCE (codobiectasoc, 0) = v_Rec.codobiectorig
        and codncredit = aCodNC;
    END LOOP;
  ELSE
    FOR v_rec IN (SELECT COALESCE (i1.codobiect, 0) CODOBIECT, COALESCE (i1.codobiectorig, 0) CODOBIECTORIG,
                         CASE WHEN art.tiparticol::numeric = 0 THEN I1.Cant * I1.PU ELSE i1.cant END  VALOARE
                  FROM intrari1          i1
                    INNER JOIN nartobj obj ON i1.codobiect = obj.codobiect
                    INNER JOIN nart    art ON obj.codarticol = art.codarticol
                  WHERE i1.codintr = aCodIes)
    LOOP
      UPDATE centralizarenc
      SET
        diferente = nvl(diferente,0) - Sign(aCodIes) * v_Rec.valoare,
        facturat  = nvl(facturat,0) + Sign(aCodIes) * v_rec.valoare
      WHERE
        COALESCE (codobiect, 0) = v_rec.codobiect
        and COALESCE (codobiectasoc, 0) = v_Rec.codobiectorig
        and codncredit = aCodNC;

      UPDATE tmp_centralizarenc
      SET
        diferente = nvl(diferente,0) - Sign(aCodIes) * v_Rec.valoare,
        facturat  = nvl(facturat,0) + Sign(aCodIes) * v_rec.valoare
      WHERE
        COALESCE (codobiect, 0) = v_rec.codobiect
        and COALESCE (codobiectasoc, 0) = v_Rec.codobiectorig
        and codncredit = aCodNC;

    END LOOP;
  END IF;

  UPDATE tmp_notecredit
  SET
  TOTALZ    = TOTALZ    + (SELECT COALESCE (Round ( (sum (valdoc)) ::numeric, 2) , 0)
                           FROM tmp_notecreditz WHERE COALESCE (codobligstins, 0) = 0) ,
  TOTALLEIZ = TOTALLEIZ + (SELECT COALESCE (Round ( (sum (vallei)) ::numeric, 2) , 0)
                           FROM tmp_notecreditz WHERE COALESCE (codobligstins, 0) = 0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getcodcontract1_20210504</obj_name>
  <obj_hashval>22043439c7af1ec8514675d534b5bbd5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getcodcontract1_20210504(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT adatadoc timestamp without time zone, INOUT acodcontract numeric, INOUT acodies1 numeric DEFAULT 0)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
  declare
    vrec record;
  BEGIN
    --Adina 16.04.2021
    vrec = pkg_notecredit_getcodcontract1(null,acodobiect,adatadoc::date,acodcontract,COALESCE(acodies1,0));
    WME_Result := vrec.wme_result;
    RETURN;
  end;
  $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_getprocoffinvoice</obj_name>
  <obj_hashval>d21eae0eaaa4ae47c95370747192bfec</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_getprocoffinvoice(INOUT wme_result numeric, INOUT vcodpart numeric, INOUT vdata character varying, INOUT vcodsubunit numeric, INOUT vcodsediu numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aProcNed numeric;
  aProc    numeric;
begin
  -- BOGDAN 15.04.2021
  BEGIN
    SELECT COALESCE (SUM (COALESCE (DI.Procent, 0)) , 0)
    INTO STRICT
      aProc
    FROM NPARTDISC             PD
      INNER JOIN criteriidisc  CD  ON PD.CODCATEGDISC = CD.CODCRITERIU
      INNER JOIN criteriidisc1 CD1 ON CD.CODCRITERIU  = CD1.CODCRITERIU
      INNER JOIN DISCOUNT      D   ON CD.CODCRITERIU  = D.CODCRITERIU and CD1.CODCRITERIU1 = D.CODCRITERIU1
      INNER JOIN DISCINTERVAL  DI  ON DI.CODDISCOUNT  = D.CODDISCOUNT
      INNER JOIN NAGENDA       AG  ON D.CODTIPSEDIU   = AG.CODTIPSEDIU
    WHERE
      CD.peclase = 3
      and CD.offinvoice = 1
      and AG.CODAGENDA  = vCodSediu
      and CD1.Subunitatea = vCodSubunit
      and PD.CodPart    = vCodPart
      and CD1.Datastart = (SELECT max (CD11.datastart) FROM criteriidisc1 CD11 WHERE to_date (vData, 'DD.MM.YYYY') &gt;= CD11.DATASTART and CD11.CODCRITERIU1 = cd1.codcriteriu1);

  EXCEPTION
  WHEN others THEN
    aProc := 0;
  END;

  BEGIN
    SELECT COALESCE (SUM (COALESCE (DI.Procent, 0)) , 0)
    INTO STRICT
      aProcNed
    FROM NPARTDISC             PD
      INNER JOIN criteriidisc  CD  ON PD.CODCATEGDISC = CD.CODCRITERIU
      INNER JOIN criteriidisc1 CD1 ON CD.CODCRITERIU  = CD1.CODCRITERIU
      INNER JOIN DISCOUNT      D   ON CD.CODCRITERIU  = D.CODCRITERIU and CD1.CODCRITERIU1 = D.CODCRITERIU1
      INNER JOIN DISCINTERVAL  DI  ON DI.CODDISCOUNT  = D.CODDISCOUNT
    WHERE
      CD.peclase = 3
      and CD.offinvoice   = 1
      and CD1.Subunitatea = vCodSubunit
      and COALESCE (D.Codtipsediu, 0) = 0
      and PD.CodPart    = vCodPart
      and CD1.Datastart = (SELECT max (CD11.datastart) FROM criteriidisc1 CD11 WHERE to_date (vData, 'DD.MM.YYYY') &gt;= CD11.DATASTART and CD11.CODCRITERIU1 = cd1.codcriteriu1);

  EXCEPTION
  WHEN others THEN
    aProcNed := 0;
  END;

  WME_Result := aProc + aProcNed;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_settnccadouri</obj_name>
  <obj_hashval>bce6eb21750dd96bc5e0ab36940aa614</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_settnccadouri(atnccadouri numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOTECREDIT.tncCadouri',atncCadouri::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_tncpenalizari</obj_name>
  <obj_hashval>a87a2018e67458cd6513ddbdfa684770</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_tncpenalizari(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.tncPenalizari', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 6;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_npartretail_sp_deleterecord</obj_name>
  <obj_hashval>6852f55c66fb6f8dab31e673bba888b8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_npartretail_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM NSEDIIPARTRETAIL WHERE CODPARTRETAIL = RECID;
  DELETE FROM NCODFISCRETAIL   WHERE CODPARTRETAIL = RECID;
  DELETE FROM NPARTDISCRETAIL  WHERE CODPARTRETAIL = RECID;
  DELETE FROM NDELEGATRETAIL   WHERE CODPARTRETAIL = RECID;
  DELETE FROM NBANCIRETAIL     WHERE CODPARTRETAIL = RECID;
  DELETE FROM NPARTRETAIL      WHERE CODPARTRETAIL = RECID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nzone_sp_deleterecord</obj_name>
  <obj_hashval>675ab5bda38f6ea59e46010365d4fb56</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nzone_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_NZONE_SP_LOCKRECORD( recid);
  DELETE FROM nzone WHERE codzona = recid;
  PERFORM NotifyModif( 2, RECID, 'NZONE');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nzone_sp_gotorecord</obj_name>
  <obj_hashval>5f33a98297d9982ef96029ad2460a47a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nzone_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO tmp_nzone(codzona, den_zona, simbol, obs)
  SELECT codzona, den_zona, simbol, obs FROM nzone WHERE codzona = recid;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oferta_setct_monitor</obj_name>
  <obj_hashval>38cab44fb805be0309d49c39cef46289</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oferta_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_OFERTA.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oferta_updatecomandaxofertanoua</obj_name>
  <obj_hashval>bef6c1a9bd734bfa25aba3b42dd072e7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oferta_updatecomandaxofertanoua(INOUT wme_result character varying, INOUT pcodoferta numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  V_REC       RECORD;
  listaComenziDeModificat numeric[];
  codComandaModificata numeric(20);
  valDoc numeric(20,7);
  vPretLinie numeric(20,7);
  listaComenziModificate Varchar(3000);
  listaComenziBlocate Varchar(3000);
  existaComenziBLocate boolean;
  tmpCod numeric(20);
  it numeric;

  lista_comenzi CURSOR FOR  select l_tot.codComanda1,l_tot.codComanda, l_tot.nrDoc, l_tot.dataDoc, l_tot.adDim, l_tot.cmdPU, l_tot.cmdPretOrig, l_tot.rotunjire,l_tot.codOferta1, l_tot.ofrPret
      from
         (select distinct  t_lst.codComanda1, t_lst.codComanda, t_lst.nrDoc, t_lst.dataDoc, t_lst.adDim, t_lst.cmdPU, t_lst.cmdPretOrig, t_lst.rotunjire,
                   last_value (t_lst.codOferta1) over ( PARTITION BY t_lst.codComanda1, t_lst.codComanda, t_lst.nrDoc, t_lst.dataDoc, t_lst.adDim, t_lst.cmdPU, t_lst.cmdPretOrig, t_lst.rotunjire
                                         ORDER by t_lst.cantmin range between unbounded preceding and unbounded following )  as codOferta1,
                   last_value (t_lst.ofrPret) over ( PARTITION BY t_lst.codComanda1, t_lst.codComanda, t_lst.nrDoc, t_lst.dataDoc, t_lst.adDim, t_lst.cmdPU, t_lst.cmdPretOrig, t_lst.rotunjire
                                         ORDER by t_lst.cantmin range between unbounded preceding and unbounded following )  as ofrPret
         from (
         select cmd1.codcomanda1 as codComanda1,
                      cmd.codcomanda as codComanda,
                      cmd.nrdoc as nrDoc,
                      cmd.datadoc as dataDoc,
                      ofr1.codoferta1 as codOferta1,
                      cmd1.addim as adDim,
                      cmd1.PU as cmdPU,
                      cmd1.pretorig as cmdPretOrig,
                      ofr1.pret as ofrPret,
                      obj.rotunjire as rotunjire,
                      ofr1.cantmin as cantmin,
                      cmd1.termen
                 from oferta ofr
                 join oferta1 ofr1
                   on ofr1.codoferta = ofr.codoferta
                 join comanda cmd
                   on cmd.partener = ofr.partener
                 join comanda1 cmd1
                   on cmd1.codcomanda = cmd.codcomanda and cmd1.codobiect = ofr1.codobiect and cmd1.cantacceptat &gt;= coalesce(ofr1.cantmin,0)
                 join npart part
                   on part.codpart = cmd.partener
                join nartobj obj on obj.codobiect = cmd1.codobiect
                where ofr.codoferta = pCodOferta
                  and cmd1.termen between ofr.datastart and
                      ofr.dataend
                  and cmd1.restacceptat &gt; 0
                  and coalesce(cmd.anulat, 0) = 0
                  and coalesce(cmd.inchisa, 0) = 0
                  and coalesce(part.preofefurnvar, 0) = 1
                  and cmd.tipdoc = 8
                 order by cmd1.codcomanda) t_lst ) l_tot
  where l_tot.cmdpretorig &lt;&gt; l_tot.ofrpret
  order by l_tot.codcomanda;
BEGIN
  --Florin 23/24.04.2025 - fixat 65459
  --Bogdan 29.09.2022 - 55428 : Oferte furnizori - data/termen
  codComandaModificata := -1;
  valDoc := 0.0;
  listaComenziModificate := '';
  listaComenziBlocate :='';
  existaComenziBLocate := false;
  it := 0;
  for v_rec in lista_comenzi
  loop
    if codComandaModificata = -1 or codComandaModificata != v_rec.codComanda then
      codComandaModificata := v_rec.codComanda;
      begin
      perform lockdoceditat('COMANDA', 'CodComanda', v_rec.codComanda, 0);
      listaComenziDeModificat[it] := v_rec.codComanda;
      it := it+1;
      exception
         when others  then
           listaComenziBlocate := listaComenziBlocate || v_rec.nrdoc ||'/'|| to_char(v_rec.datadoc,'dd.mm.yyyy')||'; ';
           existaComenziBLocate := true;
      end;
    end if;
  end loop;
  if existaComenziBLocate then
    wme_result := 'ERR#$'||listaComenziBlocate;
  else
    codComandaModificata := -1;
    for v_rec in lista_comenzi
    loop
      if codComandaModificata = -1 then
        codComandaModificata := v_rec.codComanda;
        listaComenziModificate := v_rec.nrdoc ||'/'|| to_char(v_rec.datadoc,'dd.mm.yyyy');
      else
        if codComandaModificata != v_rec.codComanda then
          select sum(pkg_oferta_roundpret(((100 + coalesce(cmd1.procdisc,0)) / 100) * cmd1.cantacceptat * cmd1.pu, obj.rotunjire)) into valDoc
          from comanda1 cmd1
          join nartobj obj on obj.codobiect = cmd1.codobiect
          where cmd1.codcomanda = codComandaModificata
                and coalesce(cmd1.anulat,0) = 0;
           update comanda cmd set valoare = valDoc where cmd.codcomanda = codComandaModificata;
          codComandaModificata := v_rec.codComanda;
          listaComenziModificate := listaComenziModificate || '; '|| v_rec.nrdoc ||'/'|| to_char(v_rec.datadoc,'dd.mm.yyyy');
        end if;
      end if ;

      vPretLinie := pkg_oferta_roundpret(((100 + coalesce(v_rec.addim,0)) / 100) * v_rec.ofrpret, v_rec.rotunjire);

      update comanda1 cmd1
         set pretorig = v_rec.ofrpret,
             pu = vPretLinie
         where cmd1.codcomanda1 = v_rec.codcomanda1;
    end loop;
    if codComandaModificata != -1 then
          select sum(pkg_oferta_roundpret(((100 + coalesce(cmd1.procdisc,0)) / 100) * cmd1.cantacceptat * cmd1.pu, obj.rotunjire)) into valDoc
          from comanda1 cmd1
           join nartobj obj on obj.codobiect = cmd1.codobiect
          where cmd1.codcomanda = codComandaModificata
                and coalesce(cmd1.anulat,0) = 0;
          update comanda cmd set valoare = valDoc where codcomanda = codComandaModificata;
     end if;
       wme_result :=  listaComenziModificate ;
  end if;
  IF (listaComenziDeModificat) IS NOT NULL THEN
    foreach it in array listaComenziDeModificat loop
      perform unlockdoceditat('COMANDA', it, current_setting('PKG_GLOBALS.USERID', true)::numeric);
    end loop;
  END IF;

end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_onorarecomenzi_get_tmp_operlivr_articole</obj_name>
  <obj_hashval>5f5400f444bd4ec3043455284301362b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_onorarecomenzi_get_tmp_operlivr_articole()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 07.03.2023 - fixat 57515
  --Florin 01.03.2023 - sinc. Oracle
  --Florin 26.08.2022 - sinc. Oracle (25.08.2022)
  --Stef 29.06.2022 - fnc_getprocenttvaart
  --Adina 18.05.2021 - sinc.Oracle din 17.05.2021 - doar martor la zi
  --Bogdan 11.02.2021
  DELETE FROM TMP_OnorCom_PrelStoc;
  DELETE FROM TMP_OnorCom_Articole;

  INSERT INTO TMP_Onorcom_Articole (CODCOMANDA1, CODCOMANDA, INDEXLOCAL, CODOBIECT,
      DENOBIECT, CODEXTERN, CODARTICOL, TERMENLIVR,
      CODUM, UMSEC, CANTCOMANDAT, CANTACCEPTAT,
      RESTLIVR, LIVRSTOC, LIVRECHIV, CODEKIV,
      DENEKIV, PARITATEEKIV, CODUMEKIV, CODUMSPEC,
      CANTSPEC, D1, D2, D3,
      RELATIEUMSPEC, RELATIEUMALT, Cantaribil, CANT,
      PRET, PRETORIG, VALOARE, ADDIM,
      PROCDISC, OBS, SCADENTA, TERMENPLATA,
      NET, BRUT, A1, A2,
      A3, A4, A5, A6,
      KGA1, KGA2, KGA3, KGA4,
      KGA5, KGA6, FlagInchidere, PROCTVA,
      RestNeglijCmd, CoefDiscMaj, Codgest, Codioart,
      TipLinie, ContServ, GestAct, den_um1)
  SELECT C1.CodComanda1, C.CodComanda, c1.IndexLocal, C1.CodObiect,
    NAO.Denumire, NAO.CodExtern, NA.CODARTICOL, C1.Termen,
    NA.UM, C1.UMSec, C1.CantComandat, C1.CantAcceptat,
    C1.RestAcceptat, 0, 0, 0,
    ' ', 1, 0, NA.UM1,
    C1.CantUM1, C1.D1, C1.D2, C1.D3,
    NA.RelatieUM1, NA.RelatieUM2,
    CASE WHEN U.TipUM = 1 AND COALESCE (U.Coef, 0) &lt;&gt; 0 THEN 1 ELSE 0 END ,
    0, case when c.pretcuamanunt = 1 then C1.PU / (1 + (SELECT wme_result FROM PKG_SELECTARTICOLE_GETPROCENTTVA(NULL, NAO.CodArticol, GETANLUCRU(),GETLUNALUCRU())) / 100) else c1.pu end,
    C1.PRETORIG,
    0, C1.AdDim, C1.ProcDisc, C1.Obs,
    C1.Scadenta, NAO.TermenPlata, 0, 0,
    0, 0, 0, 0,
    0, 0, 0, 0,
    0, 0, 0, 0,
    0,
    fnc_getprocenttvaart(NAO.CodArticol, current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric, current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric) ,
    COALESCE (NA.RestNeglijCmd, 0.01) , CoefDiscMaj, IMP.GESTIMPLICITA,
    IMP.CONTIMPLICIT,
    CASE WHEN NA.TIPARTICOL = '0' THEN '=' ELSE 'S' END TIPLINIE,
    CASE WHEN NA.TIPARTICOL = '1' THEN NA.ContServiciu ELSE NULL END CONTSERV,
    CASE WHEN NA.TIPARTICOL = '1' THEN Coalesce (NullIF (C1.GestAct, 0) , IMP.GESTIMPLICITA) ELSE NULL END GESTACT,
    num1.den_um1
  FROM Comanda                 C
      INNER JOIN Comanda1      C1  ON C1.CodComanda  = C.CodComanda
      INNER JOIN NArtObj       NAO ON NAO.CodObiect  = C1.CodObiect
      INNER JOIN NArt          NA  ON NA.CodArticol  = NAO.CodArticol
      INNER JOIN NUM           U   ON U.CodUM        = NA.UM
      LEFT  JOIN NARTIMPLICITE IMP ON IMP.CODARTICOL = NA.CODARTICOL AND IMP.CODSUBUNIT = C.SUBUNITATEA
      LEFT  JOIN NUM1              ON NUM1.CODUM1    = C1.UMSEC
  WHERE
    C.TipDoc IN (18, 43, 44)  -- doar comenzi clienti, comenzi de la gestiuni, comenzi de la subunitati
    AND C.UserIDBlocaj = current_setting ('PKG_GLOBALS.UserID', true)::numeric
    AND C1.RESTACCEPTAT &gt; 0
    AND (current_setting ('PKG_ONORARECOMENZI.pFlagTermLivr', true)::numeric = 0
         OR
         COALESCE (C1.Termen, (to_date(current_setting ('PKG_ONORARECOMENZI.pDataSys', true),'dd.mm.yyyy'))) BETWEEN to_date( current_setting ('PKG_ONORARECOMENZI.pDataTermLivrDeLa', true),'dd.mm.yyyy') AND to_date( current_setting ('PKG_ONORARECOMENZI.pDataTermLivrPanaLa', true),'dd.mm.yyyy')
        )
    AND (current_setting ('PKG_ONORARECOMENZI.pFlagClaseArt', true)::numeric = 1
         OR
         COALESCE (NA.Clasa, 0) IN (SELECT Valoare::NUMERIC FROM TMP_MANEVRA_LISTE WHERE UPPER (Filtru) = 'CODCLASEA')
    AND COALESCE(C1.MODINCHIDERE,0) = 0
    AND (aRez = 0 or exists (select r.codrezervats from rezervats r where r.codcomanda1 = c1.codcomanda1 and r.rest &gt; 0)));
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_onorarecomenzi_setpdatasys</obj_name>
  <obj_hashval>401f80b334cfa5e3252315d1239c68ff</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_onorarecomenzi_setpdatasys(apdatasys date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_ONORARECOMENZI.pDataSys',apDataSys,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_onorarecomenzi_setpdatatermlivr</obj_name>
  <obj_hashval>6bc4208754e445c334899a03b7ebdd8f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_onorarecomenzi_setpdatatermlivr(apdatatermlivr date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_ONORARECOMENZI.pDataTermLivr',apDataTermLivr,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_onorarecomenzi_setpflagclaseart</obj_name>
  <obj_hashval>98ea1aecf27170aea5472e1231c03df7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_onorarecomenzi_setpflagclaseart(apflagclaseart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_ONORARECOMENZI.pFlagClaseArt',to_char(apFlagClaseArt,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oportunitati_setnrdoc_i</obj_name>
  <obj_hashval>62842ffa4d520b7bd8f8af95bb11a673</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oportunitati_setnrdoc_i(anrdoc numeric, acarnet numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_OPORTUNITATI.CARNETDOC_I',to_char(ACARNET,'999999999999999999'),false);
  perform set_config('PKG_OPORTUNITATI.NRDOC_I',to_char(ANRDOC,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_opreg_sp_insertrecord</obj_name>
  <obj_hashval>755b617d358bf831daa8efb206daf46a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_opreg_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_OPREG(CodOp) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pachete_setct_monitor</obj_name>
  <obj_hashval>342800070b9d5beb51e71e63f1e98b74</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pachete_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PACHETE.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconttert_getg_codcontrult</obj_name>
  <obj_hashval>9ee73e14e1f9fb17a5a605f8998b27d1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconttert_getg_codcontrult(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANCONTTERT.g_CodContRulT', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconttert_getg_codcontsoldt</obj_name>
  <obj_hashval>35d694361fc8e0a18f8d2bf8265436a2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconttert_getg_codcontsoldt(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANCONTTERT.g_CodContSoldT', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_contechivalent</obj_name>
  <obj_hashval>097e73a5356f0245491d04a18465b2a7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_contechivalent(INOUT wme_result numeric, INOUT acodcont numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  Res numeric := 0;
begin
  --Bogdan 09.02.2021
  SELECT COALESCE (MIN (CONTNOU) , aCODCONT)
  INTO RES
  FROM NCONTECHIV
  WHERE CONTVECHI = aCODCONT AND AN = current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric;

  WME_Result := RES;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_echiv_contserv_intrari1</obj_name>
  <obj_hashval>b312c43c74cfafca517b7c03d4afb47b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_echiv_contserv_intrari1()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN (SELECT E.CONTVECHI, I1.CODINTR1, I.CODINTR, I.TIPDOC, MIN( E.CONTNOU) AS CONTNOU
                FROM NCONTECHIV E, INTRARI1 I1, INTRARI I
                WHERE E.AN = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') AND  I1.CODINTR = I.CODINTR AND  I.AN = E.AN AND  I1.CONTSERV = E.CONTVECHI
                GROUP BY E.CONTVECHI, I1.CODINTR1, I.CODINTR, I.TIPDOC
               )
  LOOP
    UPDATE INTRARI1 SET CONTSERV = V_REC.CONTNOU WHERE CODINTR1 = V_REC.CODINTR1;
    UPDATE JURNAL1  SET DIRTY = 1 WHERE TIPDOC = V_REC.TIPDOC AND  CODDOC = V_REC.CODINTR AND  AN = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999');
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_getsimbolcont</obj_name>
  <obj_hashval>4b9b49033e007b6e296f216ba6a95011</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_getsimbolcont(INOUT wme_result character varying, INOUT cont numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aSimbol varchar := '???';
begin
  BEGIN
    SELECT SIMBOL INTO aSimbol FROM NCONT WHERE CODCONT = CONT;
  EXCEPTION WHEN OTHERS THEN
    WME_Result :=  aSimbol;
    RETURN;
  END;

  WME_Result :=  aSimbol;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_initializari</obj_name>
  <obj_hashval>3862876d5ccad597066b7721d807446f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_initializari(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANCONTURI.INITIALIZARI', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plancurs_sp_gotorecord</obj_name>
  <obj_hashval>b4628fc28d6773e87478ff3cab9e1c8f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plancurs_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_PlanCurs(CodPlanCurs, CODPERS, NR, DataCurs, TIP, AN, LUNA)
  (SELECT CodPlanCurs, CODPERS, NR, DataCurs, TIP, AN, LUNA FROM PlanCurs WHERE CodPlanCurs = RecId);

  INSERT INTO TMP_PlanCurs1(CodPlanCurs1, CodPlanCurs, CodTema, DataPlan, Stare)
  (SELECT CodPlanCurs1, CodPlanCurs, CodTema, DataPlan, Stare FROM PlanCurs1 WHERE CodPlanCurs = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plancurs_sp_lockrecord</obj_name>
  <obj_hashval>931c0b8f3fcde4ffcd4056be8ea8cb48</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plancurs_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodPlanCurs INTO Tmp FROM PlanCurs WHERE CodPlanCurs = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_genereazastare</obj_name>
  <obj_hashval>f3771e8b9642eabae22299585b35dc7f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_genereazastare(aan numeric, aset numeric, acodoferta numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V     RECORD;
  V_REC RECORD;
  aAnG         numeric;
  aSetG        numeric;
  aDataCreare  timestamp;
  aSubunitatea numeric;
  aUserId      numeric;
  aCodStare    numeric;
BEGIN
  --Florin 30.09.2022 - sinc. Oracle
  --Adina 19.04.2021 - sinc.Oracle din 19.04.2021
  PERFORM PKG_STOC_GENERARE_FACTURI_MAKE_CONFIG_LUNA();

  aAnG         := aAn;
  aSetG        := aSet;
  aDataCreare  := CURRENT_TIMESTAMP;
  aSubunitatea := current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric;
  aUserID      := current_setting ('PKG_GLOBALS.USERID', true) ::numeric;

  IF (SELECT WME_RESULT
      FROM winmadmin.PKG_USERFIRME_ValidPostLog (NULL,current_setting ('PKG_GLOBALS.USERID', true) ::numeric, current_setting ('PKG_PLANIFCMD.CT_MONITOR', true)))
  THEN
    PERFORM winmadmin.pkg_userfirme_postlogcucommit ('STAREESTIMARI',
                                                     current_setting ('PKG_GLOBALS.USERNAME', true) ,
                                                     'A',
                                                     aAn * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip (NULL,aAn)) + aSet,
                                                     current_setting ('PKG_GLOBALS.FIRMANAME', true) ,
                                                     current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric,
                                                     aDataCreare,
                                                     coalesce (aSet,'') || '/' || coalesce (aAn::varchar,'') ,
                                                     coalesce (aSet::varchar,'') || '/' || coalesce (aAn::varchar,'') ,
                                                     current_setting ('PKG_GLOBALS.EXE_VERSION', true));
  END IF;

  PERFORM PKG_PLANIFCMD_UmpleTemporarGenerator (aAn * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip (NULL,aAn)) + aSet,
                                                aUserID, aSubunitatea);

  DELETE FROM TMP_PLANIFCMDMAT WHERE userid = aUserID;

  INSERT INTO TMP_PLANIFCMDMAT (CODOBIECT, STOC, STOCMIN, PRET, USERID)
  SELECT  DISTINCT obj.codobiect CODOBIECT, stoc.cant STOC, osub.stocmin STOCMIN, o1.pret, aUserID
  FROM nartobj                obj
    LEFT  JOIN nartobjsubunit osub ON  osub.codobiect = OBJ.codobiect
                                   and ( osub.codgest is null or osub.codgest = 0)
                                   and osub.subunitate = aSubunitatea
           left join (select sum(case when nir.operat = 0 then ns.cantnir else ns.rest end) cant, ns.codobiect
                FROM nirstoc       ns
                  INNER JOIN nir     ON nir.codnir = ns.codnir
                  INNER JOIN ngest g ON g.codgest  = nir.gest
                where g.codsubunit = GETSUBUNITATE() and ((ns.rest &lt;&gt; 0 and nir.operat = 1) or (ns.rest = 0 and nir.operat = 0 and nir.tipnir = 12)) and g.tip &lt;&gt; 4
                GROUP BY ns.codobiect
              ) stoc   ON stoc.codobiect = obj.codobiect
    LEFT  JOIN OFERTA1         O1    ON O1.CODOFERTA      = aCodOferta     AND O1.Codobiect   = obj.Codobiect,
    nart art
    INNER JOIN NARTIMPLICITE  IMP    ON ART.CODARTICOL    = IMP.CODARTICOL AND IMP.CODSUBUNIT = aSubunitatea
    INNER JOIN TMP_IOART_LUNA IOLUNA ON IOLUNA.CODIOART   = IMP.CONTIMPLICIT
    INNER JOIN CONSTVAL       CV     ON TRIM (CV.VALOARE) = TRIM ( (IOLUNA.CONT) ::varchar)
    INNER JOIN CONSTLUNA      CL     ON CV.CODCONSTLUNA   = CL.CODCONSTLUNA
    INNER JOIN CONST1         CS1    ON CS1.CODCONST1     = CL.CODCONST1
  WHERE
    COALESCE (obj.produspropriu, 0) = 0
    and obj.codarticol = art.codarticol
    and COALESCE (art.tiparticol, '0') = '0'
    and UPPER (CS1.SIMBOL) = 'GENCMDFCONTURI';

  FOR V IN (SELECT tmp.codobiect CODOBIECT, osub.stocmin STOCMIN, O1.PRET PRET, STOC.CANT CANT
            FROM TMP_CMDTL             tmp
              LEFT JOIN nartobjsubunit osub ON  osub.codobiect = tmp.codobiect
                                            and (osub.codgest is null or osub.codgest = 0)
                                            and osub.subunitate = aSubunitatea
              LEFT JOIN OFERTA1        O1   ON O1.CODOFERTA = aCodOferta and O1.Codobiect = TMP.Codobiect
              LEFT JOIN ( SELECT sum (ns.rest) CANT, ns.codobiect
                          FROM nirstoc               ns
                            INNER JOIN nir     ON nir.codnir = ns.codnir
                            INNER JOIN ngest g ON g.codgest = nir.gest
                          WHERE
                            g.codsubunit = current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric
                            and ns.rest &lt;&gt; 0
                            and g.tip &lt;&gt; 4
                          GROUP BY ns.codobiect
                        ) stoc ON stoc.codobiect = TMP.codobiect
            WHERE
              tmp.tip IN (1, 2)
              and tmp.userid = current_setting ('PKG_GLOBALS.USERID', true) ::NUMERIC
           )
  LOOP
    INSERT INTO TMP_PLANIFCMDMAT (CODOBIECT, STOC, STOCMIN, PRET, USERID)
    VALUES (V.CODOBIECT, V.CANT, V.STOCMIN, V.PRET, aUserID);
  END LOOP;

  FOR v_rec IN (SELECT sum (COALESCE (se1.estimat, 0)) ESTIMAT,
                       sum (COALESCE (se1.stocmin, 0)) STOCMIN,
                       sum (COALESCE (se1.stocini, 0)) STOCINI,
                       sum (COALESCE (se1.cmdf, 0)) CMDF,
                       se1.codobiect
                FROM stareestimari se INNER JOIN stareestimari1 se1 ON se.codstare = se1.codstare
                WHERE
                  se.an = aAn
                  and se.saptamana = aSet
                  and se.subunitatea = aSubunitatea
                GROUP BY se1.codobiect
               )
  LOOP
    IF v_rec.estimat    = 0
      and v_rec.stocmin = 0
      and v_rec.stocini = 0
      and v_rec.cmdf    = 0
    THEN
      DELETE FROM stareestimari1 se1
      WHERE
        se1.codobiect = v_rec.codobiect
        and EXISTS (SELECT se.codstare
                    FROM stareestimari se
                    WHERE
                      se.codstare = se1.codstare
                      and se.an = aan
                      and se.saptamana = aset
                      and se.subunitatea = aSubunitatea);
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_setvallgest</obj_name>
  <obj_hashval>a5256de5071e2645d1642840836a763d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_setvallgest(avallgest numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANIFPRODLUN.vAllGest',to_char(avAllGest,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_setvallioart</obj_name>
  <obj_hashval>46d3bd103216d482e96549df6bdfef0b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_setvallioart(avallioart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANIFPRODLUN.vAllIOArt',to_char(avAllIOArt,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_vanlunafin</obj_name>
  <obj_hashval>b5164d6f364dee7575ef46486916d30d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_vanlunafin(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANIFPRODLUN.vAnLunaFin', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_vanlunaini</obj_name>
  <obj_hashval>95b196ea50a42c4ac86acd0d68b85fcd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_vanlunaini(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANIFPRODLUN.vAnLunaIni', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_vcodgest</obj_name>
  <obj_hashval>498d0d67c472a417b4d9a0443454b28d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_vcodgest(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PLANIFPRODLUN.vCodGest', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plati_sp_insertrecord</obj_name>
  <obj_hashval>fd379db8a68ab18ddd8432eff4252da8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plati_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 19.11.2024 - sinc. Oracle
  INSERT INTO TMP_PLATI(CODPLATA) VALUES(0);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(105);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plati_sp_lockrecord</obj_name>
  <obj_hashval>38e378a575160b2af23a3c8c990a7eb2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plati_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CODPLATA INTO Tmp FROM PLATI WHERE CODPLATA = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_getg_pmp_last_val</obj_name>
  <obj_hashval>47e2169c5ff0497080f48366740391c2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_getg_pmp_last_val(INOUT wme_result double precision, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PMP.G_PMP_LAST_VAL', true)),'99999999999.9999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_getg_pmp_prec_val</obj_name>
  <obj_hashval>7fe945db07285c1453fefccbe3d7608e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_getg_pmp_prec_val(INOUT wme_result double precision, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PMP.G_PMP_PREC_VAL', true)),'99999999999.9999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_getg_pmp_valuta</obj_name>
  <obj_hashval>c1f45526c79985e16d708d33d19bcfd5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_getg_pmp_valuta(INOUT wme_result double precision, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PMP.G_PMP_VALUTA', true)),'99999999999.9999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_postretail_prepare_temp_preturi</obj_name>
  <obj_hashval>e957df5fc3c82a52be5036a7c3feaf1a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_postretail_prepare_temp_preturi(acodpostretail numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  DELETE FROM TMP_NART;
  DELETE FROM TMP_NTAXE;
  DELETE FROM TMP_NART1;
  DELETE FROM TMP_NARTOBJ;
  DELETE FROM TMP_NARTOBJ1;
  DELETE FROM TMP_NUM;
  DELETE FROM TMP_NUM1;
  DELETE FROM TMP_PRETM;
  DELETE FROM TMP_PRETMAMB;
  DELETE FROM TMP_NCATPRET;

  FOR V_REC IN (SELECT S.*, A.CODARTICOL, A.UM, P.SUBUNITATEA
                FROM SYNCPRETRETAIL S, NARTOBJ O, NART A, POSTRETAIL P
                WHERE CODPOSTRETAIL = aCODPOSTRETAIL AND  O.CODOBIECT = S.CODOBIECT AND  A.CODARTICOL = O.CODARTICOL AND  P.COD = aCODPOSTRETAIL AND  COALESCE( S.SINCRONIZAT, 0) = 0
               )
  LOOP
    INSERT INTO TMP_NART(CODARTICOL, DEN_ARTICOL, TIPARTICOL, UM, TIPSERIE, ARETG, CONTSERVICIU, CASADEMARCAT, CODEXTERNART, SUFIXCODEXTERN)
    SELECT CODARTICOL, DEN_ARTICOL, TIPARTICOL, UM, TIPSERIE, ARETG, CONTSERVICIU, CASADEMARCAT, CODEXTERNART, SUFIXCODEXTERN
    FROM NART WHERE CODARTICOL = V_REC.CODARTICOL;

    INSERT INTO TMP_NARTOBJ(CODOBIECT, CODARTICOL, CODEXTERN, CODINTERN, ROTUNJIRE, PROMOTIE, DENUMIRE, BLOCAT, INACTIV)
    SELECT CODOBIECT, CODARTICOL, CODEXTERN, CODINTERN, ROTUNJIRE, PROMOTIE, DENUMIRE, BLOCAT, INACTIV
    FROM NARTOBJ WHERE CODOBIECT = V_REC.CODOBIECT;

    INSERT INTO TMP_PRETM(CODPRETM, CODOBIECT, CODCATPRET, LEI, VALUTA, MONEDA, IMPLICIT, PROC, INDEXLOCAL, SUBUNITATEA)
    SELECT CODPRETM, CODOBIECT, CODCATPRET, LEI, VALUTA, MONEDA, IMPLICIT, PROC, INDEXLOCAL, SUBUNITATEA
    FROM PRETM WHERE CODOBIECT = V_REC.CODOBIECT AND  SUBUNITATEA = V_REC.SUBUNITATEA AND  CODCATPRET = V_REC.CODCATPRET;
  END LOOP;

  INSERT INTO TMP_PRETMAMB(CODPRETMAMB, CODPRETM, CODAMB, LEI, VALUTA)
  SELECT CODPRETMAMB, CODPRETM, CODAMB, LEI, VALUTA FROM PRETMAMB WHERE CODPRETM IN (SELECT CODPRETM FROM TMP_PRETM);

  INSERT INTO TMP_NUM(CODUM, DEN_UM, TIP, ZECIMALE, TIPUM, COEF)
  SELECT CODUM, DEN_UM, TIP, ZECIMALE, TIPUM, COEF FROM NUM WHERE CODUM IN (SELECT UM FROM TMP_NART);

  INSERT INTO TMP_NUM1(CODUM1, CODUM, SECUNDARA, DEN_UM1, PARITATE, ZECIMALE, OBS, CODEXTERN)
  SELECT CODUM1, CODUM, SECUNDARA, DEN_UM1, PARITATE, ZECIMALE, OBS, CODEXTERN FROM NUM1 WHERE CODUM IN (SELECT UM FROM TMP_NART);

  INSERT INTO TMP_NART1(CODARTICOL1, CODARTICOL, CODTVA, CODACCIZE, CODTAXA1, CODTAXA2, ANSTART, LUNASTART)
  SELECT CODARTICOL1, CODARTICOL, CODTVA, CODACCIZE, CODTAXA1, CODTAXA2, ANSTART, LUNASTART FROM NART1 WHERE CODARTICOL IN (SELECT CODARTICOL FROM TMP_NART);

  INSERT INTO TMP_NTAXE(CODTAXA, DEN_TAXA, CENTRALIZAT)
  SELECT CODTAXA, DEN_TAXA, CENTRALIZAT FROM NTAXE WHERE CODTAXA IN (SELECT CODACCIZE FROM TMP_NART1) or CODTAXA IN (SELECT CODTAXA1 FROM TMP_NART1) or CODTAXA IN (SELECT CODTAXA2 FROM TMP_NART1);

  INSERT INTO TMP_NARTOBJ1(CODOBIECT1, CODOBIECT, PRETMAXIMAL, PROCADAOSMAXIMAL, ADAOSLA, ANSTART, LUNASTART, PRETREFERINTA, TIPPRETMAX, COMPENSAT, TIPCOMPENSARE, GRUPA)
  SELECT CODOBIECT1, CODOBIECT, PRETMAXIMAL, PROCADAOSMAXIMAL, ADAOSLA, ANSTART, LUNASTART, PRETREFERINTA, TIPPRETMAX, COMPENSAT, TIPCOMPENSARE, GRUPA
  FROM NARTOBJ1 WHERE CODOBIECT IN (SELECT CODOBIECT FROM TMP_NARTOBJ);

  INSERT INTO TMP_NCATPRET(CODCATPRET, DEN_CATPRET, TIP, SIMBOL)
  SELECT CODCATPRET, DEN_CATPRET, TIP, SIMBOL FROM NCATPRET WHERE CODCATPRET IN (SELECT CODCATPRET FROM TMP_PRETM);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prestatii_sp_insertrecord</obj_name>
  <obj_hashval>276367175794a6d256539c2d41915362</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prestatii_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  INSERT INTO TMP_PRESTATII (CODPRESTATIE) VALUES (0) ;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_getpretnirstoc1mat</obj_name>
  <obj_hashval>de21fa108c0af6c34857afa928d55b67</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_getpretnirstoc1mat(INOUT wme_result numeric, INOUT acodnirstoc numeric, INOUT curesetmanevra boolean DEFAULT true)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  aPredat numeric;
  aValMat numeric;
  aPret   numeric;
  aCount  numeric;
begin
  -- Bogdan corectat pkg_pretprod_getpretnirstoc1mat.wme_result is ambiguous
  IF CuResetManevra THEN
    DELETE FROM tmp_manevra2;
  END IF;

  aPredat := 0;
  aValMat := 0;

  FOR v_rec IN (SELECT predat.cant PREDAT, COALESCE(l1.cant, 0) CANTLIVR, COALESCE(ns1.pretmat, 0) PU, COALESCE(nsi.pret, 0) - COALESCE(nsi.adaos, 0) PUNS, COALESCE(ns1.tipdoc, 0) TIPDOC, COALESCE(ns1.dirty, 1) DIRTY, nsi.codnirstoc
                FROM nirstoc1 nsp
                INNER JOIN nirstoc    ns   ON  ns.codnirstoc    = nsp.codnirstocorig
                INNER JOIN intrari1   i1   ON  i1.codintr1      = ns.codintr1
                INNER JOIN cmdprodmat prod ON  prod.codcomanda1 = i1.codcmdint1 and  COALESCE(prod.tip, 0) = 0
                INNER JOIN (SELECT sum(i1.cant) CANT, i1.codcmdint1
                            FROM intrari1 i1 INNER JOIN intrari i ON  i1.codintr = i.codintr
                            WHERE i1.codcmdint1 &gt; 0 and  COALESCE(i.anulat, 0) = 0 and  COALESCE(i.operat, 0) = 1
                            GROUP BY i1.codcmdint1
                           ) predat ON  predat.codcmdint1    = prod.codcomanda1
                INNER JOIN iesiri1  ies1 ON  ies1.codcmdint1 = prod.codcomanda1
                INNER JOIN iesiri   ies  ON  ies.codies      = ies1.codies
                INNER JOIN livr     l    ON  l.codies        = ies.codies
                INNER JOIN livr1    l1   ON  l1.codies1      = ies1.codies1 and  l.codlivr = l1.codlivr
                INNER JOIN nirstoc  nsi  ON  nsi.codnirstoc  = l1.codnirstoc
                LEFT  JOIN nirstoc1 ns1  ON  ns1.codnirstoc  = nsi.codnirstoc
                WHERE
                   COALESCE(ies.anulat, 0) = 0 and  COALESCE(ies.operat, 0) = 1 and  nsp.codnirstoc = aCodNirStoc
               )
  LOOP
    aPredat := v_Rec.Predat;
    SELECT count(*) INTO acount FROM tmp_manevra2 WHERE codunic = v_rec.codnirstoc;
    IF  acount &gt; 0 THEN
      aValMat := aValMat + v_Rec.cantlivr * v_rec.pu;
    ELSE
      INSERT INTO tmp_manevra2(codunic) VALUES(v_Rec.Codnirstoc);

      IF  v_rec.tipdoc = 7 and  v_Rec.dirty = 1 THEN
        aValMat := aValMat + v_Rec.cantlivr * (SELECT innerSql.WME_RESULT FROM PKG_PRETPROD_GetPretNirStoc1Mat(NULL,v_rec.codnirstoc, false) as innerSql);
      ELSE
        IF  v_rec.tipdoc = 7 and  v_Rec.dirty = 0 THEN
          aValMat := aValMat + v_Rec.cantlivr * v_rec.pu;
        ELSE
          IF  v_Rec.dirty = 1 THEN
            aValMat := aValMat + v_Rec.cantlivr * v_rec.puns;
          ELSE
            aValMat := aValMat + v_Rec.cantlivr * v_rec.pu;
          END IF;
        END IF;
      END IF;
    END IF;
  END LOOP;

  IF  aPredat = 0 THEN
    aPret := 0;
  ELSE
    aPret := aValMat / aPredat;
  END IF;

  WME_Result :=  aPret;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proc_act_date_sp_lockrecord</obj_name>
  <obj_hashval>59ae91acdcb34c5d89f470eb46eb1b3e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proc_act_date_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  null;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_aduvaloaremateriale</obj_name>
  <obj_hashval>7c734a252a3be95b83642e619207e1d6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_aduvaloaremateriale(INOUT wme_result numeric, INOUT acodprodcomp numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aVal numeric;
begin
  aVal := 0;
  BEGIN
    SELECT sum(CASE WHEN COALESCE(mat.tip, 3) IN (3, 5) or  COALESCE(mat.valmat, 0) = 0 THEN COALESCE(mat.cant, 0) * COALESCE(mat.pret, 0)
                    ELSE COALESCE(mat.cant, 0) * COALESCE(mat.valmat, 0)
               END )
    INTO aVal
    FROM prodmat mat
    INNER JOIN prodcomp pc ON  pc.codprodcomp = mat.codprodcomp
    INNER JOIN prodgest pg ON  pc.codprodcomp = pg.codprodcomp and  mat.codprodgest = pg.codprodgest
    WHERE
       pc.codprodcomp = aCodProdComp;
  EXCEPTION WHEN others THEN
    aVal := 0;
  END;

  WME_Result :=  aVal;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getktipcoefindirecte</obj_name>
  <obj_hashval>78a8e266cb09d7ac28576f5c8bcb12e1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getktipcoefindirecte(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PRODCOMP.KTipCoefIndirecte', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getvdatamin</obj_name>
  <obj_hashval>038e279db0f4001c7a6d66a76b0993cb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getvdatamin(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_PRODCOMP.vDataMin', true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_setvtipfiltru</obj_name>
  <obj_hashval>cf9e5acd4d69084c15a51c877a1d724d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_setvtipfiltru(avtipfiltru numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PRODCOMP.vTipFiltru',avTipFiltru::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodnet_sp_insertrecord</obj_name>
  <obj_hashval>6806d0121256001a9aaf1663cd249da6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodnet_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_prodnet (codprodnet) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_setcarnetdoc_i</obj_name>
  <obj_hashval>15d67c1902e94c510cecf73794da7b9f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_setcarnetdoc_i(acarnetdoc_i numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PROGRAMF.CARNETDOC_I',aCARNETDOC_I::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_updatepfmanevra_xx</obj_name>
  <obj_hashval>5264d1e3d6d888c402fc1449bb861b0f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_updatepfmanevra_xx(ddela character varying, dpanala character varying, odela character varying, opanala character varying, vtipdurata numeric, dcodprogramf numeric, vallgest numeric, valltipcont numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM tmp_programf_manevra;
  INSERT INTO tmp_programf_manevra(codprogramf, vdela, vpanala, vdelaora, vpanalaora, tipdurata, AllGest, AllTipCont)
  VALUES(dCodProgramf, to_date(dDela, 'DD.MM.YYYY'), to_date(dPanaLa, 'DD.MM.YYYY'), to_date(oDeLa, 'HH24'), to_date(oPanaLa, 'HH24'), vTipDurata, vAllGest, vAllTipCont);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_getcopilmaxim</obj_name>
  <obj_hashval>3cd7ab6c1067c400ce3ec8b378eaecb4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_getcopilmaxim(anod numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  x     numeric;
  y     numeric;
BEGIN
  --Florin 04.11.2020 - fixat #40630
  SELECT CopilMaxim INTO x FROM Tmp_Proiectman WHERE CodProiectNod = aNod;

  IF  x = -1 THEN
    x := 0;
    FOR v_rec IN (SELECT * FROM Tmp_Proiectman WHERE NodOriginal = aNod) LOOP
      y := pkg_proiect_getcopilmaxim(v_rec.CodProiectNod) + v_rec.Durata;
      IF  y &gt; x THEN
        x := y;
      END IF;
    END LOOP;

    UPDATE tmp_proiectman
    SET
    copilmaxim = x,
    DurataNod  = Durata + x
    WHERE
     CodProiectNod = aNod;
  END IF;

  RETURN x;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_getnecesar</obj_name>
  <obj_hashval>2c60509cff3f3e92f579f3ff2d27fc99</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_getnecesar(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  current_setting('PKG_PROIECT.vNecesar', true)::numeric;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_setvcodproiect</obj_name>
  <obj_hashval>be2e4a300517c7a64227626adcaed2f4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_setvcodproiect(avcodproiect numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PROIECT.vCodProiect',avCodProiect::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_rez_fill_rac_tables</obj_name>
  <obj_hashval>a3bdda46df186aed5e642b1f2aabad27</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_rez_fill_rac_tables()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  IndGrupa    numeric;
  DATAPORNIRE timestamp;
BEGIN
  --Adina 16.08.2021 - sinc.Oracle
  perform set_config('PKG_RAC_REZ.DATAPORNIRE',to_char(CURRENT_TIMESTAMP, 'DD.MM.YYYY hh24:mi:ss'),false);
  perform set_config('PKG_RAC_REZ.IsDataCuOra',(1)::varchar                                       ,false);

  DATAPORNIRE := CURRENT_TIMESTAMP;
  IndGrupa    := (SELECT PKG_RAC_REZ_IndexGrupaAuto.WME_RESULT FROM PKG_RAC_REZ_IndexGrupaAuto(NULL,NULL));

  DELETE FROM RAC_CARS;
  DELETE FROM RAC_AUTO_CEN;
  DELETE FROM RAC_AUTO;
  DELETE FROM RAC_Transfer;
  DELETE FROM RAC_EMU;

  INSERT INTO RAC_CARS
  SELECT P.CodNParcAut CODAUTO, NPG.Data, Coalesce(NPG.CodGest, 0) CODGEST, NG.Den_Gest GESTIUNE, NG.Codsubunit SUBUNITATE, NG.CodClasa,
         Coalesce(NPG.Status, 0) INACTIV, Coalesce(P.Extern, 0) EXTERN, P.CodArt CODOBIECT, P.Nrinreg NRAUTO, Ma.Marca, Mo.Model, P.AnF,
         Coalesce(G.CodGrEchiv, 0) CODGRECHIV, Coalesce(G.IND, 0) IND, G.DENUMIRE CLASA, Coalesce(E.Generic, 0) GENERIC
  FROM NParcAut P
      INNER JOIN (SELECT CodNParcAut, Max(DATA) AS DATA
                  FROM NParcG
                  WHERE Data &lt;= DATAPORNIRE
                  GROUP BY CodNParcAut
                 )           xNPG ON  xNPG.CodNParcAut = P.CodNParcAut
      INNER JOIN NParcG      NPG  ON  NPG.CodNParcAut  = xNPG.CodNParcAut and  NPG.Data = xNPG.Data
      LEFT  JOIN NEchiv      E    ON  E.Codobiect      = P.CodArt
      LEFT  JOIN GrEchiv     G    ON  G.CODGRECHIV     = E.CodGrupa
      LEFT  JOIN Nmodeleauto Mo   ON  Mo.CODMODELEAUTO = p.Model
      LEFT  JOIN Nmarciauto  Ma   ON  Ma.CODMarciAuto  = p.Marca
      LEFT  JOIN NGest       NG   ON  NG.CODGEST       = NPG.CodGest;

  INSERT INTO RAC_Transfer
  SELECT R.CodGestSursa, R.CodGestDest, COALESCE(C.MijlTransp, 0) CODAUTO, R.DataStart, R.DataStop, R.DataPred
  FROM RAC_REZ R INNER JOIN Comanda c ON  R.codcomanda = c.codcomanda
  WHERE  COALESCE(C.Operat, 0) = 1
    and  COALESCE(R.Predat, 0) = 1
    and  R.CodGestSursa &lt;&gt; R.CodGestDest
    and  DATAPORNIRE &gt; R.DataPred
  union ALL
  SELECT X.CodGestDest CODGESTSURSA, R.CodGestSursa CODGESTDEST, COALESCE(C.MijlTransp, 0) CODAUTO, R.DataStart, R.DataStop, R.DataPred
  FROM RAC_REZ R
      INNER JOIN Comanda c  ON  R.codcomanda  = c.codcomanda
      INNER JOIN Comanda XX ON  XX.codcomanda = R.CodRezervare
      INNER JOIN Rac_Rez X  ON  X.codcomanda  = XX.codcomanda
  WHERE  COALESCE(C.Operat, 0) = 1
    and  COALESCE(R.Predat, 0) = 1
    and  COALESCE(R.CodRezervare, 0) &gt; 0
    and  COALESCE(XX.Mijltransp, 0) = COALESCE(C.Mijltransp, 0)
    and  R.CodGestSursa &lt;&gt; R.CodGestDest
    and  DATAPORNIRE &gt; R.DataPred;

  INSERT INTO RAC_AUTO
  WITH
  PTransf AS
  (SELECT CodCmd, CodNparcAut CODAUTO, Data, CodGest, CodGestIni CODGESTPREC
   FROM NParcG
   WHERE COALESCE(CodGest, 0) &gt; 0 and  COALESCE(CodCmd, 0) = 0
  ),
  Cars AS
  (SELECT COALESCE(CodGest, 0) CODGEST, CodNParcAut CODAUTO, CodArt CODOBIECT
   FROM NPArcAut
   WHERE COALESCE(Extern, 0) = 0 and  COALESCE(CodGest, 0) &gt; 0
  )
  SELECT X.CodAuto, X.CodObiect, X.CodGest, X.Transferat, X.Q, X.DataStart, X.DataStop, GG.CodClasa
  FROM (
        SELECT T.CodAuto, C.CodObiect, T.CodGestSursa CODGEST, 1 TRANSFERAT, -1 Q, T.DataStart, T.DataStop
        FROM v_rac_Transfer T INNER JOIN Cars C ON  C.CodAuto = T.CodAuto
        union ALL
        SELECT T.CodAuto, C.CodObiect, T.CodGestDest CODGEST, 1 TRANSFERAT, +1 Q, T.DataStart, T.DataStop
        FROM v_rac_Transfer T INNER JOIN Cars C ON  C.CodAuto = T.CodAuto
        union ALL
        SELECT T.CodAuto, C.CodObiect, T.CodGestPrec CODGEST, 0 TRANSFERAT, -1 Q, T.Data DATASTART, T.Data DATASTOP
        FROM PTransf T INNER JOIN Cars C ON  C.CodAuto = T.CodAuto
        WHERE T.CodGestPrec &lt;&gt; 0
        union ALL
        SELECT T.CodAuto, C.CodObiect, T.CodGest, 0 TRANSFERAT, +1 Q, T.Data DATASTART, T.Data DATASTOP
        FROM PTransf T INNER JOIN Cars C ON  C.CodAuto = T.CodAuto
       ) X
         INNER JOIN NGEST GG ON  GG.CodGest = X.CodGest;

  INSERT INTO RAC_AUTO_CEN
  (
  SELECT CODAUTO, CODGEST, Q
  FROM (SELECT CodAuto, CodGest, Sum(Q) Q FROM RAC_AUTO GROUP BY CodAuto, CodGest) A_PG
  WHERE Q &lt;&gt; 0
  );

  INSERT INTO RAC_EMU
  SELECT CODCOMANDA, Sum(COALESCE(e1.Cant, 0)) CANT
  FROM Emulare1 e1
      INNER JOIN Emulare  e  ON  e.CodEmulare   = e1.CodEmulare  and  COALESCE(e.CODMONETAR, 0) = 0
      INNER JOIN Comanda1 c1 ON  C1.CodComanda1 = e1.CodComanda1 and  COALESCE(e1.CODCOMANDA1, 0) &lt;&gt; 0
  GROUP BY CodComanda;

  INSERT INTO RAC_AUTO(CODAUTO, CODOBIECT, CODGEST, TRANSFERAT, Q, DATASTART, DATASTOP, CODCLASA)
  VALUES(-1, 0, 0, 0, 0, DATAPORNIRE, CURRENT_TIMESTAMP, 0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_rez_indexgrupaauto</obj_name>
  <obj_hashval>1c728fa00f77e23ff1a213cc37e2249f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_rez_indexgrupaauto(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  1;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_rez_setisdatacuora</obj_name>
  <obj_hashval>13b1f45ee9b604227b0ed5e8a03bb5df</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_rez_setisdatacuora(aisdatacuora numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_RAC_REZ.IsDataCuOra',to_char(aIsDataCuOra,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_raportp_sp_postrecords</obj_name>
  <obj_hashval>2b7b0713d1ee74e87f958227f3b431f0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_raportp_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  vCod        numeric;
  aCARNET     numeric := 0;
  aNrDoc      numeric;
  aCodSubunit numeric;
  aDataDoc    date;
  aDoc        varchar;
  Nr          numeric;
  aCount      numeric := 0;
BEGIN
  --Florin 02.04.2024 - sinc. Oracle
  --Florin 01.06.2023 - monitor
  --Florin 26.10.2020 - fixat tichet #40649
  --Florin 19.01.2021 - adaugat obs
  --Florin 15.02.2021 - fixat 41936
  --Florin 23.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_raportp_setct_monitor('MON_xx');
  SELECT CodRaportP, NrDoc, Subunitatea, DataI, 'RaportP ' || NrDoc || '/' || dataI || '-' || DataS, CarnetDoc
  INTO RecId, aNrDoc, aCodSubunit, aDataDoc, aDoc, aCarnet
  FROM TMP_RaportP;
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT (63);

  IF  Operation = 0 THEN
    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_RAPORTP.CT_MONITOR', true)))
    THEN
      PERFORM pkg_userfirme_postlogcucommit( 'RaportP', current_setting('PKG_GLOBALS.USERNAME', true), 'M', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), aCodSubunit, aDataDoc, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    UPDATE RaportP
    SET
    (NRDOC, DATAI, DATAS, Intreruperi, PE_FORMATIE, CODCENTRU, SECTIE, FORMATIE, PROGRAMF, SUBUNITATEA, AN, LUNA, prefixdoc, carnetdoc, seriadoc, SCHIMB, Obs)
    =
    (
    SELECT NRDOC, DATAI, DATAS, Intreruperi, PE_FORMATIE, CODCENTRU, SECTIE, FORMATIE, PROGRAMF, SUBUNITATEA, AN, LUNA, prefixdoc, carnetdoc, seriadoc, SCHIMB, Obs
    FROM TMP_RaportP
    )
    WHERE CodRaportP = RecId;

    SELECT Count( *) INTO NR FROM RaportP0 P0 WHERE P0.CodRaportP = RecId;
    IF  NR = 0 THEN
      DELETE FROM MANPRODLINK WHERE CodRaportP2 IN (SELECT CodRaportP2    FROM TMP_MANPRODLINK_INITIAL);
      DELETE FROM RaportP2    WHERE CodRaportP1 IN (SELECT P1.CodRaportP1 FROM RaportP1 P1 WHERE P1.CodRaportP = RecID);
      DELETE FROM RaportP1    WHERE CodRaportP = RecID;
      DELETE FROM RaportP3    WHERE CodRaportP = RecID;

      FOR v_rec IN (SELECT * FROM TMP_RaportP0) LOOP
        SELECT NEXTVAL('SEQ_RAPORTP0_CODRAPORTP0') INTO vCod;

        UPDATE TMP_RaportP1 SET CodRaportP0 = vCOD WHERE CodRaportP0 = v_rec.CodRaportP0;

        INSERT INTO RaportP0(CODRAPORTP0, CODRAPORTP, CodComanda1, Realizat, Rebut, OBS)
        VALUES(vCod, RecId, v_rec.CodComanda1, v_rec.Realizat, v_rec.Rebut, V_REC.OBS);
      END LOOP;

      FOR v_rec IN (SELECT * FROM TMP_RaportP1) LOOP
        SELECT NEXTVAL('SEQ_RAPORTP1_CODRAPORTP1') INTO vCod;

        UPDATE TMP_RaportP2 SET CodRaportP1 = vCOD WHERE CodRaportP1 = v_rec.CodRaportP1;

        INSERT INTO RaportP1(CODRAPORTP1, CODRAPORTP0, CODRAPORTP, ANGAJAT, Realizat, Indice, Rebut, Prodrealizat, Prodrebut)
        VALUES(vCod, v_rec.CODRAPORTP0, RecId, v_rec.ANGAJAT, v_rec.Realizat, v_rec.Indice, v_rec.Rebut, v_rec.ProdRealizat, v_rec.ProdRebut);
      END LOOP;

      FOR v_rec IN (SELECT CODRAPORTP2, CODRAPORTP1, CODCOMANDA1, CODOBIECT, CODMAN, REALIZAT, REBUT, CODOP, CODLOC, CODTARIF, TU, CODUTILAJ, DATASTART, DATASTOP, REFACUT, CODIES1
                    FROM TMP_RaportP2 ORDER BY CodRaportP1 , IndexOper
                   )
      LOOP
        SELECT NEXTVAL('SEQ_RAPORTP2_CODRAPORTP2') INTO vCod;

        UPDATE tmp_manprodlink SET codraportp2 = vcod WHERE codraportp2 = v_rec.codraportp2;

        INSERT INTO RaportP2(CODRAPORTP2, CODRAPORTP1, CODCOMANDA1, CODOBIECT, CODMAN, REALIZAT, REBUT, CODOP, CODLOC, CODTARIF, TU, CODUTILAJ, DATASTART, REFACUT, CODIES1)
        VALUES(vCod, v_rec.CODRAPORTP1, v_rec.CODCOMANDA1, v_rec.CODOBIECT, v_rec.CODMAN, v_rec.REALIZAT, v_rec.REBUT, v_rec.CODOP, v_rec.CODLOC, v_rec.CODTARIF, v_rec.TU, v_rec.CODUTILAJ, v_rec.DATASTART, V_REC.REFACUT, V_REC.CODIES1);
      END LOOP;

      FOR V_REC IN (SELECT * FROM TMP_MANPRODLINK) LOOP
        SELECT COALESCE( COUNT( *), 0) INTO NR FROM MANPRODLINK WHERE CODRAPORTP2 = v_rec.CODRAPORTP2;
        IF  NR = 0 THEN
          INSERT INTO MANPRODLINK(CODRAPORTP2, CODCMDPRODMAN, CANT, CODPROGRAMF1)
          VALUES(v_rec.CODRAPORTP2, v_rec.CODCMDPRODMAN, v_rec.CANT, v_rec.CODPROGRAMF1);
        ELSE
          UPDATE MANPRODLINK
          SET
          CODRAPORTP2   = v_Rec.Codraportp2,
          CODCMDPRODMAN = v_Rec.Codcmdprodman,
          CANT          = v_Rec.Cant,
          CODPROGRAMF1  = v_rec.codprogramf1
          WHERE
           CODRAPORTP2 = v_rec.CODRAPORTP2;
        END IF;
      END LOOP;
    ELSE
      DELETE FROM MANPRODLINK WHERE CodRaportP2 IN (SELECT CodRaportP2 FROM TMP_MANPRODLINK_INITIAL);
      DELETE FROM RaportP2    WHERE CodRaportP1 IN (SELECT P1.CodRaportP1 FROM RaportP1 P1 WHERE P1.CodRaportP = RecID)
                                AND CodRaportP2 NOT IN (SELECT CodRaportP2 FROM TMP_RaportP2 WHERE CodRaportP2 &gt; 0);
      DELETE FROM RAPORTP3 R3 WHERE R3.CODRAPORTP = RECID AND  NOT  EXISTS (SELECT TMP.CODRAPORTP3 FROM TMP_RAPORTP3 TMP WHERE TMP.CODRAPORTP3 = R3.CODRAPORTP3);
      DELETE FROM RaportP1    WHERE CodRaportP = RecID AND CodRaportP1 NOT IN (SELECT CodRaportP1 FROM TMP_RaportP1);
      DELETE FROM RaportP0    WHERE CodRaportP = RecID AND CodRaportP0 NOT IN (SELECT CodRaportP0 FROM TMP_RaportP0);

      FOR v_rec IN (SELECT * FROM TMP_RaportP0) LOOP
        IF  COALESCE( v_rec.CodRaportP0, 0) &gt; 0 THEN
          UPDATE RaportP0
          SET
          CODCoMANDA1 = v_rec.CODCoMANDA1,
          REALIZAT    = v_rec.REALIZAT,
          REBUT       = v_rec.REBUT,
          OBS         = V_REC.OBS
          WHERE CodRaportP0 = v_rec.CodRaportP0;
        ELSE
          SELECT NEXTVAL('SEQ_RAPORTP0_CODRAPORTP0') INTO vCod;

          UPDATE TMP_RaportP1 SET CodRaportP0 = vCOD WHERE CodRaportP0 = v_rec.CodRaportP0;

          INSERT INTO RaportP0(CODRAPORTP0, CODRAPORTP, CodComanda1, Realizat, Rebut, OBS)
          VALUES(vCod, RecId, v_rec.CodComanda1, v_rec.Realizat, v_rec.Rebut, V_REC.OBS);
        END IF;
      END LOOP;

      FOR v_rec IN (SELECT * FROM TMP_RaportP1 ORDER BY ANGAJAT) LOOP
        IF  COALESCE( v_rec.CodRaportP1, 0) &gt; 0 THEN
          UPDATE RaportP1
          SET
          ANGAJAT      = v_rec.ANGAJAT,
          REALIZAT     = v_rec.REALIZAT,
          Indice       = v_rec.Indice,
          REBUT        = v_rec.REBUT,
          ProdRealizat = v_rec.Prodrealizat,
          ProdRebut    = v_rec.prodrebut
          WHERE
           CodRaportP1 = v_rec.CodRaportP1;
        ELSE
          SELECT NEXTVAL('SEQ_RAPORTP1_CODRAPORTP1') INTO vCod;

          UPDATE TMP_RaportP2 SET CodRaportP1 = vCOD WHERE CodRaportP1 = v_rec.CodRaportP1;
          UPDATE TMP_RaportP3 SET CodRaportP1 = vCOD WHERE CodRaportP1 = v_rec.CodRaportP1;

          INSERT INTO RaportP1(CODRAPORTP1, CODRAPORTP0, CODRAPORTP, ANGAJAT, Realizat, Indice, Rebut, ProdRealizat, ProdRebut)
          VALUES(vCod, v_rec.CODRAPORTP0, RecId, v_rec.ANGAJAT, v_rec.Realizat, v_rec.Indice, v_rec.Rebut, v_rec.ProdRealizat, v_rec.ProdRebut);
        END IF;
      END LOOP;

      FOR V_REC IN (SELECT codraportp3, codraportp1, codraportp, codmotiv, ore FROM TMP_RAPORTP3) LOOP
        IF  COALESCE( V_REC.CODRAPORTP3, 0) &gt; 0 THEN
          UPDATE RAPORTP3
          SET
          codraportp1 = V_REC.CODRAPORTP1,
          codraportp  = V_REC.CODRAPORTP,
          codmotiv    = CODMOTIV,
          ore         = ORE
          WHERE
           CODRAPORTP3 = V_REC.CODRAPORTP3;
        ELSE
          SELECT NEXTVAL('SEQ_RAPORTP3_CODRAPORTP3') INTO vCod;

          INSERT INTO RAPORTP3(CODRAPORTP3, CODRAPORTP1, CODRAPORTP, CODMOTIV, ORE)
          VALUES(VCOD, V_REC.CODRAPORTP1, RecId, V_REC.CODMOTIV, V_REC.ORE);
        END IF;
      END LOOP;

      FOR v_rec IN (SELECT CODRAPORTP2, CODRAPORTP1, CODCOMANDA1, CODOBIECT, CODMAN, REALIZAT, REBUT, CODOP, CODLOC, CODTARIF, TU, CODUTILAJ, DATASTART, DATASTOP, REFACUT, CODIES1
                    FROM TMP_RaportP2 ORDER BY CodRaportP1 , IndexOper
                   )
      LOOP
        IF  COALESCE( v_rec.CODRAPORTP2, 0) &gt; 0 THEN
          UPDATE RaportP2
          SET
          CODCOMANDA1 = v_Rec.Codcomanda1,
          CODOBIECT   = v_Rec.Codobiect,
          CODMAN      = v_Rec.Codman,
          REALIZAT    = v_Rec.Realizat,
          REBUT       = v_Rec.Rebut,
          CODOP       = v_Rec.Codop,
          CODLOC      = v_Rec.Codloc,
          CODTARIF    = v_Rec.Codtarif,
          TU          = v_rec.tu,
          CODUTILAJ   = v_Rec.Codutilaj,
          DATASTART   = v_Rec.DataStart,
          DATASTOP    = v_Rec.DataStop,
          REFACUT     = V_rEC.Refacut,
          CODIES1     = V_REC.CODIES1
          WHERE
           CODRAPORTP2 = v_rec.CODRAPORTP2;
        ELSE
          SELECT NEXTVAL('SEQ_RAPORTP2_CODRAPORTP2') INTO vCod;

          UPDATE tmp_manprodlink SET codraportp2 = vcod WHERE codraportp2 = v_rec.codraportp2;

          INSERT INTO RaportP2(CODRAPORTP2, CODRAPORTP1, CODCOMANDA1, CODOBIECT, CODMAN, REALIZAT, REBUT, CODOP, CODLOC, CODTARIF, TU, CODUTILAJ, DATASTART, DATASTOP, REFACUT, CODIES1)
          VALUES(vCod, v_Rec.CODRAPORTP1, v_Rec.CODCOMANDA1, v_Rec.CODOBIECT, v_Rec.CODMAN, v_Rec.REALIZAT, v_Rec.REBUT, v_Rec.CODOP, v_Rec.CODLOC, v_Rec.CODTARIF, v_Rec.TU, v_Rec.CODUTILAJ, v_Rec.DATASTART, v_Rec.DATASTOP, V_REC.REFACUT, V_REC.CODIES1);
        END IF;
      END LOOP;

      FOR V_REC IN (SELECT * FROM TMP_MANPRODLINK) LOOP
        SELECT COALESCE( COUNT( *), 0) INTO NR FROM MANPRODLINK WHERE CODRAPORTP2 = v_rec.CODRAPORTP2;
        IF  NR = 0 THEN
          INSERT INTO MANPRODLINK(CODRAPORTP2, CODCMDPRODMAN, CANT, CODPROGRAMF1)
          VALUES(v_rec.CODRAPORTP2, v_rec.CODCMDPRODMAN, v_rec.CANT, v_rec.CODPROGRAMF1);
        ELSE
          UPDATE MANPRODLINK
          SET
          CODRAPORTP2   = v_Rec.Codraportp2,
          CODCMDPRODMAN = v_Rec.Codcmdprodman,
          CANT          = v_Rec.Cant,
          CODPROGRAMF1  = v_rec.codprogramf1
          WHERE
           CODRAPORTP2 = v_rec.CODRAPORTP2;
        END IF;
      END LOOP;
    END IF;

  ELSE
    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, current_setting('PKG_GLOBALS.USERID', true)::NUMERIC, current_setting('PKG_RAPORTP.CT_MONITOR', true)))
    THEN
      PERFORM pkg_userfirme_postlogcucommit( 'RaportP', current_setting('PKG_GLOBALS.USERNAME', true), 'A', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), aCodSubunit, aDataDoc, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    SELECT NEXTVAL('SEQ_RAPORTP_CODRAPORTP') INTO RecId;
    PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('RaportP', RecId);

    INSERT INTO RaportP(CODRAPORTP, NRDOC, DATAI, DATAS, Intreruperi, PE_FORMATIE, CODCENTRU, SECTIE, FORMATIE, PROGRAMF, SUBUNITATEA, AN, LUNA, USERID, DATACREARE, prefixdoc, carnetdoc, seriadoc, SCHIMB)
    SELECT RecId, NRDOC, DATAI, DATAS, Intreruperi, PE_FORMATIE, CODCENTRU, SECTIE, FORMATIE, PROGRAMF, SUBUNITATEA, AN, LUNA, TO_NUMBER((current_setting('PKG_GLOBALS.UserId', true)),'999999999999999999'), now(), prefixdoc, carnetdoc, seriadoc, SCHIMB
    FROM TMP_RaportP;

    FOR v_rec IN (SELECT * FROM TMP_RaportP0) LOOP
      SELECT NEXTVAL('SEQ_RAPORTP0_CODRAPORTP0') INTO vCod;

      UPDATE TMP_RaportP1 SET CodRaportP0 = vCOD WHERE CodRaportP0 = v_rec.CodRaportP0;

      INSERT INTO RaportP0(CODRAPORTP0, CODRAPORTP, CodComanda1, Realizat, Rebut, OBS)
      VALUES(vCod, RecId, v_rec.CodComanda1, v_rec.Realizat, v_rec.Rebut, V_REC.OBS);
    END LOOP;

    FOR v_rec IN (SELECT * FROM TMP_RaportP1) LOOP
      SELECT NEXTVAL('SEQ_RAPORTP1_CODRAPORTP1') INTO vCod;

      UPDATE TMP_RaportP2 SET CodRaportP1 = vCOD WHERE CodRaportP1 = v_rec.CodRaportP1;
      UPDATE TMP_RaportP3 SET CodRaportP1 = vCOD WHERE CodRaportP1 = v_rec.CodRaportP1;

      INSERT INTO RaportP1(CODRAPORTP1, CODRAPORTP0, CODRAPORTP, ANGAJAT, Realizat, Indice, Rebut, ProdRealizat, ProdRebut)
      VALUES(vCod, v_rec.CODRAPORTP0, RecId, v_rec.ANGAJAT, v_rec.Realizat, v_rec.Indice, v_rec.Rebut, v_rec.ProdRealizat, v_rec.ProdRebut);
    END LOOP;

    FOR v_rec IN (SELECT * FROM TMP_RaportP2) LOOP
      SELECT NEXTVAL('SEQ_RAPORTP2_CODRAPORTP2') INTO vCod;

      UPDATE TMP_MANPRODLINK SET CodRaportP2 = vCOD WHERE CodRaportP2 = v_rec.CodRaportP2;

      INSERT INTO RaportP2 (CODRAPORTP2, CODRAPORTP1, CODCOMANDA1, CODOBIECT, CODMAN, REALIZAT, REBUT, CODOP, CODLOC, CODTARIF, TU, CODUTILAJ, DATASTART, DATASTOP, REFACUT, CODIES1)
      VALUES(vCod, v_Rec.CODRAPORTP1, v_Rec.CODCOMANDA1, v_Rec.CODOBIECT, v_Rec.CODMAN, v_Rec.REALIZAT, v_Rec.REBUT, v_Rec.CODOP, v_Rec.CODLOC, v_Rec.CODTARIF, v_Rec.TU, v_Rec.CODUTILAJ, v_Rec.DATASTART, v_Rec.DATASTOP, V_REC.REFACUT, V_REC.CODIES1);
    END LOOP;

    INSERT INTO MANPRODLINK(CODRAPORTP2, CODCMDPRODMAN, CANT, CODPROGRAMF1)
    SELECT CODRAPORTP2, CODCMDPRODMAN, CANT, CODPROGRAMF1 FROM TMP_MANPRODLINK;

    INSERT INTO RAPORTP3(CODRAPORTP3, CODRAPORTP1, CODRAPORTP, CODMOTIV, ORE)
    SELECT NEXTVAL('SEQ_RAPORTP3_CODRAPORTP3'), CODRAPORTP1, RecId, CODMOTIV, ORE FROM TMP_RAPORTP3;
  END IF;


  IF    (TO_NUMBER((current_setting('PKG_RAPORTP.CARNETDOC_I', true)),'999999999999999999') &lt;&gt; 0)
    AND (TO_NUMBER((current_setting('PKG_RAPORTP.NRDOC_I'    , true)),'999999999999999999') &lt;&gt; 0)
    AND (aCARNET &lt;&gt; TO_NUMBER((current_setting('PKG_RAPORTP.CARNETDOC_I', true)),'999999999999999999')
         OR
         aNRDOC &lt;&gt; TO_NUMBER((current_setting('PKG_RAPORTP.NRDOC_I', true)),'999999999999999999')
        )
  THEN
    PERFORM PKG_CARNETEDOC_RELEASENUMARDOC( TO_NUMBER((current_setting('PKG_RAPORTP.CARNETDOC_I', true)),'999999999999999999'), TO_NUMBER((current_setting('PKG_RAPORTP.NRDOC_I', true)),'999999999999999999'));
    PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE( TO_NUMBER((current_setting('PKG_RAPORTP.CARNETDOC_I', true)),'999999999999999999'));
  END IF;

  PERFORM PKG_CARNETEDOC_SOLVENUMARDOC( aCARNET, aNRDOC::varchar);

  DELETE FROM TMP_COMANDA1;
  INSERT INTO TMP_COMANDA1(CODCOMANDA1)
  SELECT CODCMDPRODMAN FROM TMP_MANPRODLINK
  UNION ALL
  SELECT CODCMDPRODMAN
   FROM TMP_MANPRODLINK_INITIAL;

   FOR v_rec IN (SELECT codcomanda1 AS codcmdprodman FROM tmp_comanda1) LOOP
        select coalesce(sum(il.cant),0) INTO aCount FROM MANPRODLINK IL
                            inner join raportp2 r2 on r2.codraportp2 = il.codraportp2
                            inner join raportp1 r1 on r1.codraportp1 = r2.codraportp1
                            inner join raportp r on r.codraportp = r1.codraportp
        WHERE il.codcmdprodman = v_rec.codcmdprodman;
        UPDATE cmdprodman SET rest = cant - acount WHERE codcmdprodman = v_rec.codcmdprodman;
    END LOOP;

  --UPDATE CMDPRODMAN
  --SET
  --REST = cant - (
  --SELECT COALESCE( SUM( IL.CANT), 0)
  --FROM MANPRODLINK IL
  --WHERE
  --   codcmdprodman = il.codcmdprodman
  --)
  --WHERE
  --CODcmdprodmaN IN (
  --SELECT CODcomanda1
  --FROM TMP_comanda1
  --)
  --;
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS(63);
  PERFORM NotifyModif( Operation, RecId, 'RAPORTP');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selurmofe_datafin</obj_name>
  <obj_hashval>097ed333b7e54ec479c833094dbb88b7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selurmofe_datafin()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 09.09.2020
  return to_date(current_setting ('PKG_LIST_SELURMOFE.vDataFin', true),'dd.mm.yyyy');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_locmunca_sp_gotorecord</obj_name>
  <obj_hashval>007c31061eedba7d22184284ecb0339b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_locmunca_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vTip       numeric;
  StartDate  Date;
  StopDate   Date;
  sStartDate Varchar;
  sStopDate  Varchar;
  aDate      Date;
  aSapt      numeric;
  A          numeric;
  L          numeric;
  sSQL       varchar;
BEGIN
  --Florin 18.06.2025 - sinc. Oracle
  --Laura 27.11.2021 - sinc Oracle (26.11.2021)
  --Adina 12.08.2021 - sinc.Oracle din 11.08.2021
  --Adina 09.07.2021 - sinc.Oracle din 08.07.2021 si 09.07.2021
  --Adina 21.04.2021 - sinc.Oracle din 20.04.2021
  --Adina 16.04.2021 - sinc.Oracle din 15.04.2021
  INSERT INTO TMP_LOCMUNCA(CODLOC, SIMBOL, DENUMIRE, TIP, ACTIVI, DSV, CodLocDef, MinuteOn, MinuteOff, SPECIAL, FARA_GANT)
  SELECT CODLOC, SIMBOL, DENUMIRE, TIP, ACTIVI, DSV, CodLocDef, MinuteOn, MinuteOff, SPECIAL, COALESCE(FARA_GANT,0)
  FROM LOCMUNCA WHERE CodLoc = RecId;

  BEGIN
    SELECT tip INTO vTip FROM tmp_locmunca;
  EXCEPTION WHEN others THEN
    vTip := 0;
  END;

  IF  vTip = 1 THEN
    INSERT INTO TMP_LOCMUNCA1(CODLOC1, CODLOC, NICKNAME, CODMIFIX, ORE, NRINV, DENUMIRE, DEN_GEST, CodGest, CODUTILAJ)
    SELECT LM1.CODLOC1, LM1.CODLOC, LM1.NICKNAME, LM1.CODMIFIX, LM1.ORE, MF.NRINVENTAR,
           (
            SELECT Min( O.DENUMIRE)
            FROM MIFIX1 MF1
                LEFT JOIN NIRSTOC NS ON  NS.CODNIRSTOC = MF1.CODNIRSTOC
                LEFT JOIN NARTOBJ O  ON  O.CODOBIECT   = NS.CODOBIECT
            WHERE MF1.CODMIFIX = LM1.CODMIFIX
            ),
            NG.DEN_GEST, NG.CodGest, LM1.CODUTILAJ
    FROM LOCMUNCA1 LM1
        LEFT JOIN MIFIX   MF  ON  MF.CODMIFIX    = LM1.CODMIFIX
        LEFT JOIN MIFIX1  MF1 ON  MF.CODMIFIX    = MF1.CODMIFIX AND  MF1.AnStart = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') AND  MF1.LunaStart = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999')
        LEFT JOIN NIRSTOC NS  ON  MF1.CODNIRSTOC = NS.CODNIRSTOC
        LEFT JOIN NIR         ON  NIR.CODNIR     = NS.CODNIR
        LEFT JOIN NGEST   NG  ON  NG.CODGEST     = NIR.GEST
    WHERE NS.Rest &gt; 0 and  CodLoc = RecId;
  ELSE
    IF  vTip = 2 THEN
      INSERT INTO TMP_LOCMUNCA1(CODLOC1, CODLOC, NICKNAME, CODMIFIX, ORE, NRINV, DENUMIRE, DEN_GEST, CODUTILAJ, CodGest, CodLocatie)
      SELECT LM1.CODLOC1, LM1.CODLOC, LM1.NICKNAME, LM1.CODMIFIX, LM1.ORE, U.NRINVENTAR, O.DENUMIRE, NG.DEN_GEST, LM1.CODUTILAJ, Coalesce(NG.CODGEST, 0), LM1.CodLocatie
      FROM LOCMUNCA1 LM1
          INNER JOIN UTILAJE U  ON  LM1.CODUTILAJ = U.CODUTILAJ
          INNER JOIN NARTOBJ O  ON  U.CODOBIECT   = O.CODOBIECT
          LEFT  JOIN NGEST   NG ON  LM1.CODGEST   = NG.CODGEST
      WHERE LM1.CodLoc = RecId;
    ELSE
      INSERT INTO TMP_LOCMUNCA1(CODLOC1, CODLOC, NICKNAME, DEN_GEST, CodGest, Ore, CodLocatie)
      SELECT LM1.CODLOC1, LM1.CODLOC, LM1.NICKNAME, NG.DEN_GEST, Coalesce(LM1.CODGEST, 0), LM1.Ore, LM1.CodLocatie
      FROM LOCMUNCA1 LM1
           LEFT JOIN NGEST NG ON LM1.CODGEST = NG.CODGEST
      WHERE LM1.CodLoc = RecId;
    END IF;
  END IF;

  INSERT INTO TMP_LOCMUNCA2 ( codloc2 , codloc1 , codloc , codLoc1Asoc, OreStart , DataStart , OreStop , DataStop , OreActiv, MinuneOn, MinuneOff,
                              codLocAsoc , DenLocAsoc  , DenLoc1Asoc )
                     SELECT  codloc2 , L2.codloc1 , L2.codloc , codLoc1Asoc, OreStart , DataStart , OreStop , DataStop , OreActiv, MinuneOn, MinuneOff,
                            L.CODLOC codLocAsoc, L.DENUMIRE DenLocAsoc  , L1.NICKNAME DenLoc1Asoc
    FROM LOCMUNCA2 L2
    Left join LOCMUNCA1 L1 on L1.CODLOC1 = L2.CODLOC1Asoc
    Left join LOCMUNCA  L  on L .CODLOC  = L1.CODLOC
    WHERE L2.CodLoc = RecId;

  L         := GetLUNALUCRU();
  A         := GetANLUCRU();
  StartDate := To_Date('01'||To_Char(L,'fm00')||To_Char(A,'fm0000'),'DDMMYYYY');
  StartDate := (SELECT wme_result FROM iso_week_to_date(NULL, (EXTRACT (YEAR FROM StartDate))::numeric, to_char(StartDate,'iw')::numeric));
--  insert into TMP_OreLM (CodORELM, DataLM,CodLM,CodLM1,Ore, Saptamana)
--  Select CodORELM, DataLM,CodLM,CodLM1,Ore, to_char(DataLM,'iw')::numeric from ORELM x where CodLM = RecID and DataLM &gt;= StartDate;

  L := L + 1;
  if L = 13 then
    L := 1;
    A := A + 1;
  end if;

  Select Max(DataLM) into StopDate From OreLM where CodLM = RecId;

  aDate := To_Date('01'||To_Char(L,'fm00')||To_Char(A,'fm0000'),'DDMMYYYY') - 1;

  if (StopDate is null) or StopDate &lt; aDate then
    StopDate := aDate;
  end if;

  StopDate   := (SELECT wme_result FROM iso_week_to_date(NULL, (EXTRACT(YEAR FROM StopDate))::numeric, to_char(StopDate,'iw')::numeric)) + 6;  --trunc(TRUNC(StopDate,'iw') + 6)
  sStopDate  := To_Char(StopDate , 'DDMMYYYY');
  sStartDate := To_Char(StartDate, 'DDMMYYYY');

  PERFORM umple_tmp_zile(StartDate, StopDate);

  INSERT INTO TMP_OreLM(CodORELM, DataLM,CodLM,CodLM1,Ore, Saptamana)
  WITH
  Recs as
   ( SELECT L1.CodLoc1 CodLM1, D.Ziua AS Data from Tmp_Zile D, LocMunca1 L1 WHERE L1.CodLoc = RecId),
  OLM1 as
   (SELECT L1.CodLoc CodLM, L1.CodLoc1 CodLM1, Case when coalesce(L1.ORE,0) = 0 then G.Ore else L1.ORE end Ore
    FROM LocMunca1 L1
    inner join ( Select CodGest, coalesce(NrSchimburi, 0) * coalesce(OreSchimb, 0) Ore from NGEST) G on G.CodGest = L1.CodGest
   )
  select Case when OreLM.CODORELM is null then -row_number() over() else OreLM.CODORELM end,
         Recs.Data, OLM1.CodLM,  OLM1.CodLM1,
         case when z.codzineluc is null then coalesce(OreLM.Ore, OLM1.Ore) else 0 end Ore,
         to_char(Recs.Data, 'iw')::numeric Saptamana
  from Recs
    left join OLM1       on OLM1.CodLM1   = Recs.CodLM1
    left join OreLM      on OreLM.DataLM  = Recs.Data and OreLM.Codlm1 = OLM1.CodLM1
    left join zineluc1 z on z.data::date = recs.data::date;

/*
  sSql :=
  'INSERT INTO TMP_OreLM(CodORELM, DataLM,CodLM,CodLM1,Ore, Saptamana)
  WITH RECURSIVE drec(Data) AS (
    SELECT To_Date('''||sStartDate||''',''DDMMYYYY'') AS Data
    UNION ALL
    SELECT Data + 1 FROM drec WHERE Data &lt; To_Date('''||sStopDate||''',''DDMMYYYY'')
  ),
  Recs as
   ( SELECT L1.CodLoc1 CodLM1, D.Data from drec D, LocMunca1 L1 WHERE L1.CodLoc = '||RecId::varchar||'),
  OLM1 as
   (SELECT L1.CodLoc CodLM, L1.CodLoc1 CodLM1, Case when coalesce(L1.ORE,0) = 0 then G.Ore else L1.ORE end Ore
    FROM LocMunca1 L1
    inner join ( Select CodGest, coalesce(NrSchimburi, 0) * coalesce(OreSchimb, 0) Ore from NGEST) G on G.CodGest = L1.CodGest
   )
  select Case when OreLM.CODORELM is null then -row_number() over() else OreLM.CODORELM end,
         Recs.Data, OLM1.CodLM,  OLM1.CodLM1,
         case when z.codzineluc is null then coalesce(OreLM.Ore, OLM1.Ore) else 0 end Ore,
         to_char(Recs.Data, ''iw'')::numeric Saptamana
  from Recs
    left join OLM1       on OLM1.CodLM1   = Recs.CodLM1
    left join OreLM      on OreLM.DataLM  = Recs.Data and OreLM.Codlm1 = OLM1.CodLM1
    left join zineluc1 z on z.data::date = recs.data::date';
  EXECUTE sSQL;
*/
   PERFORM PKG_CFGTABLES_EXT_GOTORECORD(524);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_sp_deleterecord</obj_name>
  <obj_hashval>11c410bd86a68b58fdfc98d16aa9b814</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC            RECORD;
  V_REC_MIFIX1     RECORD;
  V_NS             RECORD;
  V_TMP            RECORD;
  V_REC_JURN_SUB   RECORD;
  ACARNETDOC       numeric;
  ANRDOC           numeric;
  ATIPDOC          numeric;
  aCodSubunit      numeric;
  aDataDoc         date;
  aDoc             varchar;
  aCURS            double precision;
  aPRETPARINTE     double precision;
  ANPREC           numeric := 0;
  LUNAPREC         numeric := 0;
  NR               numeric := 0;
  aTipNS1          numeric;
  aCodRezervats    numeric;
  aCodNirStocOrig  numeric;
  LivrDinRezTransf character varying;
  aCodClasif       numeric;
  aDurataN         numeric;
  aDurataF         numeric;
  aDurataNG        numeric;
  aDurataNF        numeric;
  aCodCentru       numeric;
  aCONTIO          numeric;
  PRET_IMB_MF      numeric;
  VAL_ACHIZ_MF     numeric;
  CANT_IMB_MF      numeric;
  aCodMifix        numeric(20);
BEGIN
  --Florin 25.11.2025 - sinc. Oracle
  --Florin 16.10.2024 - sinc. Oracle
  --Florin 22.08.2024 - sinc. Oracle
  --Florin 15.06.2023 - fixat 58576
  --Florin 01.06.2023 - monitor
  --Florin 12.04.2023 - sinc. Oracle (11.04.2023)
  --Florin 18.10.2022 - sinc. Oracle
  --Florin 14.09.2022 - sinc. Oracle
  --Florin 22.01.2022 - sinc. Oracle (29.12.2021)
  --Florin 26.07.2021 - fixat 50894
  --Adina 04.05.2021 - sinc.Oracle din 30.04.2021
  --Adina 25.02.2021 - sinc.Oracle din 24.02.2021
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit

  -- MEMOREZ LIVRARILE CARE VOR FI STERSE
  perform pkg_miscari_interne_setct_monitor('MON_13');
  SELECT fnc_GetValConstanta('LivrDinRezTransf', getANLUCRU(), getLUNALUCRU()) INTO LivrDinRezTransf;

  perform PKG_GLOBALS_MarkDirtyJurnal();
  perform PKG_MISCARI_INTERNE_SP_LOCKRECORD(RecId);

  SELECT CARNETDOC, NRDOC, TIPDOC, SUBUNITATEA, DATADOC, coalesce(PREFIXDOC, '') ||NRDOC::varchar  || '/' DATADOC
  INTO ACARNETDOC, ANRDOC, aTIPDOC, aCodsubunit, ADATADOC, ADOC
  FROM TRANSF WHERE CODTRANSF = RECID;

  DELETE FROM DetaliiET1 et1
    where et1.coddetaliuet in (select et.coddetaliu
  from detaliiet et
    WHERE et.TipDoc = aTipDoc and et.CODDOC = RECID);
  DELETE FROM DetaliiET  WHERE TipDoc = aTipDoc and CODDOC = RECID;
  DELETE FROM STATUSDECL WHERE TipDoc = 100 + aTipDoc and CODDOC = RECID;

  PERFORM PKG_CFGTABLES_EXT_DELETERECORD (recId, aTIPDOC);
  if (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT
      FROM PKG_USERFIRME_ValidPostLog(null, to_number(current_setting('PKG_GLOBALS.USERID', true), '999999999999999999'), current_setting('PKG_MISCARI_INTERNE.CT_MONITOR', true)))
  then
    perform pkg_userfirme_postlogcucommit( 'TRANSF', current_setting('PKG_GLOBALS.USERNAME', true), 'S', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true),
                                             aCodSubunit, aDataDoc, aDoc, null,
                                             (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(null,null)));
  end if;

  DELETE FROM TRANSF1_MAN;
  INSERT INTO TRANSF1_MAN SELECT * FROM TRANSF1 WHERE CODTRANSF = RECID;

  DELETE FROM TMP_MANEVRA;
  INSERT INTO TMP_MANEVRA (CODUNIC)
  SELECT CODNIRSTOC FROM LIVR1 WHERE CODLIVR in (SELECT CODLIVR FROM LIVR WHERE CODTRANSF = RECID );

  DELETE FROM TMP_COMANDA1;
  INSERT INTO TMP_COMANDA1 (CODCOMANDA1)
  SELECT CODLINIECOMANDA FROM TRANSFLINK IL
  WHERE IL.CODTRANSF1 in (SELECT I1.CODTRANSF1 FROM TRANSF1 I1 WHERE CODTRANSF = RecID );

  -- EMULARE1
  FOR V_REC IN
  (
  SELECT
    E1.CODEMULARE1,
    NP.GEST,
    NSP.CODIOART,
    NSP.PRET
  FROM
    TRANSF1 T1,
    NIRSTOC NS,
    NIRSTOC NSP,
    NIR NP,
    EMULARE1 E1
  WHERE
    T1.CODTRANSF       = RECID
    AND T1.CODEMULARE1 = E1.CODEMULARE1
    AND NS.CODTRANSF1  = T1.CODTRANSF1
    AND NSP.CODNIRSTOC = NS.CODNIRSTOCPARINTE
    AND NP.CODNIR      = NSP.CODNIR
   )
  LOOP
    UPDATE EMULARE1
    SET
      CODGEST     = V_REC.GEST,
      CODIOART    = V_REC.CODIOART,
      PRETNIRSTOC = V_REC.PRET
    WHERE
      CODEMULARE1 = V_REC.CODEMULARE1;

  END LOOP;

-- LIVRARI
  DELETE FROM TMP_LIVR1;

  INSERT INTO TMP_LIVR1 ( CODLIVR1, CODNIRSTOC, CODNIRSER, CANT, CODIES1, CANTREZERVAT )
  SELECT CODLIVR1, CODNIRSTOC, CODNIRSER, CANT, CODIES1, CANTREZERVAT
  FROM LIVR1 L1
  where
    CODLIVR in (SELECT CODLIVR FROM LIVR WHERE CODTRANSF = RECID );

  DELETE FROM TMP_LIVR1_INITIAL;
  INSERT INTO TMP_LIVR1_INITIAL SELECT * FROM TMP_LIVR1;

  DELETE FROM LIVRVAL  WHERE CODLIVR1 in (SELECT CODLIVR1 FROM TMP_LIVR1 );
  DELETE FROM LIVR1 L1 WHERE CODLIVR1 in (SELECT CODLIVR1 FROM TMP_LIVR1 );

-- INAINTE DE STEREGERE DIN LIVR REACTIVEZ NUMERELE
  for V_REC in (SELECT * FROM LIVR WHERE CODTRANSF = RECID ) loop
    perform PKG_CARNETEDOC_RELEASENUMARDOC( V_REC.CARNETLIVR, V_REC.NRLIVR);
    perform PKG_CARNETEDOC_COMPACTEAZAINTERVALE(V_REC.CARNETLIVR);
  end loop;

  DELETE FROM LIVR WHERE CODTRANSF = RECID;

  DELETE FROM TMP_NIRSERINI;
  INSERT INTO TMP_NIRSERINI ( CODNIRSER, CODNIRSTOC, CANTNIR )
  SELECT CODNIRSER, CODNIRSTOC, CANTNIR
  FROM NIRSER
  WHERE CODNIRSTOC in (SELECT CODNIRSTOC FROM NIRSTOC WHERE CODNIR in (SELECT CODNIR FROM NIR WHERE CODTRANSF = RECID ) );

  DELETE FROM NIRSER WHERE CODNIRSTOC in (SELECT CODNIRSTOC FROM NIRSTOC WHERE CODNIR in (SELECT CODNIR FROM NIR WHERE CODTRANSF = RECID ) );

  DELETE FROM NIRSERLUNA WHERE CODNIRSTOC in (SELECT CODNIRSTOC FROM NIRSTOC WHERE CODNIR in (SELECT CODNIR FROM NIR WHERE CODTRANSF = RECID ) );

  DELETE FROM NIRLUNA WHERE CODNIRSTOC in (SELECT CODNIRSTOC FROM NIRSTOC WHERE CODNIR in (SELECT CODNIR FROM NIR WHERE CODTRANSF = RECID ) );

  DELETE FROM TMP_NIRSTOCINI;

  DELETE FROM TMP_TRANSFLINK_INITIAL;
  INSERT INTO TMP_TRANSFLINK_INITIAL ( CODTRANSF1, CODLINIECOMANDA, CANT )
  SELECT     CODTRANSF1, CODLINIECOMANDA, CANT
  FROM TRANSFLINK
  WHERE CODTRANSF1 in (SELECT CODTRANSF1 FROM TRANSF1 WHERE CODTRANSF = RecId );

-- STERG MIJLOACE FIXE
  for V_REC in (SELECT NS.*, N.GEST, T1.CODCOMANDA1 FROM NIRSTOC NS, NIR N, TRANSF1 T1 WHERE N.CODNIR = NS.CODNIR and N.CODTRANSF = RECID AND NS.CODTRANSF1 = T1.CODTRANSF1) loop
    perform PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA( to_number(current_setting('PKG_GLOBALS.ANLUCRU'  , true), '999999999999999999'),
                                                    to_number(current_setting('PKG_GLOBALS.LUNALUCRU', true), '999999999999999999'),
                                                    ANPREC, LUNAPREC);
    perform PKG_GLOBALS_SetLunaPRECEDENTA( ANPREC, LUNAPREC);
    perform PKG_GLOBALS_SetLunaTEMP( to_number(current_setting('PKG_GLOBALS.ANLUCRU'  , true), '999999999999999999'),
                                     to_number(current_setting('PKG_GLOBALS.LUNALUCRU', true), '999999999999999999'));

    for V_REC_MIFIX1 in (SELECT * FROM MIFIX1 WHERE CODNIRSTOC = V_REC.CODNIRSTOC ) loop
      begin
        SELECT coalesce( PRET, 0) INTO aPRETPARINTE FROM NIRSTOC WHERE CODNIRSTOC = V_REC.CODNIRSTOCPARINTE;
        SELECT coalesce( CONT, 0) INTO aCONTIO      FROM NIRSTOC NS, TMP_IOART_LUNA IO1 WHERE NS.CODNIRSTOC = V_REC.CODNIRSTOCPARINTE and NS.CODIOART = IO1.CODIOART;
      exception
        when others then aPRETPARINTE := 0;
      end;

      if aCONTIO &lt;&gt; 0 and
         ( (SELECT PKG_CATEGCONST_ESTEMIFIX.WME_RESULT FROM PKG_CATEGCONST_ESTEMIFIX(null,  aCONTIO)) = 1
           or (SELECT PKG_CATEGCONST_ESTEOBINV.WME_RESULT FROM PKG_CATEGCONST_ESTEOBINV(null, aCONTIO)) = 1
         )
      then
        begin
          SELECT codclasif, durataf, duratan, duratang, duratanf, codcentru
          INTO acodclasif, aDurataF, aDurataN, aDurataNG, aDurataNF, aCodCentru
          FROM MIFIX1 WHERE CODNIRSTOC = V_REC.CODNIRSTOCPARINTE limit 1;
        exception
          when others then
            begin
              SELECT codclasif, durata, durataf, duratag, durataf INTO acodclasif, aDurataN, aDurataF, aDurataNG, aDurataNF
              FROM mfclasif
              WHERE codclasif = (fnc_GetValConstanta('CodClasifImob', getANLUCRU(), getLUNALUCRU()) )::numeric;
            exception
              when others then acodclasif := 0;
                aDurataF := 0;
                aDurataN := 0;
                aDurataNG := 0;
                aDurataNF := 0;
            end;
            aCodCentru := v_rec_mifix1.CodCentru;
        end;

            begin
              select coalesce(codmifix,0) into aCodMifix from mifix where codmifixnou = v_rec_mifix1.codmifix;
            exception when others then aCodMifix := v_rec_mifix1.codmifix;
            end;

            if aCodMifix = 0 then aCodMifix := v_rec_mifix1.codmifix; end if;
            if aCodMifix &lt;&gt; v_rec_mifix1.codmifix then
              update mifix set codmifixnou = null, anlunamifixnou = null where codmifix = acodmifix;
            end if;

        UPDATE MIFIX1
        set
          codmifix   = aCodMifix,
          CODNIRSTOC = V_REC.CODNIRSTOCPARINTE,
          PRET       = aPRETPARINTE,
          DATAREEVAL = null,
          AMOVECHI   = 0,
          PRETVECHI  = 0,
          CodCentru  = aCodCentru,
          TIPREEVAL  = null,
          INCLUDRATA = null
        where
          CODMIFIX1 = V_REC_MIFIX1.CODMIFIX1 ;

      update mifix1 set codmifix = aCodMifix, codnirstoc = v_rec.codnirstocparinte where codnirstoc = v_rec.codnirstoc and anstart*12+lunastart &gt; v_rec_mifix1.anstart*12+v_rec_mifix1.lunastart;

        if aCodClasif &gt; 0 then
          if aTipDoc = 12 then
            for v_ns in (SELECT ns.codnirstoc
                         FROM nirstoc ns
                              inner join nirstoc nsp on nsp.codnirstoc = ns.codnirstocparinte
                              inner join ioart1 ioa1 on ioa1.codioart = ns.codioart    and getanlunalucru() BETWEEN ioa1.alstart  AND ioa1.alstop
                              inner join ioart1 ioa1p on ioa1p.codioart = nsp.codioart and getanlunalucru() BETWEEN ioa1p.alstart AND ioa1p.alstop
                              WHERE ns.codnirstoc = v_Rec.Codnirstoc
                           and nsp.codnirstoc = v_rec.codnirstocparinte
                           and (SELECT PKG_CATEGCONST_ESTEMIFIX.WME_RESULT FROM PKG_CATEGCONST_ESTEMIFIX(null, IOA1.CONT)) &gt; 0
                           and (SELECT PKG_CATEGCONST_ESTEIMBUNATATIREMIFIX.WME_RESULT FROM PKG_CATEGCONST_ESTEIMBUNATATIREMIFIX(null, IOA1P.CONT)) &gt; 0
                        )
            loop
              UPDATE mifix1
              set
                stare     = 5,
                codclasif = acodclasif,
                durataf   = adurataf,
                duratan   = aduratan,
                duratanf  = aduratanf,
                duratang  = aduratang,
                durataff  = adurataf * 12,
                duratafg  = aduratang * 12
              where
                codmifix1 = V_REC_MIFIX1.CODMIFIX1 ;
            end loop;
          end if;
        end if;

        if V_REC_MIFIX1.ANSTART = to_number(current_setting('PKG_GLOBALS.ANLUCRU', true), '999999999999999999')
           and V_REC_MIFIX1.LUNASTART = to_number(current_setting('PKG_GLOBALS.LUNALUCRU', true), '999999999999999999')
        then
           perform PKG_INCHIDERI_REFA_MIFIX(V_REC_MIFIX1.CODMIFIX);
        end if;

        UPDATE JURNAL1 SET DIRTY = 1 WHERE TIPDOC = 36 and CODDOC = V_REC_MIFIX1.CODMIFIX and AN * 12 + LUNA &gt;= V_REC_MIFIX1.ANSTART * 12 + V_REC_MIFIX1.LUNASTART ;
      end if;
    end loop;

    SELECT count(*) INTO NR FROM MASTERMIFIX WHERE CODNIRSTOC = V_REC.CODNIRSTOCPARINTE;

    if NR = 0 THEN
      UPDATE MASTERMIFIX SET CODNIRSTOC = V_REC.CODNIRSTOCPARINTE WHERE CODNIRSTOC = V_REC.CODNIRSTOC ;
    else
      DELETE FROM MASTERMIFIX WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
    end if;

    INSERT INTO TMP_NIRSTOCINI ( CODNIRSTOC, CODLIVR1 ) values ( V_REC.CODNIRSTOC, V_REC.CODLIVR1 );

    if aTIPDOC = 13 then
      DELETE FROM FISAMF WHERE CODOPERATIE in (6, 7) and NRDOC = RECID;

      DELETE FROM FISAMF WHERE CODOPERATIE = 3 and NRDOC = aNRDOC and DATAOPERATIE = aDATADOC and PRETE = V_REC.PRET and GESTDEST = V_REC.GEST;
    else
      DELETE FROM FISAMF WHERE CODOPERATIE = 2 and NRDOC = aNRDOC and DATAOPERATIE = aDATADOC and PRETE = V_REC.PRET and GESTDEST = V_REC.GEST;
    end if;

    if LivrDinRezTransf = '1' AND current_setting ('pkg_miscari_interne.v$Session_LivrDinRezTransf ', true) = '1' then
      for v_tmp in (SELECT r.* FROM rezervats r WHERE r.codnirstoc = v_rec.codnirstoc and (v_Rec.codcomanda1 = r.codcomanda1 or v_rec.codcomanda1 is null)) loop
        DELETE FROM rezervats WHERE codrezervats = v_tmp.codrezervats;

        if v_tmp.codcomanda1 &gt; 0 then
          begin
            SELECT CodRezervatS INTO aCodRezervats FROM rezervats WHERE codcomanda1 = v_tmp.codcomanda1 and codnirstoc = v_rec.codnirstocparinte;
          exception
            when others then aCodrezervats := 0;
          end;

          if aCodrezervatS &gt; 0 then
            UPDATE rezervats
            set
              rezervatini = rezervatini + v_tmp.rezervatini,
              rest        = rest + v_tmp.rest
            where
              codrezervats = acodrezervats ;
          else
            INSERT INTO rezervats ( codrezervats, codcomanda1, codnirstoc, codnirser, rest, umsec, codcmdprodmat, rezervatini, codobiect, codcomanda1f, codinventar1 )
            values ( nextval('SEQ_REZERVATS_CODREZERVATS'), v_tmp.codcomanda1, v_rec.codnirstocparinte, v_tmp.codnirser, v_tmp.rest, v_tmp.umsec, v_tmp.codcmdprodmat, v_tmp.rezervatini, v_tmp.codobiect, v_tmp.codcomanda1f, v_tmp.codinventar1 );
          end if;
        end if;
      end loop;
    end if;

    DELETE FROM MIFIX1      WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
    DELETE FROM MASTERMIFIX WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
    DELETE FROM NIRSTOC     WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
    DELETE FROM NIRSTOC1    WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
    DELETE FROM REZERVATS   WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
  end loop;

-- INAINTE DE STEREGERE DIN NIR REACTIVEZ NUMERELE
  for V_REC in (SELECT * FROM NIR WHERE CODTRANSF = RECID ) loop
    perform PKG_CARNETEDOC_RELEASENUMARDOC( V_REC.CARNETNIR, V_REC.NRNIR);
    perform PKG_CARNETEDOC_COMPACTEAZAINTERVALE(V_REC.CARNETNIR);
  end loop;

  DELETE FROM NIR WHERE CODTRANSF = RECID;

  DELETE FROM TRANSFLINK WHERE CODTRANSF1 in (SELECT CODTRANSF1 FROM TRANSF1 WHERE CODTRANSF = RecId );

  DELETE FROM TMP_IMBMIFIXLINK;
  INSERT INTO TMP_IMBMIFIXLINK ( CODTRANSF1, CODINTR1, CODIES1, CODNC1, CODMIFIX )
  SELECT L.CODTRANSF1, CODINTR1, CODIES1, CODNC1, L.CODMIFIX
  FROM IMBMIFIXLINK L, TRANSF1 T1
  WHERE T1.CODTRANSF = RECID and L.CODTRANSF1 = T1.CODTRANSF1;

  DELETE FROM IMBMIFIXLINK IL WHERE exists (SELECT CODTRANSF1 FROM TMP_IMBMIFIXLINK WHERE CODTRANSF1 = IL.CODTRANSF1 );

  UPDATE CANTAR
  set
    TIPDOC  = null,
    CODDOC1 = null
  where
    TIPDOC = aTIPDOC and CODDOC1 in (SELECT CODTRANSF1 FROM TRANSF1 WHERE CODTRANSF = RECID ) ;

  DELETE FROM FISAMF WHERE CODDOC1 in (SELECT CODTRANSF1 FROM TRANSF1 WHERE CODTRANSF = RECID ) and TIPDOC = ATIPDOC;

  DELETE FROM TRANSF1 WHERE CODTRANSF = RECID;

  DELETE FROM TRANSF WHERE CODTRANSF = RECID;
  -- REALOC IN DOCFREE NUMARUL DE DOCUMENT STERS
  perform PKG_CARNETEDOC_RELEASENUMARDOC( ACARNETDOC, ANRDOC);
  perform PKG_CARNETEDOC_COMPACTEAZAINTERVALE(ACARNETDOC);

  for V_REC in (SELECT * FROM JURNAL WHERE CODDOC = RecID and TIPDOC = ATIPDOC ) loop
    UPDATE NCONTRUL
    set
      RULAJCD  = RULAJCD  - V_REC.VALOARE,
      RULAJVCD = RULAJVCD - V_REC.VALOAREV
    where
      CODCONT  = V_REC.CONTD
      and AN   = to_number(current_setting('PKG_GLOBALS.ANLUCRU'  , true), '999999999999999999')
      and LUNA = to_number(current_setting('PKG_GLOBALS.LUNALUCRU', true), '999999999999999999') ;

    for V_REC_JURN_SUB in (SELECT * FROM NCONTRUL WHERE CODCONT = V_REC.CONTD and AN = V_REC.AN and LUNA = V_REC.LUNA ) loop
      UPDATE NCONTRULSUB
      set
        RULAJCD  = RULAJCD  - V_REC.VALOARE,
        RULAJVCD = RULAJVCD - V_REC.VALOAREV
      where
        CODCONTRUL = V_REC_JURN_SUB.CODCONTRUL
        and SUBUNITATEA = V_REC.SUBUNITATEA ;
    end loop;

    UPDATE NCONTRUL
    set
      RULAJCC  = RULAJCC  - V_REC.VALOARE,
      RULAJVCC = RULAJVCC - V_REC.VALOAREV
    where
      CODCONT = V_REC.CONTC
      and AN = to_number(current_setting('PKG_GLOBALS.ANLUCRU', true), '999999999999999999')
      and LUNA = to_number(current_setting('PKG_GLOBALS.LUNALUCRU', true), '999999999999999999') ;

    for V_REC_JURN_SUB in (SELECT * FROM NCONTRUL WHERE CODCONT = V_REC.CONTC and AN = V_REC.AN and LUNA = V_REC.LUNA ) loop
      UPDATE NCONTRULSUB
      set
        RULAJCC = RULAJCC - V_REC.VALOARE,
        RULAJVCC = RULAJVCC - V_REC.VALOAREV
      where
        CODCONTRUL = V_REC_JURN_SUB.CODCONTRUL
        and SUBUNITATEA = V_REC.SUBUNITATEA ;
    end loop;
  end loop;

  DELETE FROM JURNAL  WHERE CODDOC = RecID and TIPDOC = ATIPDOC;
  DELETE FROM JURNAL1 WHERE CODDOC = RecID and TIPDOC = ATIPDOC;
  DELETE FROM EXPERT1 WHERE CODEXPERT in (SELECT CODEXPERT FROM EXPERT WHERE CODDOC = RecID and TIPDOC = ATIPDOC);
  DELETE FROM EXPERT  WHERE CODDOC = RecID and TIPDOC = ATIPDOC;

  UPDATE NIRSTOC NS
  set
    REST = (SELECT PKG_INTRARI_GET_REST_STOC.WME_RESULT
            FROM PKG_INTRARI_GET_REST_STOC(null, NS.CODNIR, NS.CODNIRSTOC, NS.CANTNIR)),
    RESTUM1 = (SELECT PKG_INTRARI_GET_REST_STOC_UM1.WME_RESULT
               FROM PKG_INTRARI_GET_REST_STOC_UM1(null, NS.CODNIR, NS.CODNIRSTOC, NS.CANTUM1)),
    RESTUM2 = (SELECT PKG_INTRARI_GET_REST_STOC_UM2.WME_RESULT
               FROM PKG_INTRARI_GET_REST_STOC_UM2(null, NS.CODNIR, NS.CODNIRSTOC, NS.CANTUM2))
  where
    NS.CODNIRSTOC in (SELECT CODUNIC FROM TMP_MANEVRA ) ;

  UPDATE NIRSER NS
  set
    REST = (SELECT PKG_INTRARI_GET_REST_STOC_SERIE.WME_RESULT
            FROM PKG_INTRARI_GET_REST_STOC_SERIE(null, (SELECT CODNIR FROM NIRSTOC WHERE CODNIRSTOC = NS.CODNIRSTOC ), NS.CODNIRSER, NS.CANTNIR)),
    RESTUM1 = (SELECT PKG_INTRARI_GET_REST_STOC_SERIE_UM1.WME_RESULT FROM PKG_INTRARI_GET_REST_STOC_SERIE_UM1(null, (SELECT CODNIR FROM NIRSTOC WHERE CODNIRSTOC = NS.CODNIRSTOC ), NS.CODNIRSER, NS.CANTUM1)),
    RESTUM2 = (SELECT PKG_INTRARI_GET_REST_STOC_SERIE_UM2.WME_RESULT FROM PKG_INTRARI_GET_REST_STOC_SERIE_UM2(null, (SELECT CODNIR FROM NIRSTOC WHERE CODNIRSTOC = NS.CODNIRSTOC ), NS.CODNIRSER, NS.CANTUM2))
  where
    NS.CODNIRSTOC in (SELECT CODUNIC FROM TMP_MANEVRA ) ;

  UPDATE COMANDA1 c1
  set
    RESTACCEPTAT = c1.CANTACCEPTAT - (SELECT coalesce( sum(IL.CANT), 0)
                                      FROM TRANSFLINK IL
                                           left join TRANSF1 II1 ON II1.CODTRANSF1 = IL.CODTRANSF1
                                           left join TRANSF II ON II.CODTRANSF = II1.CODTRANSF
                                      WHERE IL.CODLINIECOMANDA = c1.CodComanda1 and II.OPERAT = 1 and II.ANULAT = 0 )
  where
    c1.CODCOMANDA1 in (SELECT CODCOMANDA1 FROM TMP_COMANDA1 ) ;

  for V_REC in (SELECT I.TIPDOC, I1.TVA, I1.CODINTR1, coalesce( I.CURS, 0) as CURS, I1.CANT, I1.PU
                FROM INTRARI1 I1, INTRARI I
                WHERE exists (SELECT CODINTR1 FROM TMP_IMBMIFIXLINK WHERE CODINTR1 = I1.CODINTR1 )
                      and I.CODINTR = I1.CODINTR
               )
  loop
    aCurs := V_REC.CURS;

    if aCURS = 0 then aCURS := 1; end if;

    UPDATE INTRARI1 I1
    SET
      RESTIMBMF = (CASE when V_REC.TIPDOC = 3 then V_REC.CANT * V_REC.PU * aCURS - coalesce( V_REC.TVA, 0)
                        else V_REC.CANT * V_REC.PU * aCURS end
                  )
                  -
                  (SELECT coalesce( sum(IL.CANT), 0)
                   FROM IMBMIFIXLINK IL
                        left join TRANSF1 T1 ON T1.CODTRANSF1 = IL.CODTRANSF1
                        left join TRANSF  T  ON T.CODTRANSF   = T1.CODTRANSF
                   WHERE IL.CODINTR1 = I1.CodINTR1 and T.T.OPERAT = 1 and T.ANULAT = 0
                  )
    WHERE CODINTR1 = V_REC.CODINTR1 ;
  end loop;

  for V_REC in (SELECT I1.CODIES1, coalesce( I.CURS, 0) as CURS, I1.CANT, I1.PU
                FROM IESIRI1 I1, IESIRI I
                WHERE exists (SELECT CODIES1 FROM TMP_IMBMIFIXLINK WHERE CODIES1 = I1.CODIES1 )
                      and I.CODIES = I1.CODIES
               )
  loop
    aCurs := V_REC.CURS;
    if aCURS = 0 then aCURS := 1; end if;

    PRET_IMB_MF := 0; VAL_ACHIZ_MF := 0; CANT_IMB_MF := 0;
    BEGIN
      SELECT SUM(L1.CANT) AS CANTDIMIN,
             SUM(L1.CANT * (NS.PRET - COALESCE(NS.ADAOS, 0))) AS VALDIMIN
      INTO
        CANT_IMB_MF,
        VAL_ACHIZ_MF
      FROM
        LIVR1 L1,
        LIVR L,
        NIRSTOC NS
      WHERE
        L1.CODIES1 = V_REC.CODIES1
        AND L1.CODLIVR = L.CODLIVR
        AND L.TIPLIVR = 14
        AND NS.CODNIRSTOC = L1.CODNIRSTOC
      GROUP BY L1.CODIES1;
    EXCEPTION WHEN OTHERS THEN NULL;
    END;

    IF coalesce(CANT_IMB_MF, 0) &lt;&gt; 0 THEN
       PRET_IMB_MF := VAL_ACHIZ_MF / CANT_IMB_MF;
    END IF;

    UPDATE IESIRI1 I1
    SET
      RESTIMBMF = /*V_REC.CANT * V_REC.PU*/
                  PRET_IMB_MF * V_REC.CANT * aCURS
                  - (SELECT coalesce( sum(IL.CANT), 0)
                     FROM IMBMIFIXLINK IL
                          left join TRANSF1 T1 ON T1.CODTRANSF1 = IL.CODTRANSF1
                          left join TRANSF  T  ON T.CODTRANSF   = T1.CODTRANSF
                     WHERE IL.CODIES1 = I1.CodIES1 and T.T.OPERAT = 1 and T.ANULAT = 0 )
    WHERE CODIES1 = V_REC.CODIES1 ;
  end loop;

  for V_REC in (SELECT N1.CODNC1, coalesce( N.CURS, 0) as CURS, N1.VALOARE
                FROM NC1 N1, NC N
                WHERE exists (SELECT CODNC1 FROM TMP_IMBMIFIXLINK WHERE CODNC1 = N1.CODNC1 )
                      and N.CODNC = N1.CODNC
               )
  loop
    aCurs := V_REC.CURS;
    if aCURS = 0 then aCURS := 1; end if;

    UPDATE NC1 N1
    SET
      RESTIMBMF = V_REC.VALOARE * aCURS - (SELECT coalesce( sum(IL.CANT), 0)
                                           FROM IMBMIFIXLINK IL
                                                left join TRANSF1 T1 ON T1.CODTRANSF1 = IL.CODTRANSF1
                                                left join TRANSF  T  ON T.CODTRANSF   = T1.CODTRANSF
                                           WHERE IL.CODNC1 = N1.CodNC1 and T.T.OPERAT = 1 and T.ANULAT = 0 )
    WHERE CODNC1 = V_REC.CODNC1 ;
  end loop;

  for V_REC in (SELECT M.CODMIFIX, M1.PRET as VALOARE
                FROM MIFIX M, MIFIX1 M1
                WHERE exists (SELECT CODMIFIX FROM TMP_IMBMIFIXLINK WHERE CODMIFIX = M.CODMIFIX )
                      and M1.CODMIFIX = M.CODMIFIX
                      and M1.ANSTART * 12 + M1.LUNASTART &lt;= getAnLunaLucru()
                      AND M1.ANSTART * 12 + M1.LUNASTART = (SELECT MAX(ANSTART * 12 + LUNASTART) FROM MIFIX1 M2 WHERE M2.CODMIFIX = M.CODMIFIX AND M2.ANSTART * 12 + M2.LUNASTART &lt;=  getAnLunaLucru() )
  )  loop
    UPDATE MIFIX N1
    SET
      RESTIMBMF = V_REC.VALOARE - (SELECT coalesce( sum(IL.CANT), 0)
                                   FROM IMBMIFIXLINK IL
                                        left join TRANSF1 T1 ON T1.CODTRANSF1 = IL.CODTRANSF1
                                        left join TRANSF  T  ON T.CODTRANSF   = T1.CODTRANSF
                                   WHERE IL.CODMIFIX = N1.CODMIFIX and T.T.OPERAT = 1 and T.ANULAT = 0 )
    WHERE CODMIFIX = V_REC.CODMIFIX ;
  end loop;

  if ATIPDOC = 13 then
    perform PKG_MISCARI_INTERNE_CHECK_REZERVARI_MODIPRET_IN();
  end if;

  if ATIPDOC = 12 then
    perform PKG_MISCARI_INTERNE_CHECK_REZERVARI_TRANSF_IN();
  end if;

  for V_REC in (SELECT IL.CODLINIECOMANDA, coalesce( L1.CODNIRSTOC, 0) as CODNIRSTOC, coalesce( L1.CODNIRSER, 0) as CODNIRSER, L1.CANTREZERVAT
                FROM TMP_LIVR1_INITIAL L1, TMP_TRANSFLINK_INITIAL IL
                WHERE L1.CODIES1 = IL.CODTRANSF1
               )
  loop
    UPDATE REZERVATS
    SET
      REST = REST + V_REC.CANTREZERVAT
    WHERE
      CODCOMANDA1    = V_REC.CODLINIECOMANDA
      and CODNIRSTOC = V_REC.CODNIRSTOC
      and coalesce( CODNIRSER, 0) = V_REC.CODNIRSER ;
  end loop;

  DELETE FROM DocAsoc WHERE ( CODDOC = RECID and TIPDOC = aTipDoc) or ( CODDOCASOC = RECID and TIPDOCASOC = aTipDoc) ;

  perform NotifyModif( 2, RECID, 'TRANSF');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomactivit_sp_insertrecord</obj_name>
  <obj_hashval>9ddb78026b8ba1f20c27d9be9978e71a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomactivit_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NACTIVIT(codactivit) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_operatii_getclasa_op</obj_name>
  <obj_hashval>537fb0b9ba7910825eafb758d2979f77</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_operatii_getclasa_op(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_OPERATII.CLASA_OP', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_getjob_datafin</obj_name>
  <obj_hashval>b4ec9bd71f82a559f343fe2d680c6298</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_getjob_datafin(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_ORA_LISTS.JOB_DATAFin', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := Null;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_promo_sp_gotorecord</obj_name>
  <obj_hashval>6d22d624bc4097d6614eadccc6c94074</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_promo_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  vCount     numeric;
  vTipDenArt numeric;
  vTipPrefix numeric;
begin
  --Florin 29.06.2022 - fnc_getprocenttvaart
  --Bogdan 02.03.2022 - 53337 - Promotii clienti - cantitatea maxima trebuie trecuta prin paritatea unitatii de masura de pe linie
  --Laura 22.10.2021 - sinc Oracle (21.10.2021)
  --Adina 23.06.2021 - sinc.Oracle din 22.06.2021 - legat de serii
  --Adina 07.06.2021 - sinc.Oracle din 03.06.2021
  --Florin 16.11.2021 - fixat 52001
  perform pkg_promo_setct_monitor('MON_30');
  vTipPrefix := coalesce( (select PKG_CATEGCONST_GetValConstanta.WME_RESULT from PKG_CATEGCONST_GetValConstanta(null, 'TipPrefixDenObiect', current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric, current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric))::numeric, 1);

  INSERT INTO TMP_PROMO (CodPromo, TipDoc, Anulat, Blocat, Operat, CarnetDoc, SeriaDoc, NrDoc, DataStart,
                         DataEnd, Moneda, TipPromotie, TipConditie, Obs, Subunitatea, UserId, TipClasep,
                         TipServire, DeMana, ValMin, Praguri, CantMin, ExclAltePromo, OraStart, OraStop,
                         An, Luna, Conf_Active, PRETCUAMANUNT
                        )
  SELECT CodPromo, TipDoc, Anulat, Blocat, Operat, CarnetDoc, SeriaDoc, NrDoc, DataStart, DataEnd,
         Moneda, TipPromotie, TipConditie, Obs, coalesce( Subunitatea,
         (select PKG_GLOBALS_getSubunitate.WME_RESULT from PKG_GLOBALS_getSubunitate(null, null))),
         UserId, coalesce( TipClasep, 0), coalesce( TipServire, 0), coalesce( DeMana, 0), coalesce( ValMin, 0),
         coalesce( Praguri, 0), coalesce( CantMin, 0), coalesce( ExclAltePromo, 0), coalesce( OraStart, '00:00'),
         coalesce( OraStop, '23:59'), current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric,
         current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric, 1, PRETCUAMANUNT
  FROM PROMO
  WHERE CodPromo = RecId;

  SELECT CASE DEMANA when 4 then 9
                     when 3 then 8
                     else vTipPrefix
         END
  INTO vTipDenArt
  FROM TMP_PROMO;

  INSERT INTO TMP_PROMOPART ( CodPromoPart, CodPromo, CodClaseP, Partener, CodLocatie, CodFiscal, CodPersC,
                              Prioritar, Denumire, Den_Sediu, Den_CodFiscal, Den_PersC )
  SELECT PP.CodPromoPart, PP.CodPromo, PP.CodClaseP, PP.Partener, PP.CodLocatie, PP.CodFiscal, PP.CodPersC,
         coalesce( PP.Prioritar, 0),
         CASE when coalesce( P.TipClaseP, 0)= 1 then C.Den_ClaseP else NP.Den_Part END ,
         CASE when PP.CodLocatie = 0 then 'TOATE' else A.Obs END ,
         CF.CodFiscal, coalesce(PC.NUme, '') || ' ' || coalesce(PC.Prenume, '')
  FROM PROMO P
       inner join PROMOPART    PP ON PP.CodPromo      = P.CodPromo
       left  join NCLASEP      C  ON C.CodClaseP      = PP.CodClaseP
       left  join NPART        NP ON NP.CodPart       = PP.Partener
       left  join NAGENDA      A  ON A.CodAgenda      = PP.CodLocatie
       left  join NPARTCODFISC CF ON CF.Cod_CodFiscal = PP.CodFiscal
       left  join NPERSCONTACT PC ON PC.CodPersC      = PP.CodPersC
      WHERE P.CodPromo = RecId;

  vCount := 0;

  SELECT count(CodPromoPart) INTO vCount FROM TMP_PROMOPART;

  IF vCount = 0 THEN
    INSERT INTO TMP_PROMOPART ( CodPromoPart, CodPromo, Partener, CodLocatie, CodFiscal, CodPersC, Prioritar,
                                Denumire, Den_Sediu, Den_CodFiscal, Den_PersC )
    SELECT -1, P.CodPromo, P.Partener, P.CodLocatie, P.CodFiscal, P.CodPersC, 0 PRIORITAR, NP.Den_Part,
           CASE when P.CodLocatie = 0 then 'TOATE' else A.Obs END ,
           CF.CodFiscal, coalesce(PC.NUme, '') || ' ' || coalesce(PC.Prenume, '')
    FROM PROMO P
         inner join NPART        NP ON NP.CodPart       = P.Partener
         left  join NAGENDA      A  ON A.CodAgenda      = P.CodLocatie
         left  join NPARTCODFISC CF ON CF.Cod_CodFiscal = P.CodFiscal
         left  join NPERSCONTACT PC ON PC.CodPersC      = P.CodPersC
    WHERE P.CodPromo = RecId and coalesce( P.Partener, 0) &lt;&gt; 0;
  END IF;

  INSERT INTO TMP_PROMOSUB ( CodPromoSub, CodPromo, Subunitatea, Denumire )
  SELECT PS.CodPromoSub, PS.CodPromo, PS.Subunitatea, S.Den_Subunit
  FROM PROMOSUB PS inner join NSUBUNIT S ON S.CodSubunit = PS.Subunitatea
  WHERE PS.CodPromo = RecId;

  vCount := 0;

  SELECT count(CodPromoSub) INTO vCount FROM TMP_PROMOSUB;

  IF vCount = 0 THEN
    INSERT INTO TMP_PROMOSUB ( CodPromoSub, CodPromo, Subunitatea, Denumire )
    SELECT -1, P.CodPromo, P.Subunitatea, S.Den_Subunit
    FROM TMP_PROMO P inner join NSUBUNIT S ON S.CodSubunit = P.Subunitatea
    WHERE P.Subunitatea &gt; 1;
  END IF;

  INSERT INTO TMP_PROMOPRAG ( CODPRAG, CODPROMO, VALMIN, PROCDISC, VALDISC, CANTMIN )
  SELECT CODPRAG, CODPROMO, VALMIN, PROCDISC, VALDISC, CANTMIN
  FROM PROMOPRAG
  WHERE CODPROMO = RecId;

  INSERT INTO TMP_PROMO1 ( CodPromo1, CodPromo, CodObiect, CodArticol, CodClaseA, CuEchivalente, UMSec,
                           Cant, CantOptim, Pret, PretAmanunt, ProcDisc, ValDisc, ZileC, TipLimita,
                           ModAplic, TG_Max, Zile_Exp, GrupaPret, ValMin, IndexLocal, DenObiect, DenUM,
                           Paritate, AuxLimita, ObjCuAtrib, ProcTVA, CodExtern, CodIntern, CodExternArt, PeArticol, cant_max )
  SELECT P1.CodPromo1, P1.CodPromo, P1.CodObiect, P1.CodArticol, P1.CodClaseA, CuEchivalente, P1.UMSec,
         P1.Cant / coalesce( U.Paritate, 1),
         p1.CantOptim / coalesce( U.Paritate, 1),
         P1.Pret * coalesce( U.Paritate, 1),
         P1.PretAmanunt * coalesce( U.Paritate, 1),
         P1.ProcDisc, P1.ValDisc, P1.ZileC, coalesce( P1.TipLimita, 0), coalesce( P1.ModAplic, 0),
         P1.TG_Max, P1.Zile_Exp, P1.GrupaPret, P1.ValMin, dense_rank() over(ORDER BY P1.CodPromo1 ASC),
         CASE vTipDenArt
           when 9 then '***TOATE***'
           when 8 then CA.Den_ClaseA
           when 3 then SUBSTR( coalesce(OBJ.CodIntern, '') || ';' || coalesce(OBJ.Denumire, ''),1,200)
           when 2 then SUBSTR( coalesce(OBJ.CodExtern, '') || ';' || coalesce(OBJ.Denumire, ''),1,200)
           else OBJ.Denumire
         END DENOBIECT,
         U.Den_UM1, coalesce( U.Paritate, 1),
         CASE P1.TipLimita
           when 3 then 'Serie'
           when 2 then 'Zile expirare &lt;= ' || coalesce(P1.Zile_Exp::varchar, '')
           when 1 then 'Data expirare &lt;= ' || coalesce(to_char( P1.TG_Max, 'dd.mm.yyyy'), '')
           else 'Stoc disponibil'
         END ,
         CASE when exists (SELECT AO.CODATROBJ FROM NATROBJ AO WHERE AO.CodObiect = P1.CodObiect ) then 1 else 0 END ,
         fnc_getprocenttvaart(Obj.CODARTICOL, current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric,
                                                current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric
         ),
         OBJ.CODEXTERN, OBJ.CODINTERN, A.CODEXTERNART,
         CASE when coalesce( P1.CodArticol, 0) &gt; 0 then 1 else 0 END PEARTICOL, P1.CANT_MAX/Coalesce(U.Paritate,1)
  FROM  PROMO1 P1
        left join NARTOBJ OBJ ON Obj.CodObiect = P1.CodObiect
        left join NUM1    U   ON U.CodUM1      = P1.UMSec
        left join NART    A   ON A.CodArticol  = OBJ.CodArticol
        left join NCLASEA CA  ON CA.CodClaseA  = P1.CodClaseA
  WHERE P1.CodPromo = RecId;

  -- promo1cadou cu legatura in promo1
  INSERT INTO TMP_PROMO1CADOU ( CodCadou, CodPromo1, CodPromo, CodObiect, UMSec, Cant, TipLimita, TG_Max,
                                Zile_Exp, ValMin, CantMin, IndexLocal, DenObiect, DenUM, Paritate, AuxLimita )
  SELECT PC.CodCadou, PC.CodPromo1, PC.CodPromo, PC.CodObiect, PC.UMSec, PC.Cant / U.Paritate,
         coalesce( PC.TipLimita, 0), PC.TG_Max, PC.Zile_Exp, PC.ValMin, PC.CantMin / U.Paritate,
         dense_rank() over(PARTITION BY PC.CodPromo1 ORDER BY PC.CodCadou ASC),
         CASE vTipPrefix
           when 2 then SUBSTR( coalesce(OBJ.CodExtern, '') || ';' || coalesce(OBJ.Denumire, ''),1,200)
           when 3 then SUBSTR( coalesce(OBJ.CodIntern, '') || ';' || coalesce(OBJ.Denumire, ''),1,200)
           else OBJ.Denumire
         END DENOBIECT,
         U.Den_UM1, U.Paritate,
         CASE PC.TipLimita
           when 3 then 'Serie'
           when 2 then 'Zile expirare &lt;= ' || coalesce(PC.Zile_Exp::varchar, '')
           when 1 then 'Data expirare &lt;= ' || coalesce(to_char( PC.TG_Max, 'dd.mm.yyyy'), '')
           else 'Stoc disponibil'
         END
  FROM PROMO1CADOU PC
       left join NARTOBJ OBJ ON Obj.CodObiect = PC.CodObiect
       left join NUM1    U   ON U.CodUM1      = PC.UMSec
  WHERE PC.CodPromo1 in (SELECT CODPROMO1 FROM TMP_PROMO1 );

  -- promo1 cadou fara legatura in promo1
  INSERT INTO TMP_PROMO1CADOU ( CodCadou, CodPromo1, CodPromo, CodObiect, UMSec, Cant, TipLimita, TG_Max,
                                Zile_Exp, ValMin, CantMin, IndexLocal, DenObiect, DenUM, Paritate, AuxLimita )
  SELECT PC.CodCadou, PC.CodPromo1, PC.CodPromo, PC.CodObiect, PC.UMSec, PC.Cant / U.Paritate,
         coalesce( PC.TipLimita, 0), PC.TG_Max, PC.Zile_Exp, PC.ValMin, PC.CantMin / U.Paritate,
         dense_rank() over(PARTITION BY PC.CodPromo1 ORDER BY PC.CodCadou ASC),
         CASE vTipPrefix
           when 2 then SUBSTR( coalesce(OBJ.CodExtern, '') || ';' || coalesce(OBJ.Denumire, ''),1,200)
           when 3 then SUBSTR( coalesce(OBJ.CodIntern, '') || ';' || coalesce(OBJ.Denumire, ''),1,200)
           else OBJ.Denumire
         END DENOBIECT,
         U.Den_UM1, U.Paritate,
         CASE PC.TipLimita
           when 3 then 'Serie'
           when 2 then 'Zile expirare &lt;= ' || coalesce(PC.Zile_Exp::varchar, '')
           when 1 then 'Data expirare &lt;= ' || coalesce(to_char( PC.TG_Max, 'dd.mm.yyyy'), '')
           else 'Stoc disponibil'
         END
  FROM PROMO1CADOU PC
       left join NARTOBJ OBJ ON Obj.CodObiect = PC.CodObiect
       left join NUM1    U   ON U.CodUM1      = PC.UMSec
  WHERE PC.CodPromo = RecId and coalesce( PC.CODPROMO1, 0) = 0;

  INSERT INTO TMP_PROMO1SER ( CODPROMO1S, CODPROMO1, SERIE, INDEXLOCAL )
  SELECT PS.CODPROMO1S, PS.CODPROMO1, PS.SERIE, ROW_NUMBER() OVER (PARTITION BY PS.CODPROMO1 ORDER BY PS.CODPROMO1S)
  FROM TMP_PROMO1 P1 inner join PROMO1SER PS ON PS.CODPROMO1 = P1.CODPROMO1;

  INSERT INTO TMP_PROMO1CADOUSER ( CODCADOUS, CODCADOU, SERIE, INDEXLOCAL )
  SELECT CS.CODCADOUS, CS.CODCADOU, CS.SERIE, ROW_NUMBER() OVER (PARTITION BY CS.CODCADOU ORDER BY CS.CODCADOUS)
  FROM TMP_PROMO1CADOU C inner join PROMO1CADOUSER CS ON CS.CODCADOU = C.CODCADOU;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_adauga_param_ext</obj_name>
  <obj_hashval>89bb2fd5d2786c9be57465b145cf69ba</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_adauga_param_ext(ptable character varying, pfield character varying, pvalfield numeric, pprefix character varying DEFAULT ''::character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  VREC     RECORD;
  sSql     varchar := '';
  sSqlP    varchar := '';
  vNr      numeric := 0;
  vNrX     numeric := 0;
  vTry     numeric;
  sDen     varchar := '';
  vCount   numeric;
  sZec     varchar := '';
  sSchema  varchar;
  sDisplay varchar;
BEGIN
  --Florin 11.04.2024 - fixat 61640
  --Florin 25.09.2023 - sinc. Oracle
  --Bogdan 21.09.2023 - densediu -&gt; obs
  --Florin 06.03.2023 - fixat 57481
  --Florin 28.02.2023 - sinc. Oracle (27.02.2023)
  --Adina 07.06.2021 - sinc.Oracle din 04.06.2021 (sDisplay)
  --Adina 02.06.2021 - add schema in information_schema
  --Adina 24 septembrie 2020 + comentariile mele
  --Florin 07.12.2020 - fixat #41362
  --Florin 11.05.2021 - sincron Oracle
  --Florin 21.05.2021 - fixat 50271
  sSchema := Lower(current_setting('PKG_GLOBALS.FIRMANAME', true));
  IF NULLIF(sSchema, '') IS NULL THEN
    sSchema := public.get_schema();
  END IF;

  FOR vRec IN ( SELECT  utc.column_name, c1.numecamp,
                        Coalesce(c1.CAPTION, c1.NUMECAMP) DEN,
                        Coalesce(c1.nomlink, 0) NOMLINK,
                        'T.' || coalesce(REPLACE(c1.lookupdisplay, ';', '||'';''||T.'),'') LOOKUPDISPLAY,
                        c1.tip, coalesce(c1.zecimale,0) zecimale
                FROM  cfgtables c
                      INNER JOIN cfgtables1 c1 ON c1.CodCfgTable  = c.CodCfgTable
                      --LEFT  JOIN user_tab_columns utc ON  utc.table_name  = Upper(c.numetabela) AND  utc.column_name = Upper(c1.numecamp)
                      LEFT  JOIN information_schema.COLUMNS utc ON utc.table_schema = sSchema AND utc.table_name = lower(c.numetabela) AND utc.column_name = lower(c1.numecamp)
                WHERE Upper(c.numetabela) = Upper(pTable) AND utc.column_name is not null
              )
  LOOP
    sDisplay := Upper(vRec.lookupdisplay);
    if vRec.nomlink = 5 then
      sDisplay := replace(sDisplay, 'T.ADRESA','fnc_GETADRESA(T.SECTOR,T.STRADA,T.NR1,T.NR2,T.BLOC,T.SCARA,T.ETAJ,T.APART,T.CODPOSTAL)');
      sDisplay := replace(sDisplay, 'T.DENSEDIU','T.OBS');
      sDisplay := replace(sDisplay, 'T.LOCALITATE','T.IDSEDIU');
    end if;
    if vRec.nomlink = 1 THEN
      sDisplay := replace(sDisplay, 'T.DENOBIECT','T.DENUMIRE');
    END IF;

    sSql := sSql || ',
      ';
    IF vRec.column_name IS NULL THEN
      sSql := sSql || 'NULL AS ' || coalesce(vRec.numecamp,'');
    ELSE
      vNrX := vNrX + 1;
      CASE vRec.nomlink
        WHEN 1 THEN  /*Articole*/
          sSql := sSql || '(SELECT ' || coalesce(sDisplay,'') || ' FROM nartobj  t WHERE t.codobiect = x.'   || coalesce(vRec.numecamp,'') || ')';
        WHEN 2 /*Parteneri*/ THEN
          sSql := sSql||'(SELECT '||sdisplay ||' FROM (SELECT p.*, f.codfiscal FROM npart p LEFT JOIN npartcodfisc f ON f.codpart = p.codpart AND f.principal = 1) t WHERE t.codpart = x.'||vRec.numecamp||')';
        WHEN 3 THEN  /*Personal*/
          sSql := sSql || '(SELECT ' || coalesce(sDisplay,'') || ' FROM npers    t WHERE t.codpers = x.'     || coalesce(vRec.numecamp,'') || ')';
        WHEN 4 THEN  /*Contract cli*/
          sSql := sSql || '(SELECT ' || coalesce(sDisplay,'') || ' FROM contract t WHERE t.codcontract = x.' || coalesce(vRec.numecamp,'') || ')';
        WHEN 5 THEN  /*Sedii part*/
          sSql := sSql || '(SELECT ' || coalesce(sDisplay,'') || ' FROM nagenda  t WHERE t.codagenda = x.'   || coalesce(vRec.numecamp,'') || ')';
        ELSE
          sSql := sSql || 'x.' || coalesce(vRec.numecamp,'');
      END CASE;

      sSql := sSql || ' AS ' || coalesce(vRec.numecamp,'');
    END IF;

    vNr := vNr + 1;
    vTry := 0;

    LOOP
      sDen := coalesce(pPrefix,'') || coalesce(vRec.numecamp,'') || coalesce(CASE WHEN  vTry &gt; 0 THEN ' EXT_' || coalesce(vTry::varchar,'') END ,'');
      SELECT Count(1) INTO vCount FROM TMP_LIST_PARAMS WHERE DENUMIRE = sDen;
      EXIT  WHEN  vCount = 0;
      vTry := vTry + 1;
    END LOOP;

  --  sSqlP := sSqlP || '
    --PERFORM pkg_list_Struct_ADAUGA_PARAM(''' || coalesce(sDen,'') || ''',vRec.' || coalesce(vRec.COLUMN_NAME,'') || '::varchar);';    --Am adaugat PERFORM si ::varchar sa fiu sigura ca toate col.sunt varchar
    IF VREC.TIP = 'N' AND VREC.NOMLINK = 0 THEN
      IF VREC.ZECIMALE &gt; 0 THEN
        sZec := '';
        for idx in 1..VREC.ZECIMALE loop
          sZec := sZec||'9';
        end loop;
        sSqlP := sSqlP ||'
        PERFORM pkg_list_Struct_ADAUGA_PARAM('''||coalesce(sDen,'')||''',(TO_CHAR(COALESCE(vRec.'||coalesce(vRec.COLUMN_NAME,'')||',0)::numeric,''fm9G999G999G990D'||sZec||'''))::varchar);';
      ELSE
        sSqlP := sSqlP ||'
        PERFORM pkg_list_Struct_ADAUGA_PARAM('''||coalesce(sDen,'')||''',(TO_CHAR(COALESCE(vRec.'||coalesce(vRec.COLUMN_NAME,'')||',0)::numeric,''fm9G999G999G990''))::varchar);';
    END IF;
    ELSE
      sSqlP := sSqlP ||'
      PERFORM pkg_list_Struct_ADAUGA_PARAM('''||coalesce(sDen,'')||''',(vRec.'||coalesce(vRec.COLUMN_NAME,'')||')::varchar);';
    END IF;
  END LOOP;

  --am adaugat DECLARE
  sSQL := 'DO LANGUAGE PLPGSQL $$
        DECLARE
             vRec record;
           BEGIN
            FOR vRec IN (
              SELECT ' || coalesce(SUBSTR(sSQL, 2),'') || '
                ' || CASE WHEN vNrX = 0 THEN ' ' ELSE 'FROM (SELECT '||pValField||' cod) d LEFT JOIN '||pTable||' x ON x.'||pField||' = d.cod' END||'
      ) LOOP' || sSqlP || '
    END LOOP;
  END $$;';

  IF (   vNr &gt; 0)  THEN
    PERFORM LIST_EXECUTE_IMMEDIATE(sSQL, 0, 0);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_veniturirac_processlist</obj_name>
  <obj_hashval>8ba27f94d80f6b1a7dd9c5a91f6c46b8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_veniturirac_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sInsTmp     varchar;
  GrupaAuto   numeric;
  gSuplCols   varchar := 'TMP_LST_VENITURIRAC TMP, COMANDA CMD, RAC_REZ RAC';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  gDataS      varchar := current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true);
  gDataF      varchar := current_setting('PKG_LIST_ALEGPERIOADA.gDataF', true);
BEGIN
  --Florin 11.09.2025 - fixat 66628
  --Florin 22.01.2025 - sinc. Oracle
  --Florin 15.02.2023 - fixat 57206
  --Florin 29.06.2022 - fnc_getprocenttvaart
  --Adina 18.02.2021 - dupa modif.Oracle din 17.02.2021
  --Florin 03.10.2020
  GrupaAuto := (SELECT PKG_RAC_REZ_IndexGrupaAuto.WME_RESULT FROM PKG_RAC_REZ_IndexGrupaAuto(NULL,NULL));
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDA1', 'CMD1', 'CMD1.CODCOMANDA1 = TMP.CODCOMANDA1', 1);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_VENITURIRAC.gSuplCols', gSuplCols, FALSE);

  gUserAlias := Upper(gUserAlias);
  DELETE FROM TMP_LST_VENITURIRAC;
  sInsTmp := 'INSERT INTO TMP_LST_VENITURIRAC(
      NAV_CodDoc, NAV_TipDoc,
      REZERVARE, DATAREZ, NRREF, SERIAREZ,
      TIPREZ,
      GESTIUNE, CLIENT, NRAUTO, ARTICOLE, CLASAAUTO, PRETOFERTA, PUREZ, CODCOMANDA1, CODCOMANDA, TIPDOC, Z, DURATA,
      DEPASIRE,
      K,
      VALTOTALA,
      CODGEST, CATE, CODOBIECT, CANT, PU, PROCENT
    )
    SELECT
      R.CodComanda, R.TipDoc,
      R.Rezervare, R.DATAREZ, R.NRREF, R.SeriaRez,
      (CASE WHEN R.tiprezervare = 0 THEN ''Customer'' WHEN R.tiprezervare = 1 THEN ''Shuttle'' WHEN R.tiprezervare = 3 THEN ''Courtesy'' WHEN R.tiprezervare = 4 THEN ''Uz intern''
      WHEN R.tiprezervare = 5 THEN ''Reparatii'' WHEN R.tiprezervare =6 THEN ''Abonament'' WHEN R.tiprezervare = 7 THEN ''Transfer'' end) TipRez,
      R.GESTIUNE, R.CLIENT, R.NRAUTO, R.ARTICOLE, R.CLASAAUTO, R.PretOferta, R.PUREZ, R.CodComanda1, R.CodComanda, R.TipDoc, COALESCE(Rz.Zile, 0) z, Round(Durata, 3) Durata,
      Case when Depasire &lt; 0 then 0 else Round(Depasire, 3) end Depasire,
      Case when Depasire &lt; 0 then 1 when COALESCE(Durata,0) = 0 then 0 else Round((Durata - Depasire) / Durata, 3) end K,
      Valoare * (1 + COALESCE(PROCTVA, 0) / 100) ValTotala,
      R.CodGest, Cate , R.CodObiect, R.Cant, R.PU, R.Procent
    FROM (
      SELECT
        C.Nrdoc Rezervare, C.Datadoc DATAREZ, R.NR_REF NRREF, C.SeriaDoc SeriaRez, R.TipRezervare, NG.DEN_GEST GESTIUNE, NP.DEN_PART CLIENT, NA.NRINREG NRAUTO, O.DENUMIRE ARTICOLE, GRE.DENUMIRE CLASAAUTO,
        c1.PUCORELAT PretOferta, c1.PU * COALESCE(C.Curs, 1) PUREZ, C1.CodComanda1, C.CODCOMANDA, C.TipDoc, 1 Cate, 0 Tip,
        CASE
          WHEN COALESCE(R.Predat,0) = 1 then (R.DataPred::date - R.DataStart::date)::numeric
          WHEN R.DataStop &gt;= add_days(to_date(''' || gDataF || ''', ''dd.mm.yyyy''), 1) THEN (R.DataStop::date - R.DataStart::date)::numeric
          ELSE (add_days(to_date(''' || gDataF || ''', ''dd.mm.yyyy''), 1) - R.DataStart::date)::numeric
        END Durata,
        CASE
          WHEN (COALESCE(R.Predat,0) = 1 and R.DataPred &gt;= add_days(to_date(''' || gDataF || ''', ''dd.mm.yyyy''), 1))
          THEN Case when R.DataStart &gt;= to_date(''' || gDataS || ''', ''dd.mm.yyyy'') then 0 else (to_date(''' || gDataS || ''', ''dd.mm.yyyy'') - R.DataStart::date)::numeric END
          ELSE CASE WHEN R.DataStart &gt;= to_date(''' || gDataS || ''', ''dd.mm.yyyy'') then 0 else (to_date(''' || gDataS || ''', ''dd.mm.yyyy'') - R.DataStart::date)::numeric END +
                CASE WHEN COALESCE(R.Predat,0) = 0 and R.DataStop &lt; add_days(to_date(''' || gDataF || ''', ''dd.mm.yyyy''), 1) then 0
          else (COALESCE(R.DataPred,R.DataStop)::date - add_days(to_date(''' || gDataF || ''', ''dd.mm.yyyy''), 1))::numeric END
        END Depasire,
        R.CodGestSursa CodGest,
        CASE WHEN R.FaraTVA = 1 then 0 ELSE fnc_getprocenttvaart(a.CodArticol,GETANLUCRU(),GETLUNALUCRU()) END PROCTVA,
        C1.PU * C1.Cantacceptat * COALESCE(C.Curs, 1) ValLinie,
        CASE WHEN (Nvl(C1.TIPLINIESA,0) = 1) or Nvl(E.Ind,0) in (1,2000) THEN 100 - Nvl(R.Proccedat, 0) ELSE 100 END Procent,
        Case when (Nvl(C1.TIPLINIESA,0) = 1) or Nvl(E.Ind,0) in (1,2000) then (C1.PU * C1.Cantacceptat * (1 - Nvl(R.Proccedat, 0) / 100))
                               else C1.PU * C1.Cantacceptat end * COALESCE(C.Curs, 1) Valoare,
        O.CodObiect,
        Case when COALESCE(a.UM1,0) = 0 then CantAcceptat else AcceptUM1 end Cant,
        Case when COALESCE(a.UM1,0) = 0 then PU * COALESCE(C.Curs, 1) else PretUM1* COALESCE(C.Curs, 1) end PU
      FROM comanda c
        inner join RAC_REZ  R   on R.CodComanda   = C.CodComanda
        inner join comanda1 c1  on C1.CodComanda  = C.CodComanda and COALESCE(C1.TIPLINIESA,0) &lt;&gt; 2
        Inner join NGest    ng  on ng.CodGest     = R. CodGestSursa
        Inner join Npart    np  on NP.CODPART     = C.Partener
        LEFT  join Nparcaut na  on NA.CODNPARCAUT = COALESCE(C.MIJLTRANSP,0)
        LEFT  JOIN NartObj  o   on o.CodObiect    = c1.CodObiect
        LEFT  JOIN Nart     a   on a.CodArticol   = o.CodArticol
        LEFT  JOIN nechiv   e   ON e.codobiect    = c1.codobiect
        LEFT  JOIN grechiv  gre ON gre.codgrechiv = e.codgrupa
      WHERE c.codcomanda &gt; 0 and C.TipDoc = 94 and C.Operat = 1 and R.TipRezervare not in (3, 4, 5, 7)
        AND ( (R.DataStart &lt;= add_days(to_date(''' || gDataF || ''', ''dd.mm.yyyy''), 1) and (( COALESCE(R.Predat,0) = 1
        and R.DataPred &gt; add_days(to_date(''' || gDataF || ''', ''dd.mm.yyyy''), 1))or(COALESCE(R.Predat,0) = 0))) -- acumulate deskise
              or
              (COALESCE(R.Predat,0) = 1 and R.DataPred &gt;= to_date(''' || gDataS || ''',''dd.mm.yyyy'') and R.DataPred &lt; add_days(to_date(''' || gDataF || ''', ''dd.mm.yyyy''), 1)) -- acumulate inkise
            )
      UNION ALL
      SELECT
        C.Nrdoc Rezervare, C.Datadoc DATAREZ, R.NR_REF NRREF, C.SeriaDoc SeriaRez, R.TipRezervare, NG.DEN_GEST GESTIUNE, NP.DEN_PART CLIENT, NA.NRINREG NRAUTO, O.DENUMIRE ARTICOLE, GRE.DENUMIRE CLASAAUTO,
        c1.PUCORELAT PretOferta, c1.PU * COALESCE(C.Curs, 1) PUREZ, C1.CodComanda1, C.CodComanda CodComanda, C.TipDoc, 1 Cate, 0 Tip,
        CASE
          WHEN COALESCE(R.Predat,0) = 1 then (R.DataPred::date - R.DataStart::date)::numeric
          WHEN R.DataStop &gt;= add_days(to_date(''' || gDataF || ''', ''dd.mm.yyyy''), 1) then (R.DataStop::date - R.DataStart::date)::numeric
          ELSE (add_days(to_date(''' || gDataF || ''', ''dd.mm.yyyy''), 1) - R.DataStart::date)::numeric
        END Durata,
        CASE
          WHEN (COALESCE(R.Predat,0) = 1 and R.DataPred &gt;= to_date(''' || gDataS || ''', ''dd.mm.yyyy'') and R.DataPred &lt; add_days(to_date(''' || gDataF || ''', ''dd.mm.yyyy''), 1))
          THEN Case when R.DataStart &gt;= to_date(''' || gDataS || ''', ''dd.mm.yyyy'') then 0 ELSE (to_date(''' || gDataS || ''', ''dd.mm.yyyy'') - R.DataStart::date)::numeric end
          ELSE Case when R.DataStart &gt;= to_date(''' || gDataS || ''', ''dd.mm.yyyy'') then 0 else (to_date(''' || gDataS || ''', ''dd.mm.yyyy'') - R.DataStart::date)::numeric end +
                CASE when COALESCE(R.Predat,0) = 0 and R.DataStop &lt; (to_date(''' || gDataF || ''', ''dd.mm.yyyy'') + 1) then 0 else
          (COALESCE(R.DataPred,R.DataStop)::date - add_days(to_date(''' || gDataF || ''', ''dd.mm.yyyy''), 1))::numeric end
        END Depasire,
        C.CodGest,
        CASE when R.FaraTVA = 1 then 0 else fnc_getprocenttvaart(a.CodArticol,GETANLUCRU(),GETLUNALUCRU()) end PROCTVA,
        C1.PU * C1.Cantacceptat * COALESCE(C.Curs, 1) ValLinie,
        Case when COALESCE(C1.TIPLINIESA,0) = 2 then 100
              else COALESCE(R.Proccedat, 0) end Procent,
        Case when COALESCE(C1.TIPLINIESA,0) = 2 then C1.PU * C1.Cantacceptat
              else (C1.PU * C1.Cantacceptat * (COALESCE(R.Proccedat, 0) / 100)) end *COALESCE(C.Curs, 1) Valoare,
        O.CodObiect,
        CASE WHEN COALESCE(a.UM1,0) = 0 then CantAcceptat else AcceptUM1 end Cant,
        --Case when COALESCE(a.UM1,0) = 0 then PU           else PretUM1   end PU
        Case when COALESCE(a.UM1,0) = 0 then PU * COALESCE(C.Curs, 1) else PretUM1* COALESCE(C.Curs, 1) end PU
      FROM comanda c
        inner join RAC_REZ  R   on R.CodComanda   = C.CodComanda
        inner join comanda1 c1  on C1.CodComanda  = C.CodComanda
        left  join NGest    ng  on ng.CodGest     = COALESCE(C.CodGest,0)
        Inner join Npart    np  on NP.CODPART     = C.Partener
        LEFT  join Nparcaut na  on NA.CODNPARCAUT = COALESCE(C.MIJLTRANSP,0)
        LEFT  JOIN NartObj  o   on o.CodObiect    = c1.CodObiect
        LEFT  JOIN Nart     a   on a.CodArticol   = o.CodArticol
        LEFT  JOIN nechiv   e   ON e.codobiect    = c1.codobiect and NVL(E.Ind,0) in (1,2000)
        LEFT  JOIN grechiv  gre ON gre.codgrechiv = e.codgrupa
      WHERE c.codcomanda &gt; 0 and nvl(C.CodGest, 0) &gt; 0 and C.TipDoc = 94 and C.Operat = 1 and R.TipRezervare not in (3, 4, 5, 7)
        and (( nvl(c1.tipliniesa,0)&lt;&gt;0) or (nvl(c1.tipliniesa,0)=0 and E.ind in (1,2000)))
        AND ( (R.DataStart &lt;= add_days(to_date(''' || gDataF || ''', ''dd.mm.yyyy''), 1) and (( COALESCE(R.Predat,0) = 1
        and R.DataPred &gt; add_days(to_date(''' || gDataF || ''', ''dd.mm.yyyy''), 1))or(COALESCE(R.Predat,0) = 0))) -- acumulate deskise
              or
              (COALESCE(R.Predat,0) = 1 and R.DataPred &gt;= to_date(''' || gDataF || ''', ''dd.mm.yyyy'') and R.DataPred &lt; add_days(to_date(''' || gDataF || ''', ''dd.mm.yyyy''), 1)) -- acumulate inkise
            )
    ) R
      LEFT JOIN (
        SELECT C.CODCOMANDA, COALESCE(C1.ACCEPTUM1, 0) Zile
        FROM comanda c
          inner join RAC_REZ  R  on R.CodComanda  = C.CodComanda
          inner join comanda1 c1 on C1.CodComanda = C.CodComanda
          inner join NEchiv   E  on E.Codobiect   = c1.CodObiect and E.Ind = ' || coalesce(GrupaAuto::varchar,'') || '
        where c.codcomanda &gt; 0 and C1.CantAcceptat = 1
      ) Rz on Rz.CodComanda = R.Codcomanda
      where COALESCE(R.durata,0) &lt;&gt; 0';
  sInsert := 'INSERT INTO ' || tmpName || '(
      NAV_CodDoc, NAV_TipDoc, CODGEST, CODSUBUNIT, JUDET,
      REZERVARE, DATAREZ, NRREF, SeriaRez, TipRez,
      GESTIUNE, CLIENT, NRAUTO, ARTICOLE, CLASAAUTO,
      ZILER, TOTALZILER, PretOferta, PUREZ,  PUREZTVA,
      CODCOMANDA, Cate,depasire,  Valoare, Cant,PU,ProcCedat,PUReal' || gUserFields || ')
    SELECT
      TMP.NAV_CodDoc, TMP.NAV_TipDoc, TMP.CodGest, CMD.SUBUNITATEA CODSUBUNIT, J.SIMBAUTO JUDET,
      TMP.Rezervare, TMP.DataRez, TMP.NrRef, TMP.SeriaRez, TMP.TipRez,
      TMP.Gestiune, TMP.Client, TMP.NrAuto, TMP.Articole, TMP.ClasaAuto,
      Round(TMP.Durata * TMP.K, 3) ZileR, TMP.Durata TotalZileR, TMP.PretOferta, TMP.PUREZ, TMP.ValTotala PUREZTVA,
      TMP.CodComanda, TMP.Cate, TMP.Depasire depasire, Round(TMP.ValTotala * TMP.K, 3) Valoare, TMP.Cant, TMP.PU,
      COALESCE(TMP.Procent,0), Case when COALESCE(Durata,0) = 0 then 0 else Round(TMP.ValTotala /DURATA, 7) end' || gUserAlias || '
    FROM TMP_LST_VENITURIRAC TMP
      LEFT JOIN NAGENDA  A   on A.CODGEST      = TMP.CODGEST
      LEFT JOIN NLOCALIT L   on A.CODLOCALIT   = L.CODLOCALIT
      LEFT JOIN NJUDET   J   on J.CODJUDET     = L.CodJUDET
      LEFT JOIN RAC_REZ  RAC on RAC.CODComanda = TMP.CODComanda
      LEFT JOIN COMANDA  CMD on CMD.CODComanda = TMP.CODComanda ' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsTmp, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_postcalcul_sp_postrecords</obj_name>
  <obj_hashval>7ed23f32e7a9e35679f1a05316b6411e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_postcalcul_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  V_REC_SUB RECORD;
  aNest numeric;
  aCod  numeric;
  Nr    numeric;
BEGIN
  --Florin 17.06.2025 - sinc. Oracle
  IF  OPERATION = 0 THEN
    SELECT CODPC INTO RECID FROM TMP_PCALCUL;

    UPDATE PCALCUL
    SET
    (AN, LUNA, SUBUNITATEA, CUMULAT, operat, VARIANTA, DATADOC, TIPPUNCT, OBSERVATII, TipAloc, ValF)
    =
    (SELECT AN, LUNA, SUBUNITATEA, CUMULAT, operat, VARIANTA, DATADOC, TIPPUNCT, OBSERVATII, TipAloc, ValF FROM TMP_PCALCUL)
    WHERE
     CODPC = RECID;

    DELETE FROM PCGEST WHERE CODPC = RECID AND CODPCGEST NOT IN (SELECT CODPCGEST FROM TMP_PCGEST);

    FOR V_REC IN (SELECT * FROM TMP_PCGEST) LOOP
      IF  v_rec.codpcgest &gt; 0 THEN
        UPDATE PCGEST
        SET
        PUNCTE  = v_Rec.PUNCTE,
        MANS    = v_Rec.MANS,
        VALi    = v_Rec.VALi,
        VALa    = v_Rec.VALa,
        ValG    = v_Rec.ValG,
        ValC    = v_Rec.ValC,
        ValMat  = v_Rec.ValMat,
        ValMan  = v_Rec.ValMan,
        CODGEST = v_Rec.CodGest
        WHERE
         CODPCGEST = V_REC.CODPCGEST;
      ELSE
        INSERT INTO pcgest(CODPCGEST, CODPC, PUNCTE, MANS, VALi, VALa, ValG, ValC, ValMat, ValMan, CODGEST)
        VALUES(NEXTVAL('SEQ_PCGEST_CODPCGEST'), recid, v_Rec.PUNCTE, v_Rec.MANS, v_Rec.VALi, v_Rec.VALa, v_Rec.ValG, v_Rec.ValC, v_Rec.ValMat, v_Rec.ValMan, v_Rec.codgest);
      END IF;
    END LOOP;

    DELETE FROM PCART WHERE CODPC = RECID AND CODPCART NOT IN (SELECT CODPCART FROM TMP_PCART);

    FOR V_REC IN (SELECT * FROM TMP_PCART) LOOP
      IF  v_rec.codpcart &gt; 0 THEN
        UPDATE PCART
        SET
        CODCMD1     = v_rec.codcmd1,
        CODGEST     = v_rec.CODGEST,
        CODFORMATIE = v_rec.CODFORMATIE,
        COEF        = v_rec.COEF,
        MAN         = v_rec.MAN,
        VALMAN      = v_rec.VALMAN,
        CODCC       = v_rec.CodCC,
        CODIOART    = v_rec.codioart,
        CANT        = v_Rec.Cant,
        CANTTOT     = v_Rec.CantTot,
        VAL         = v_rec.val,
        VALS        = v_rec.vals,
        VALi        = v_rec.VALi,
        VALa        = v_rec.VALa,
        ValG        = v_Rec.ValG,
        ValC        = v_Rec.ValC,
        PUNCTE      = v_rec.PUNCTE,
        MAT         = v_rec.MAT,
        CODCMDPRODMAT = V_REC.CODCMDPRODMAT,
        VALLINIE    = V_REC.VALLINIE,
        VALTOT      = V_REC.VALTOT
        WHERE
         CODPCART = V_REC.CODPCART;
      ELSE
        INSERT INTO pcart(CODPCART, CODPC, CODCMD1, CODGEST, CODFORMATIE, COEF, MAN, VALMAN, CODCC, CODIOART, CANT, CANTTOT, VAL, VALS, VALi, VALa, ValG, ValC, PUNCTE, MAT,
        CODCMDPRODMAT,
        VALLINIE,
        VALTOT)
        VALUES(NEXTVAL('SEQ_PCART_CODPCART'), recid, v_rec.CODCMD1, v_rec.CODGEST, v_rec.CODFORMATIE, v_rec.COEF, v_rec.MAN, v_rec.VALMAN, v_rec.CODCC, v_rec.CODIOART, v_rec.CANT, v_rec.CANTTOT, v_rec.VAL, v_rec.VALS, v_rec.VALi, v_rec.VALa, v_rec.ValG, v_rec.ValC, v_rec.PUNCTE, v_rec.MAT,
          V_REC.CODCMDPRODMAT,
          V_REC.VALLINIE,
          V_REC.VALTOT);
      END IF;
    END LOOP;

    DELETE FROM PCDIR WHERE CODPC = RECID AND CODPCDIR NOT IN (SELECT CODPCDIR FROM TMP_PCDIR);

    FOR V_REC IN (SELECT * FROM TMP_PCDIR) LOOP
      aNEst := COALESCE( v_Rec.Codnest, 0);
      IF  aNest = 0 THEN
        aNest := (SELECT PKG_Jurnal_GetCodNestJurnal.WME_RESULT FROM PKG_Jurnal_GetCodNestJurnal(NULL, v_rec.CodD, v_rec.CodC, v_rec.CodGest, v_rec.CodCC));
      END IF;

      IF  v_rec.codpcdir &gt; 0 THEN
        UPDATE PCDIR
        SET
        CODNEST = anest,
        CODCMD1 = v_Rec.CodCMD1,
        VAL     = v_rec.val
        WHERE
         CODPCDIR = V_REC.CODPCDIR;
      ELSE
        INSERT INTO pcdir(CODPCDIR, CODPC, CODNEST, CodCMD1, VAL)
        VALUES(NEXTVAL('SEQ_PCDIR_CODPCDIR'), recid, aNEST, v_rec.CodCMD1, v_rec.VAL);
      END IF;
    END LOOP;

    DELETE FROM PCSECTII
    WHERE CODPC = RECID
      AND CODPCSECTII NOT IN (SELECT CODPCSECTII FROM TMP_PCSECTII
                              union ALL
                              SELECT CODPCSECTII2 AS CODPCSECTII FROM TMP_PCSECTII2
                              union ALL
                              SELECT CODPCSECTII3 AS CODPCSECTII FROM TMP_PCSECTII3
                              union ALL
                              SELECT CODPCSECTII5 AS CODPCSECTII FROM TMP_PCSECTII5
                              union ALL
                              SELECT CODPCSECTII4 AS CODPCSECTII FROM TMP_PCSECTII4
                              );

    FOR V_REC IN (SELECT * FROM TMP_PCSECTII) LOOP
      aNEst := COALESCE( v_Rec.Codnest, 0);
      IF  aNest = 0 THEN
        aNest := (SELECT PKG_Jurnal_GetCodNestJurnal.WME_RESULT FROM PKG_Jurnal_GetCodNestJurnal(NULL, v_rec.CodD, v_rec.CodC, v_rec.CodGest, v_rec.CodCC));
      END IF;

      IF  v_rec.codpcsectii &gt; 0 THEN
        UPDATE PCSECTII
        SET
        CODNEST = anest,
        FAZA    = 0,
        VAL     = v_rec.val
        WHERE
         CODPCSECTII = V_REC.CODPCSECTII;
      ELSE
        INSERT INTO pcsectii(CODPCSECTII, CODPC, CODNEST, FAZA, VAL)
        VALUES(NEXTVAL('SEQ_PCSECTII_CODPCSECTII'), recid, anest, 0, v_Rec.val);
      END IF;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_PCSECTII2) LOOP
      aNEst := COALESCE( v_Rec.Codnest, 0);
      IF  aNest = 0 THEN
        aNest := (SELECT PKG_Jurnal_GetCodNestJurnal.WME_RESULT FROM PKG_Jurnal_GetCodNestJurnal(NULL, v_rec.CodD, v_rec.CodC, v_rec.CodGest, v_rec.CodCC));
      END IF;

      IF  v_rec.codpcsectii2 &gt; 0 THEN
        UPDATE PCSECTII
        SET
        CODNEST = anest,
        FAZA    = 2,
        VAL     = v_rec.val
        WHERE
         CODPCSECTII = V_REC.CODPCSECTII2;
      ELSE
        INSERT INTO pcsectii(CODPCSECTII, CODPC, CODNEST, FAZA, VAL)
        VALUES(NEXTVAL('SEQ_PCSECTII_CODPCSECTII'), recid, anest, 2, v_Rec.val);
      END IF;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_PCSECTII3) LOOP
      aNEst := COALESCE( v_Rec.Codnest, 0);
      IF  aNest = 0 THEN
        aNest := (SELECT PKG_Jurnal_GetCodNestJurnal.WME_RESULT FROM PKG_Jurnal_GetCodNestJurnal(NULL, v_rec.CodD, v_rec.CodC, v_rec.CodGest, v_rec.CodCC));
      END IF;

      IF  v_rec.codpcsectii3 &gt; 0 THEN
        UPDATE PCSECTII
        SET
        CODNEST = anest,
        FAZA = 3,
        VAL = v_rec.val
        WHERE
         CODPCSECTII = V_REC.CODPCSECTII3;
      ELSE
        INSERT INTO pcsectii(CODPCSECTII, CODPC, CODNEST, FAZA, VAL)
        VALUES(NEXTVAL('SEQ_PCSECTII_CODPCSECTII'), recid, anest, 3, v_Rec.val);
      END IF;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_PCSECTII4) LOOP
      aNEst := COALESCE( v_Rec.Codnest, 0);
      IF  aNest = 0 THEN
        aNest := (SELECT PKG_Jurnal_GetCodNestJurnal.WME_RESULT FROM PKG_Jurnal_GetCodNestJurnal(NULL, v_rec.CodD, v_rec.CodC, v_rec.CodGest, v_rec.CodCC));
      END IF;

      IF  v_rec.codpcsectii4 &gt; 0 THEN
        UPDATE PCSECTII
        SET
        CODNEST = anest,
        FAZA    = 4,
        VAL     = v_rec.val
        WHERE
         CODPCSECTII = V_REC.CODPCSECTII4;
      ELSE
        INSERT INTO pcsectii(CODPCSECTII, CODPC, CODNEST, FAZA, VAL)
        VALUES(NEXTVAL('SEQ_PCSECTII_CODPCSECTII'), recid, anest, 4, v_Rec.val);
      END IF;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_PCSECTII5) LOOP
      aNEst := COALESCE( v_Rec.Codnest, 0);
      IF  aNest = 0 THEN
        aNest := (SELECT PKG_Jurnal_GetCodNestJurnal.WME_RESULT FROM PKG_Jurnal_GetCodNestJurnal(NULL, v_rec.CodD, v_rec.CodC, v_rec.CodGest, v_rec.CodCC));
      END IF;

      IF  v_rec.codpcsectii5 &gt; 0 THEN
        UPDATE PCSECTII
        SET
        CODNEST = anest,
        FAZA    = 5,
        VAL     = v_rec.val
        WHERE
         CODPCSECTII = V_REC.CODPCSECTII5;
      ELSE
        INSERT INTO pcsectii(CODPCSECTII, CODPC, CODNEST, FAZA, VAL)
        VALUES(NEXTVAL('SEQ_PCSECTII_CODPCSECTII'), recid, anest, 5, v_Rec.val);
      END IF;
    END LOOP;

    DELETE FROM JURNAl1 WHERE TIPDOC = 72 AND  CODDOC = RECID AND CODJURNAL1 NOT IN (SELECT CODJURNAL1 FROM TMP_JURNAl1);

    FOR V_REC IN (SELECT * FROM TMP_JURNAL1) LOOP
      IF  V_REC.CODJURNAL1 &gt; 0 THEN
        UPDATE JURNAL1
        SET
        CODDOC        = V_REC.CODDOC,
        TIPDOC        = V_REC.TIPDOC,
        INDEXLOCAL    = V_REC.INDEXLOCAL,
        CODBAZAD      = V_REC.CODBAZAD,
        ICONTBAZAD    = V_REC.ICONTBAZAD,
        TIPBAZAD      = V_REC.TIPBAZAD,
        CODBAZAC      = V_REC.CODBAZAC,
        ICONTBAZAC    = V_REC.ICONTBAZAC,
        TIPBAZAC      = V_REC.TIPBAZAC,
        CODDESCRD     = V_REC.CODDESCRD,
        ICONTD        = V_REC.ICONTD,
        TIPCONTD      = V_REC.TIPCONTD,
        ANALITICCONTD = V_REC.ANALITICCONTD,
        CODDESCRC     = V_REC.CODDESCRC,
        ICONTC        = V_REC.ICONTC,
        TIPCONTC      = V_REC.TIPCONTC,
        ANALITICCONTC = V_REC.ANALITICCONTC,
        GEST          = V_REC.GEST,
        VALOARE       = V_REC.VALOARE,
        VALOAREV      = V_REC.VALOAREV,
        OBS           = V_REC.OBS,
        AN            = V_REC.AN,
        LUNA          = V_REC.LUNA,
        DIRTY         = V_REC.DIRTY,
        SUBUNITATEA   = V_REC.SUBUNITATEA,
        CODCENTRU     = V_REC.CODCENTRU,
        DATADOC       = V_REC.DATADOC,
        DOCUMENT      = V_REC.DOCUMENT
        WHERE
         CODJURNAL1 = V_REC.CODJURNAl1;
      ELSE
        INSERT INTO JURNAL1 (CODJURNAL1, CODDOC, TIPDOC, INDEXLOCAL, CODBAZAD, ICONTBAZAD, TIPBAZAD, CODDESCRD, ICONTD, TIPCONTD, ANALITICCONTD, CODBAZAC, ICONTBAZAC, TIPBAZAC, CODDESCRC, ICONTC, TIPCONTC, ANALITICCONTC, GEST, VALOARE, VALOAREV, OBS, AN, LUNA, DIRTY, SUBUNITATEA, CODCENTRU, DATADOC, DOCUMENT)
        VALUES(NEXTVAL('SEQ_JURNAL1_CODJURNAL1'), RECID, V_REC.TIPDOC, V_REC.INDEXLOCAL, V_REC.CODBAZAD, V_REC.ICONTBAZAD, V_REC.TIPBAZAD, V_REC.CODDESCRD, V_REC.ICONTD, V_REC.TIPCONTD, V_REC.ANALITICCONTD, V_REC.CODBAZAC, V_REC.ICONTBAZAC, V_REC.TIPBAZAC, V_REC.CODDESCRC, V_REC.ICONTC, V_REC.TIPCONTC, V_REC.ANALITICCONTC, V_REC.GEST, V_REC.VALOARE, V_REC.VALOAREV, V_REC.OBS, V_REC.AN, V_REC.LUNA, V_REC.DIRTY, V_REC.SUBUNITATEA, V_REC.CODCENTRU, V_REC.DATADOC, V_REC.DOCUMENT);
      END IF;
    END LOOP;

    DELETE FROM JURNAL WHERE TIPDOC = 72 AND  CODDOC = RECID AND CODJURNAL NOT IN (SELECT CODJURNAL FROM TMP_JURNAl);

    FOR V_REC IN (SELECT * FROM TMP_JURNAL) LOOP
      IF  V_REC.CODJURNAL &gt; 0 THEN
        UPDATE JURNAL
        SET
        CODDOC      = V_REC.CODDOC,
        TIPDOC      = V_REC.TIPDOC,
        INDEXLOCAL  = V_REC.INDEXLOCAL,
        CONTD       = V_REC.CONTD,
        CONTC       = V_REC.CONTC,
        GEST        = V_REC.GEST,
        VALOARE     = V_REC.VALOARE,
        VALOAREV    = V_REC.VALOAREV,
        OBS         = V_REC.OBS,
        AN          = V_REC.AN,
        LUNA        = V_REC.LUNA,
        SUBUNITATEA = V_REC.SUBUNITATEA,
        CODCENTRU   = V_REC.CODCENTRU,
        DATADOC     = V_REC.DATADOC,
        DOCUMENT    = V_REC.DOCUMENT
        WHERE
         CODJURNAL = V_REC.CODJURNAl;
      ELSE
        INSERT INTO JURNAL(CODJURNAL, CODDOC, TIPDOC, INDEXLOCAL, CONTD, CONTC, GEST, VALOARE, VALOAREV, OBS, AN, LUNA, SUBUNITATEA, CODCENTRU, DATADOC, DOCUMENT)
        VALUES(NEXTVAL('SEQ_JURNAL_CODJURNAL'), RECID, V_REC.TIPDOC, V_REC.INDEXLOCAL, V_REC.CONTD, V_REC.CONTC, V_REC.GEST, V_REC.VALOARE, V_REC.VALOAREV, V_REC.OBS, V_REC.AN, V_REC.LUNA, V_REC.SUBUNITATEA, V_REC.CODCENTRU, V_REC.DATADOC, V_REC.DOCUMENT);
      END IF;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_PCALCUL_CODPC') INTO RECID;

    INSERT INTO PCALCUL(CODPC, AN, LUNA, SUBUNITATEA, CUMULAT, operat, VARIANTA, DATADOC, TIPPUNCT, OBSERVATII, TipAloc, ValF)
    SELECT RECID, AN, LUNA, SUBUNITATEA, CUMULAT, operat, VARIANTA, DATADOC, TIPPUNCT, OBSERVATII, TipAloc, ValF FROM TMP_PCALCUL;

    INSERT INTO pcgest(CODPCGEST, CODPC, PUNCTE, MANS, VALi, VALa, ValG, ValC, ValMat, ValMan, CODGEST)
    SELECT NEXTVAL('SEQ_PCGEST_CODPCGEST'), recid, PUNCTE, MANS, VALi, VALa, ValG, ValC, ValMat, ValMan, CODGEST FROM TMP_PCGEST;

    INSERT INTO pcart(CODPCART, CODPC, CODCMD1, CODGEST, CODFORMATIE, COEF, MAN, VALMAN, CODCC, CODIOART, CANT, CANTTOT, VAL, VALi, VALa, VALS, ValG, ValC, PUNCTE, MAT, CODCMDPRODMAT, VALLINIE, VALTOT)
        SELECT NEXTVAL('SEQ_PCART_CODPCART'), recid, CODCMD1, CODGEST, CODFORMATIE, COEF, MAN, VALMAN, CODCC, CODIOART, CANT, CANTTOT, VAL, VALi, VALa, VALS, ValG, ValC, PUNCTE, MAT, CODCMDPRODMAT, VALLINIE, VALTOT
        FROM TMP_PCART;

    INSERT INTO pcdir(CODPCDIR, CODPC, CODNEST, CodCMD1, VAL)
    SELECT NEXTVAL('SEQ_PCDIR_CODPCDIR'), recid, (SELECT PKG_Jurnal_GetCodNestJurnal.WME_RESULT FROM PKG_Jurnal_GetCodNestJurnal(NULL, CodD, CodC, CodGest, CodCC)), CodCMD1, VAL
    FROM TMP_PCDIR;

    INSERT INTO pcsectii(CODPCSECTII, CODPC, CODNEST, FAZA, VAL)
    SELECT NEXTVAL('SEQ_PCSECTII_CODPCSECTII'), recid, (SELECT PKG_Jurnal_GetCodNestJurnal.WME_RESULT FROM PKG_Jurnal_GetCodNestJurnal(NULL, CodD, CodC, CodGest, CodCC)), 0, val
    FROM TMP_PCSECTII;

    INSERT INTO pcsectii(CODPCSECTII, CODPC, CODNEST, FAZA, VAL)
    SELECT NEXTVAL('SEQ_PCSECTII_CODPCSECTII'), recid, (SELECT PKG_Jurnal_GetCodNestJurnal.WME_RESULT FROM PKG_Jurnal_GetCodNestJurnal(NULL, CodD, CodC, CodGest, CodCC)), 2, val
    FROM TMP_PCSECTII2;

    INSERT INTO pcsectii(CODPCSECTII, CODPC, CODNEST, FAZA, VAL)
    SELECT NEXTVAL('SEQ_PCSECTII_CODPCSECTII'), recid, (SELECT PKG_Jurnal_GetCodNestJurnal.WME_RESULT FROM PKG_Jurnal_GetCodNestJurnal(NULL, CodD, CodC, CodGest, CodCC)), 3, val
    FROM TMP_PCSECTII3;

    INSERT INTO pcsectii(CODPCSECTII, CODPC, CODNEST, FAZA, VAL)
    SELECT NEXTVAL('SEQ_PCSECTII_CODPCSECTII'), recid, (SELECT PKG_Jurnal_GetCodNestJurnal.WME_RESULT FROM PKG_Jurnal_GetCodNestJurnal(NULL, CodD, CodC, CodGest, CodCC)), 4, val
    FROM TMP_PCSECTII4;

    INSERT INTO pcsectii(CODPCSECTII, CODPC, CODNEST, FAZA, VAL)
    SELECT NEXTVAL('SEQ_PCSECTII_CODPCSECTII'), recid, (SELECT PKG_Jurnal_GetCodNestJurnal.WME_RESULT FROM PKG_Jurnal_GetCodNestJurnal(NULL, CodD, CodC, CodGest, CodCC)), 5, val
    FROM TMP_PCSECTII5;

    INSERT INTO JURNAL1(CODJURNAL1, CODDOC, TIPDOC, INDEXLOCAL, CODBAZAD, ICONTBAZAD, TIPBAZAD, CODDESCRD, ICONTD, TIPCONTD, ANALITICCONTD, CODBAZAC, ICONTBAZAC, TIPBAZAC, CODDESCRC, ICONTC, TIPCONTC, ANALITICCONTC, GEST, VALOARE, VALOAREV, OBS, AN, LUNA, DIRTY, SUBUNITATEA, CODCENTRU, DATADOC, DOCUMENT)
    (SELECT NEXTVAL('SEQ_JURNAL1_CODJURNAL1'), RECID, TIPDOC, INDEXLOCAL, CODBAZAD, ICONTBAZAD, TIPBAZAD, CODDESCRD, ICONTD, TIPCONTD, ANALITICCONTD, CODBAZAC, ICONTBAZAC, TIPBAZAC, CODDESCRC, ICONTC, TIPCONTC, ANALITICCONTC, GEST, VALOARE, VALOAREV, OBS, AN, LUNA, DIRTY, SUBUNITATEA, CODCENTRU, DATADOC, DOCUMENT
     FROM TMP_JURNAL1
    );

    INSERT INTO JURNAL(CODJURNAL, CODDOC, TIPDOC, INDEXLOCAL, CONTD, CONTC, GEST, VALOARE, VALOAREV, OBS, AN, LUNA, SUBUNITATEA, CODCENTRU, DATADOC, DOCUMENT)
    (SELECT NEXTVAL('SEQ_JURNAL_CODJURNAL'), RECID, TIPDOC, INDEXLOCAL, CONTD, CONTC, GEST, VALOARE, VALOAREV, OBS, AN, LUNA, SUBUNITATEA, CODCENTRU, DATADOC, DOCUMENT
     FROM TMP_JURNAL
    );
  END IF;

  FOR V_REC IN (SELECT * FROM TMP_RULAJ) LOOP
    SELECT COUNT( *) INTO NR FROM NCONTRUL
    WHERE CODCONT = V_REC.CODCONT AND  AN = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') AND  LUNA = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999');

    IF  NR = 0 THEN
      INSERT INTO NCONTRUL(CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, AN, LUNA)
      VALUES(NEXTVAL('SEQ_NCONTRUL_CODCONTRUL'), V_REC.CODCONT, 0, 0, 0, 0, 0, 0, 0, 0, TO_NUMBER(( current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999'), TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999'));
    END IF;

    UPDATE NCONTRUL
    SET
    RULAJCD  = RULAJCD  + (CASE WHEN  V_REC.TIP = 'D' THEN V_REC.VALOARE  ELSE 0 END ) ,
    RULAJCC  = RULAJCC  + (CASE WHEN  V_REC.TIP = 'C' THEN V_REC.VALOARE  ELSE 0 END ) ,
    RULAJVCD = RULAJVCD + (CASE WHEN  V_REC.TIP = 'D' THEN V_REC.VALOAREV ELSE 0 END ) ,
    RULAJVCC = RULAJVCC + (CASE WHEN  V_REC.TIP = 'C' THEN V_REC.VALOAREV ELSE 0 END )
    WHERE
     CODCONT = V_REC.CODCONT AND  AN = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') AND  LUNA = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999');

    IF  COALESCE( V_REC.SUBUNITATEA, 0) &lt;&gt; 0 THEN
      FOR V_REC_SUB IN (SELECT * FROM NCONTRUL
                        WHERE  CODCONT = V_REC.CODCONT
                          AND  AN      = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU'  , true)),'999999999999999999')
                          AND  LUNA    = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999')
                       )
      LOOP
        SELECT COUNT( *) INTO NR FROM NCONTRULSUB WHERE CODCONTRUL = V_REC_SUB.CODCONTRUL AND  SUBUNITATEA = V_REC.SUBUNITATEA;

        IF  NR = 0 THEN
          INSERT INTO NCONTRULSUB(CODCONTRULSUB, CODCONTRUL, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, SUBUNITATEA)
          VALUES(NEXTVAL('SEQ_NCONTRULSUB_CODRULSUB'), V_REC_SUB.CODCONTRUL, 0, 0, 0, 0, 0, 0, 0, 0, V_REC.SUBUNITATEA);
        END IF;

        UPDATE NCONTRULSUB
        SET
        RULAJCD  = RULAJCD  + (CASE WHEN  V_REC.TIP = 'D' THEN V_REC.VALOARE  ELSE 0 END ) ,
        RULAJCC  = RULAJCC  + (CASE WHEN  V_REC.TIP = 'C' THEN V_REC.VALOARE  ELSE 0 END ) ,
        RULAJVCD = RULAJVCD + (CASE WHEN  V_REC.TIP = 'D' THEN V_REC.VALOAREV ELSE 0 END ) ,
        RULAJVCC = RULAJVCC + (CASE WHEN  V_REC.TIP = 'C' THEN V_REC.VALOAREV ELSE 0 END )
        WHERE
         CODCONTRUL = V_REC_SUB.CODCONTRUL AND  SUBUNITATEA = V_REC.SUBUNITATEA;
      END LOOP;
    END IF;
  END LOOP;

  PERFORM PKG_GLOBALS_MarkDirtyJurnal();
  PERFORM NotifyModif( Operation, RecId, 'PCALCUL');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_updatepretfixmat</obj_name>
  <obj_hashval>779bbd263844cd12e0913a198899011f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_updatepretfixmat(acodobiect numeric, apret numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  UPDATE prodmat SET pret = aPret WHERE pret = 0 and  codobiect = aCodObiect;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selurmofe_totipart</obj_name>
  <obj_hashval>f5c6da3b155823e5cc3848a1677a1aa1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selurmofe_totipart()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 09.09.2020
  return current_setting ('PKG_LIST_SELURMOFE.vTotiPart', true)::numeric = 1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_cloneaza_obiect</obj_name>
  <obj_hashval>d8ed48c190e6f4851a952745a0719d5b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_cloneaza_obiect(INOUT wme_result numeric, INOUT acodarticol numeric, acodatribut numeric, vcodprodus numeric, OUT vcodatribut numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC                RECORD;
  V_LANG               RECORD;
  V_ATRIB              RECORD;
  CodObjSursa          numeric;
  codObjNou            numeric;
  denObjNou            varchar;
  CodExtObjSursa       varchar := null;
  CodExtObjNou         varchar;
  CodIntObjNou         varchar;
  KConst               numeric;
  KConst1              numeric;
  KConst2              numeric;
  ModDepozitareGeneric numeric;
  CodVamalGeneric      numeric;
  Prox                 numeric;
  MAJORARE             numeric := 1;
  MaxGRUPA             varchar := '';
  aOrdine              varchar := '';
  MaxOrdine            varchar := '';
  CaractObiectGeneric  varchar;
  aDenTrad             varchar;
  aAreTrad             numeric;
  aBifaTrad            numeric;
  V_TMP                record;
  kArtBlocat           NUMERIC(20);
  kRotIntrImplicita    NUMERIC(20);
  kRotIesImplicita     NUMERIC(20);
BEGIN
  --Florin 22.11.2024 - sinc. Oracle
  --Florin 30.05.2024 - sinc. Oracle
  --Florin 31.08.2023 - fixat 59304
  --Florin 01.06.2023 - sinc. Oracle
  --Florin 16.03.2023 - sinc. Oracle
  --Florin 16.01.2022 - sinc. Oracle
  --Florin 12.01.2023 - sinc. Oracle
  --Florin 20.10.2022 - sinc. Oracle
  --Laura 15.10.2021 - sinc Oracle (15.10.2021)
  --Adina 12.04.2021 - sinc.Oracle doar pe vers.la zi
  --Adina 12.03.2021 - prc_al_refresh
  --Adina 02.02.2021 - aranjat
  vCodAtribut := aCodAtribut;
  PERFORM PKG_NOM_ARTICOL_TMPORDINEGRUPEPRET();
-- caut obiectul generic fara atribute
  SELECT nobj.codobiect, nobj.denumire, nobj.codextern
  INTO CodObjSursa, denObjNou, CodExtObjSursa
  FROM nartobj nobj
  WHERE (SELECT COUNT(*) FROM NAtrObj AO WHERE AO.CodObiect = NOBJ.CodObiect) = 0
        and  nobj.codarticol = aCodArticol;

-- compun denumirea obiectului si codul extern ;
  KConst  := (fnc_GetValConstanta('CodExternAtrib', GetANLUCRU(), GetLUNALUCRU()));
  KConst1 := (fnc_GetValConstanta('GenCodExtArt'  , GetANLUCRU(), GetLUNALUCRU()));
  KConst2 := (fnc_GetValConstanta('GenCodIntArt'  , GetANLUCRU(), GetLUNALUCRU()));
  kArtBlocat := fnc_GetValConstanta('ArtBlocat', GetANLUCRU(), GetLUNALUCRU());
  kRotIntrImplicita := fnc_GetValConstanta('RotIntrImplicita', GetANLUCRU(), GetLUNALUCRU());
  kRotIesImplicita  := fnc_GetValConstanta('RotIesImplicita',  GetANLUCRU(), GetLUNALUCRU());

  ModDepozitareGeneric := COALESCE( (fnc_GetValConstanta('ModDepozitareGeneric', GetANLUCRU(), GetLUNALUCRU())), '');
  CodVamalGeneric      := COALESCE( (fnc_GetValConstanta('CodVamalGeneric'     , GetANLUCRU(), GetLUNALUCRU())), '');
  CodExtObjNou         := CodExtObjSursa;
  CaractObiectGeneric  := COALESCE( (fnc_GetValConstanta('CaractObiectGeneric' , GetANLUCRU(), GetLUNALUCRU())), '');

  FOR V_REC IN (SELECT ATR1.CODVALATR, ATR1.VALOARE, ATR.INDEXLOCAL, atr1.codextern, Atr1.Grupa
                FROM TMP_MANEVRA TMP
                     INNER JOIN NATRIB1 ATR1 ON  TMP.CODUNIC    = ATR1.CODVALATR
                     INNER JOIN NARTATR ATR  ON  ATR.CODATRIBUT = ATR1.CODATRIBUT
                WHERE ATR.CODARTICOL = aCodArticol
                ORDER BY ATR.INDEXLOCAL
               )
  LOOP
    aOrdine := '';
    BEGIN
      SELECT VALOARE INTO aOrdine FROM TMP_MANEVRA_LISTE WHERE Upper( COALESCE( filtru, '?')) = UPPER( COALESCE( V_Rec.Grupa, ''));
    EXCEPTION WHEN no_data_found THEN
      NULL;
    END;

    IF  COALESCE( aOrdine, '!') &lt;&gt; '!' THEN
      IF aOrdine &gt; MaxOrdine THEN
        MaxOrdine := aOrdine;
        MaxGrupa := UPPER( V_Rec.Grupa);
      END IF;
    ELSE
      IF  UPPER( COALESCE( V_Rec.Grupa, '!')) &gt; MaxGRUPA THEN
        MaxGrupa := UPPER( V_Rec.Grupa);
      END IF;
    END IF;

    BEGIN
      SELECT COALESCE( PROCMAJ, 0) INTO PROx FROM NATRIB2 WHERE CODVALATR = V_REC.CODVALATR AND  CODARTICOL = ACODARTICOL;
    EXCEPTION WHEN others THEN
      PROx := 0;
    END;

    MAJORARE := MAJORARE * (  1 + PROx / 100) ;

    denObjNou := denObjNou || ' ' || v_rec.valoare;

    IF  KConst = 3 THEN
      CodExtObjNou := NULL;
    ELSE
      IF  KConst = 1 THEN
        CodExtObjNou := CodExtObjNou || ' ' || v_rec.valoare;
      ELSE
        IF  KConst = 2 THEN
          CodExtObjNou := CodExtObjNou || v_rec.codextern;
        END IF;
      END IF;
    END IF;
  END LOOP;

  IF  KCONST1 = 1 THEN
    CodExtObjNou := (SELECT PKG_GENERARE_CODURI_GET_NEXT_CODEXTERN_ART.WME_RESULT FROM PKG_GENERARE_CODURI_GET_NEXT_CODEXTERN_ART(NULL, (SELECT PKG_GLOBALS_GETUSERID.WME_RESULT FROM PKG_GLOBALS_GETUSERID(NULL,NULL))));
  END IF;

  CodIntObjNou := '';
  IF  KCONST2 = 1 THEN
    CodIntObjNou := (SELECT PKG_GENERARE_CODURI_GET_NEXT_CODINTERN_ART.WME_RESULT FROM PKG_GENERARE_CODURI_GET_NEXT_CODINTERN_ART(NULL, (SELECT PKG_GLOBALS_GETUSERID.WME_RESULT FROM PKG_GLOBALS_GETUSERID(NULL,NULL))));
  END IF;

  SELECT NEXTVAL('SEQ_NARTOBJ_CODOBIECT') INTO codObjNou;

  INSERT INTO NARTOBJ(CODOBIECT, CODARTICOL, CODPRODUCATOR, CODEXTERN, CODINTERN, MASA, VOLUM, STOCMIN, STOCMED, INACTIVCMDONLINE, AUTORIZATIE,
                      EXPIRAREAUTORIZ, TRADUCARTGENERIC, MESAJINACTIV, STOCMAX, RETURNABIL, LUNIGARANTIE, OBS, PROCADAOSNIR, ROTUNJIRE, ADAOSEXCEPTIE,
                      PROMOTIE, ROTVALUTA, DENUMIRE, UMAMBALARE, PRETMINIM, TERMENPLATA, DATAADAUGARII, CODPLU, USESTOCMED, DURMAXAPROV, CODCNAS,
                      PRODUSPROPRIU, CODCARACT, CODD394, INACTIV, BLOCAT, DISCPROMO, TARAORIGINE, ZILEVALABIL, ZILEDISTRIB, CODPERISABIL, NEFACTURABIL,
                      GREUTSPECIFICA, COEFCNAS, RAPCNAS, ANTIBIOTIC, CODVAMAL, SAFT_EXPORT)
  SELECT codObjNou, CODARTICOL,
         CASE WHEN  CaractObiectGeneric = '1' THEN CODPRODUCATOR    ELSE NULL END ,
         CodExtObjNou, CodIntObjNou,
         CASE WHEN  CaractObiectGeneric = '1' THEN MASA             ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN VOLUM            ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN STOCMIN          ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN STOCMED          ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN INACTIVCMDONLINE ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN AUTORIZATIE      ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN EXPIRAREAUTORIZ  ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN TRADUCARTGENERIC ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN MESAJINACTIV     ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN STOCMAX          ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN RETURNABIL       ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN LUNIGARANTIE     ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN OBS              ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN PROCADAOSNIR     ELSE NULL END ,
         kRotIntrImplicita,
         CASE WHEN  CaractObiectGeneric = '1' THEN ADAOSEXCEPTIE    ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN PROMOTIE         ELSE NULL END ,
         kRotIntrImplicita,
         denObjNou,
         CASE WHEN  CaractObiectGeneric = '1' THEN UMAMBALARE       ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN PRETMINIM        ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN TERMENPLATA      ELSE NULL END ,
         CURRENT_TIMESTAMP,
         CASE WHEN  CaractObiectGeneric = '1' THEN CODPLU           ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN USESTOCMED       ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN DURMAXAPROV      ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN CODCNAS          ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN PRODUSPROPRIU    ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN CODCARACT        ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN CODD394          ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN INACTIV          ELSE NULL END ,
         CASE WHEN kArtBlocat = 1 then 1 ELSE 0 END,
         CASE WHEN  CaractObiectGeneric = '1' THEN DISCPROMO        ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN TARAORIGINE      ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN ZILEVALABIL      ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN ZILEDISTRIB      ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN CODPERISABIL     ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN NEFACTURABIL     ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN GREUTSPECIFICA   ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN COEFCNAS         ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN RAPCNAS          ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN ANTIBIOTIC      ELSE NULL END,
         CASE WHEN  CaractObiectGeneric = '1' AND  CodVamalGeneric = '1' THEN CODVAMAL ELSE NULL end,
         CASE WHEN CaractObiectGeneric = '1' THEN SAFT_EXPORT ELSE 1 END
  FROM NARTOBJ
  WHERE CODOBIECT = CodObjSursa;


  INSERT INTO NARTOBJ1(CODOBIECT1, CODOBIECT, PRETMAXIMAL, PROCADAOSMAXIMAL, ADAOSLA, ANSTART, LUNASTART, PRETREFERINTA, TIPPRETMAX, COMPENSAT,
                       TIPCOMPENSARE, GRUPA, UPLIFT, CODMONEDA, COST, PUNCTE, Umiditate, CORPURI_STRAINE, PUNCTESECTIE,
                       Incoltit, Hectolitrica, Gluten, Fuzaritate, Cadere, Deformare, Sticlozitate, Sparturi, proteina, aflatoxina, atac_plosnita, continut_ulei, aciditate,
                       sistave, refractie, indice_w, toxina_don, boabe_toxice,
    MAX_UMIDITATE,MAX_CORPURI_STRAINE,MAX_INCOLTIT,MAX_HECTOLITRICA,MAX_GLUTEN,MAX_FUZARITATE,MAX_CADERE,MAX_DEFORMARE,
    MAX_STICLOZITATE,MAX_SPARTURI,MAX_PROTEINA,MAX_AFLATOXINA,MAX_ATAC_PLOSNITA,MAX_CONTINUT_ULEI,MAX_ACIDITATE,MAX_SISTAVE,
    MAX_REFRACTIE,MAX_INDICE_W,MAX_TOXINA_DON,MAX_BOABE_TOXICE,
    MIN_UMIDITATE,MIN_CORPURI_STRAINE,MIN_INCOLTIT,MIN_HECTOLITRICA,MIN_GLUTEN,MIN_FUZARITATE,MIN_CADERE,MIN_DEFORMARE,MIN_STICLOZITATE,MIN_SPARTURI,
    MIN_PROTEINA,MIN_AFLATOXINA,MIN_ATAC_PLOSNITA,MIN_CONTINUT_ULEI,MIN_ACIDITATE,MIN_SISTAVE,MIN_REFRACTIE,MIN_INDICE_W,MIN_TOXINA_DON,MIN_BOABE_TOXICE, PretProd)
  SELECT NEXTVAL('SEQ_NARTOBJ1_CODOBIECT1'), codObjNou, PRETMAXIMAL, PROCADAOSMAXIMAL, ADAOSLA, ANSTART, LUNASTART, PRETREFERINTA, TIPPRETMAX, COMPENSAT,
         TIPCOMPENSARE, GRUPA, UPLIFT, CODMONEDA, COST, PUNCTE, Umiditate, CORPURI_STRAINE, PUNCTESECTIE,
         Incoltit, Hectolitrica, Gluten, Fuzaritate, Cadere, Deformare, Sticlozitate, Sparturi, proteina, aflatoxina, atac_plosnita, continut_ulei, aciditate,
         sistave, refractie, indice_w, toxina_don, boabe_toxice,
    MAX_UMIDITATE,MAX_CORPURI_STRAINE,MAX_INCOLTIT,MAX_HECTOLITRICA,MAX_GLUTEN,MAX_FUZARITATE,MAX_CADERE,MAX_DEFORMARE,
    MAX_STICLOZITATE,MAX_SPARTURI,MAX_PROTEINA,MAX_AFLATOXINA,MAX_ATAC_PLOSNITA,MAX_CONTINUT_ULEI,MAX_ACIDITATE,MAX_SISTAVE,
    MAX_REFRACTIE,MAX_INDICE_W,MAX_TOXINA_DON,MAX_BOABE_TOXICE,
    MIN_UMIDITATE,MIN_CORPURI_STRAINE,MIN_INCOLTIT,MIN_HECTOLITRICA,MIN_GLUTEN,MIN_FUZARITATE,MIN_CADERE,MIN_DEFORMARE,MIN_STICLOZITATE,MIN_SPARTURI,
    MIN_PROTEINA,MIN_AFLATOXINA,MIN_ATAC_PLOSNITA,MIN_CONTINUT_ULEI,MIN_ACIDITATE,MIN_SISTAVE,MIN_REFRACTIE,MIN_INDICE_W,MIN_TOXINA_DON,MIN_BOABE_TOXICE, PretProd
  FROM NARTOBJ1
  WHERE CODOBIECT = CodObjSursa;


  INSERT INTO NARTOBJSUBUNIT(CODS, CODOBIECT, SUBUNITATE, STOCMIN, STOCMED, STOCMAX, PROCSTOCMIN, PROCSTOCMED, PROCSTOCMAX, CODGEST)
  SELECT NEXTVAL('SEQ_NARTOBJSUBUNIT_CODS'), codObjNou, SUBUNITATE, STOCMIN, STOCMED, STOCMAX, PROCSTOCMIN, PROCSTOCMED, PROCSTOCMAX, CODGEST
  FROM NARTOBJSUBUNIT
  WHERE CODOBIECT = CodObjSursa;


  FOR V_REC IN (SELECT ATR1.CODVALATR, ATR.CODARTATR, ATR1.VALOARE, ATR.INDEXLOCAL
                FROM TMP_MANEVRA TMP
                     INNER JOIN NATRIB1 ATR1 ON  TMP.CODUNIC    = ATR1.CODVALATR
                     INNER JOIN NARTATR ATR  ON  ATR.CODATRIBUT = ATR1.CODATRIBUT
                WHERE ATR.CODARTICOL = aCodArticol
                ORDER BY ATR.INDEXLOCAL
               )
  LOOP
    INSERT INTO NATROBJ(CODATROBJ, CODOBIECT, CODARTATR, CODVALATR, INDEXLOCAL)
    VALUES(NEXTVAL('SEQ_NATROBJ_CODATROBJ'), codObjNou, V_REC.CODARTATR, V_REC.CODVALATR, COALESCE( V_REC.INDEXLOCAL, 0));
  END LOOP;


  INSERT INTO PRETM(CODPRETM, CODOBIECT, CODCATPRET, LEI, VALUTA, MONEDA, IMPLICIT, PROC, INDEXLOCAL, SUBUNITATEA, GRUPA, ROTUNJIRE)
  SELECT NEXTVAL('SEQ_PRETM_CODPRETM'), codObjNou, CODCATPRET, Round( (LEI * MAJORARE)::numeric, 2), Round( (VALUTA * MAJORARE)::numeric, 2), MONEDA, IMPLICIT, PROC, INDEXLOCAL, SUBUNITATEA, GRUPA, ROTUNJIRE
  FROM PRETM
  WHERE CODOBIECT = CodObjSursa and  UPPER( COALESCE( Grupa, '')) = MaxGRUPA;


  INSERT INTO NARTCLI(CODARTCLI, CODOBIECT, CODPART, DENUMIRE, CODEXTERN, UMSEC, CODMONEDA, PRET, tipcodafisat, CodLaClient, CODINTERN, UMCORELAT, DURATATR, ZILESTOC, GLN, IDspecific)
  SELECT NEXTVAL('SEQ_NARTCLI_CODARTCLI'), codObjNou, CODPART, DENUMIRE, CODEXTERN, UMSEC, CODMONEDA, PRET, tipcodafisat, CodLaClient, CODINTERN, UMCORELAT, DURATATR, ZILESTOC, GLN, IDspecific
  FROM NARTCLI
  WHERE CODOBIECT = CodObjSursa;


  INSERT INTO NARTOPT(CODOPT, CODOBIECT, codobiectopt, CodTipLocatie, ForceLei, CANT, STANDARD, OBS)
  SELECT NEXTVAL('SEQ_NARTOPT_CODOPT'), codObjNou, codobiectopt, CodTipLocatie, ForceLei, CANT, STANDARD, OBS
  FROM NARTOPT
  WHERE CODOBIECT = CodObjSursa;


  IF  ModDepozitareGeneric = '1' THEN
    INSERT INTO NARTAMB(CODAMB, CODOBIECT, CODOBIECTRETURN, CANT, CANTMIN, UMSEC, CODPLU,
      CODINTERN, MASA, LUNGIME, LATIME, INALTIME, LXLAT, LXH, LATXH, GREUTSPECIFICA, IMPLICITTIPDOC, TIP, NR_RANDURI, AdMax, returnabil)
    SELECT NEXTVAL('SEQ_NARTAMB_CODAMB'), CodObjNou, CODOBIECTRETURN, CANT, CANTMIN, UMSEC, CODPLU, CODINTERN, MASA, LUNGIME, LATIME, INALTIME,
           LXLAT, LXH, LATXH, GREUTSPECIFICA, IMPLICITTIPDOC, TIP, NR_RANDURI, AdMax, returnabil
    FROM NARTAMB
    WHERE CODOBIECT = CodObjSursa;
  END IF;


  INSERT INTO NARTOBJCOLET(CODOBJCOLET, CODOBIECT, INDEXLOCAL, CONTINUT, IDCOLET)
  SELECT NEXTVAL('SEQ_NARTOBJCOLET_COD'), CodObjNou, INDEXLOCAL, CONTINUT, IDCOLET
  FROM NARTOBJCOLET
  WHERE CODOBIECT = CodObjSursa;

  SELECT COALESCE( AO.TraducArtGeneric, 0) INTO aBifaTrad FROM NARTOBJ AO WHERE AO.CodObiect = CodObjSursa;

  IF  aBifaTrad = 1 THEN
    FOR v_lang IN (SELECT * FROM NLIMBA WHERE CodLimba &gt; 0 AND  ExtLink &lt;&gt; 'RO') LOOP
      SELECT COUNT( *) INTO aAreTrad FROM NARTOBJTRAD WHERE CodObiect = CodObjNou AND  CodLimba = v_lang.CodLimba;

      IF  aAreTrad = 0 THEN
        BEGIN
          SELECT AOT.DenumireTrad INTO aDenTrad
          FROM NARTOBJ AO
               LEFT JOIN NARTOBJTRAD AOT ON  AOT.CodObiect = AO.CodObiect
          WHERE (SELECT COUNT( *) FROM NAtrObj ATRO WHERE ATRO.CodObiect = AO.CodObiect) = 0
                 AND  AO.CodArticol = aCodArticol AND  AOT.CodLimba = v_lang.CodLimba;
        EXCEPTION WHEN NO_DATA_FOUND THEN
          aDenTrad := NULL;
        END;

        IF aDenTrad IS NOT NULL THEN
          FOR v_atrib IN (SELECT ATR1.Valoare
                          FROM TMP_MANEVRA TMP
                               INNER JOIN NATRIB1 ATR1 ON  TMP.CodUnic = ATR1.CodValAtr
                               INNER JOIN NARTATR ATR ON  ATR.CodAtribut = ATR1.CodAtribut
                          WHERE ATR.CodArticol = aCodArticol
                          ORDER BY ATR.IndexLocal
                         )
          LOOP
            aDenTrad := aDenTrad || ' ' || v_atrib.Valoare;
          END LOOP;

          INSERT INTO NARTOBJTRAD(CodObiectTrad, CodObiect, CodLimba, DenumireTrad)
          VALUES(NEXTVAL('SEQ_NARTOBJTRAD_CODOBIECTTRAD'), CodObjNou, v_lang.CodLimba, aDenTrad);
        END IF;
      END IF;
    END LOOP;
  END IF;

  CALL prc_al_refresh('nartobj1',codObjNou);
  FOR V_TMP IN (
    SELECT PN.CODATRIBUT
    FROM NATROBJ N
         INNER JOIN NARTATR PN ON PN.CODARTATR = N.CODARTATR
         INNER JOIN TMP_MANEVRA T ON T.CODUNIC = N.CODVALATR
         INNER JOIN NATRIB1 NB1 ON NB1.CODVALATR = N.CODVALATR
         INNER JOIN NATRIB1 NP1 ON NP1.VALOARE = NB1.VALOARE
         INNER JOIN NATROBJ P ON NP1.CODVALATR = P.CODVALATR
         INNER JOIN NARTATR PA ON PA.CODARTATR = P.CODARTATR
    WHERE PA.CODATRIBUT = aCodAtribut AND P.CODOBIECT = vCodProdus AND N.CODOBIECT = codObjNou
  ) LOOP
    vCodAtribut := aCodAtribut;
    exit;
  END LOOP;
  WME_Result :=  codObjNou;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_parcaut_sp_postrecords</obj_name>
  <obj_hashval>d30895a9fb1455035fa7479dcde3842e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_parcaut_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  VX           RECORD;
  IndexCount   numeric;
  vCod         numeric;
  aInactivOld  numeric;
  aCodGestOld  numeric;
  aInactivNew  numeric;
  aStatus      numeric;
  aCodGestNew  numeric;
  aData        timestamp;
  aDoc         varchar;
  aOldCodMifix numeric;
  aNewCodMifix numeric;
  aCount       NUMERIC;
  aCount1      NUMERIC;
BEGIN
  --Florin 21.05.2025 - sinc. Oracle
  --Florin 17.07.2023 - fixat 58853
  --Florin 01.06.2023 - monitor
  --Florin 21.11.2022 - fixat 56318
  --Florin 07.09.2022 - sinc. Oracle
  --Florin 24.08.2022 - sinc. Oracle (23.08.2022)
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_nom_parcaut_setct_monitor('MON_72');
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT (505);
  UPDATE TMP_NPARCAUT SET codgest = NULL WHERE COALESCE( codgest, 0) = 0;

  IF  OPERATION = 0 THEN
    SELECT CodNParcAut INTO RecId FROM TMP_NPARCAUT;

    BEGIN
      SELECT mf.codmifix INTO aOldCodMifix FROM nparcaut a INNER JOIN mifix mf ON  mf.nrinventar = a.nrinv WHERE codnparcaut = recid AND Mf.tip = 'MF';
    EXCEPTION WHEN others THEN
      aOldCodMifix := 0;
    END;

    BEGIN
      SELECT mf.codmifix INTO aNewCodMifix FROM tmp_nparcaut a INNER JOIN mifix mf ON  mf.nrinventar = a.nrinv AND Mf.tip = 'MF';
    EXCEPTION WHEN others THEN
      aNewCodMifix := 0;
    END;

    IF  aOldCodMifix &gt; 0 THEN
      UPDATE mifix1 SET codauto = NULL WHERE codauto = recid and  codmifix = aOldCodMifix;
    END IF;

    IF  aNewCodMifix &gt; 0 THEN
      UPDATE mifix1
      SET
      codauto = recid
      WHERE
       anstart = (SELECT pkg_globals_GetANLUCRU.WME_RESULT FROM pkg_globals_GetANLUCRU(NULL,NULL)) and  lunastart = (SELECT pkg_globals_GetLUNALUCRU.WME_RESULT FROM pkg_globals_GetLUNALUCRU(NULL,NULL)) and  codmifix = aNewCodMifix;
    END IF;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999'), 'MON_72'))
    THEN
      SELECT 'Nr.auto: ' || coalesce(NrInreg,'') INTO aDoc FROM TMP_NParcAut WHERE CodnparcAut = recid;
      PERFORM pkg_userfirme_postlogcucommit( 'NPARCAUT', current_setting('PKG_GLOBALS.USERNAME', true), 'M', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), TO_NUMBER(current_setting('PKG_GLOBALS.SUBUNITATE', true),'999999999999999999'), null, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    aStatus := 5;
    SELECT COALESCE( inactiv, 0), COALESCE( CodGest, 0) INTO aInactivOld, aCodGestOld FROM NParcAut WHERE CodNPARCAUT = RecId;
    SELECT COALESCE( inactiv, 0), CodGest INTO aInactivNew, aCodGestNew FROM TMP_NParcAut;

    UPDATE NPARCAUT
    SET
    (CodArt, NrInv, NrInreg, Sofer, KmPornire, Tip, DataInreg, Marca, Model, AnF, SerieC, Culoare, Lung, Lat, Inalt, TipMotor, SerieM, Motor, Cilindree, Putere, CmM, CmU, CmE, TipIncarc, Greutate, MasaM, MasaU, MasaURDF, MasaURFDF, LocT, LocF, LocS, LocP, AnvRecomF, AnvRecomS, AnvOpt1F, AnvOpt1S, AnvOpt2F, AnvOpt2S, Kg, Kgr, Sarcina, CodPutere, GrupAuto, TipRem, InstSp, Aer, Rezervor, VolumU, CuloareC, SursaE, TipUlei, TipVehicul, CodDealer, LimitaKM, Dotari, CodRadio, Transmisie, Tractiune, GPS, CodPartGPS, Frigo, GPL, Extern, Partener, codgest, nrcontr, PartLeas, moneda, rataleas, ratarca, ratacasco, dataachiz, dataendleas, partutiliz, persutiliz, obs, Inactiv, CodExtern, CodArtComb, ConsStatH)
    =
    (
    SELECT COALESCE( CodArt, 0), NrInv, NrInreg, Sofer, KmPornire, Tip, DataInreg, Marca, Model, AnF, SerieC, Culoare, Lung, Lat, Inalt, TipMotor, SerieM, Motor, Cilindree, Putere, CmM, CmU, CmE, TipIncarc, Greutate, MasaM, MasaU, MasaURDF, MasaURFDF, LocT, LocF, LocS, LocP, AnvRecomF, AnvRecomS, AnvOpt1F, AnvOpt1S, AnvOpt2F, AnvOpt2S, Kg, Kgr, Sarcina, CodPutere, GrupAuto, TipRem, InstSp, Aer, Rezervor, VolumU, CuloareC, SursaE, TipUlei, TipVehicul, CodDealer, LimitaKM, Dotari, CodRadio, Transmisie, Tractiune, GPS, CodPartGPS, Frigo, GPL, Extern, Partener, codgest, nrcontr, PartLeas, moneda, rataleas, ratarca, ratacasco, dataachiz, dataendleas, partutiliz, persutiliz, obs, Inactiv, CodExtern, CodArtComb, ConsStatH
    FROM TMP_NPARCAUT
    )
    WHERE
     CodNParcAut = RecId;

    DELETE FROM NPARC0 WHERE CodNPARCAUT = RecId and CodNParc0 NOT IN (SELECT CodNParc0 FROM TMP_NPARC0);
    INSERT INTO NPARC0(CODNPARC0, CODNPARCAUT, DATABord, KMBord, AN, LUNA, OBS, CODPERS, CodFAZ, Comb, CodCmd)
    (SELECT NEXTVAL('SEQ_NPARC0_CODNPARC0'), RecId, DATABord, KMBord, AN, LUNA, OBS, CODPERS, CodFAZ, Comb, CodCmd FROM TMP_NPARC0 WHERE CodNParc0 &lt; 0);

    FOR v_rec IN (SELECT * FROM TMP_NPARC0 WHERE COALESCE( CodNParc0, -1) &gt; 0 ORDER BY CodNParc0) LOOP
      UPDATE NPARC0
      SET
      DATABord = v_rec.DATABord,
      KMBord   = v_rec.KMBord,
      AN       = v_rec.AN,
      LUNA     = v_rec.LUNA,
      OBS      = v_rec.OBS,
      CODPERS  = V_REC.CODPERS,
      Comb     = V_REC.Comb,
      CodFAZ   = V_REC.CodFAZ,
      CodCmd   = V_REC.CodCmd
      WHERE
       CodNParc0 = v_rec.CodNParc0;
    END LOOP;

    DELETE FROM NPARC1 WHERE Cod = RecId and CodNParc1 NOT IN (SELECT CodNParc1 FROM TMP_NPARC1);
    INSERT INTO NPARC1(CodNParc1, Cod, IndexLocal, Art, Cant, Pozitie, BordInstal, atentie, codpart, Montat, Anotimp, ADANCIME, LATIME, INALTIME, DIAMETRU, GAMA, RUNFLAT, SUV, OFFROAD, XL, MS, OBS, Seria, DOT, BordDem, CodNirStoc, CodNirSer)
    (SELECT NEXTVAL('SEQ_NPARC1_CODNPARC1'), RecId, IndexLocal, Art, Cant, Pozitie, BordInstal, atentie, codpart, Montat, Anotimp, ADANCIME, LATIME, INALTIME, DIAMETRU, GAMA, RUNFLAT, SUV, OFFROAD, XL, MS, OBS, Seria, DOT, BordDem, CodNirStoc, CodNirSer
     FROM TMP_NPARC1 WHERE CodNParc1 &lt; 0
    );

    FOR v_rec IN (SELECT * FROM TMP_NPARC1 WHERE COALESCE( CodNParc1, -1) &gt; 0 ORDER BY CodNParc1) LOOP
      UPDATE NPARC1
      SET
      IndexLocal = v_rec.IndexLocal,
      Art        = v_rec.Art,
      Cant       = v_rec.Cant,
      Pozitie    = v_rec.Pozitie,
      BordInstal = v_rec.BordInstal,
      atentie    = v_rec.atentie,
      codpart    = v_rec.codpart,
      Montat     = v_rec.Montat,
      Anotimp    = v_rec.Anotimp,
      ADANCIME   = v_rec.ADANCIME,
      LATIME     = v_rec.LATIME,
      INALTIME   = v_rec.INALTIME,
      DIAMETRU   = v_rec.DIAMETRU,
      GAMA       = v_rec.GAMA,
      RUNFLAT    = v_rec.RUNFLAT,
      SUV        = v_rec.SUV,
      OFFROAD    = v_rec.OFFROAD,
      XL         = v_rec.XL,
      MS         = v_rec.MS,
      OBS        = v_rec.OBS,
      Seria      = v_rec.Seria,
      DOT        = v_rec.DOT,
      BordDem    = v_rec.BordDem,
      CodNirStoc = v_rec.Codnirstoc,
      CodNirSer  = v_rec.Codnirser
      WHERE
       CodNParc1 = v_rec.CodNPArc1;
    END LOOP;

    IndexCount := 1;
    FOR v_rec IN (SELECT * FROM NPARC1 WHERE Cod = RecId ORDER BY CodNParc1) LOOP
      UPDATE NPARC1 SET IndexLocal = IndexCount WHERE CodNParc1 = v_rec.CodNParc1;
      IndexCount := IndexCount + 1;
    END LOOP;

    DELETE FROM NPARC2 WHERE Cod = RecId and CodNParc2 NOT IN (SELECT CodNParc2 FROM TMP_NPARC2);
    INSERT INTO NPARC2(CodNParc2, Cod, IndexLocal, Doc, SN, Eliberat, Expira, atentie, Obs, Valoare, CodIntr1, Denumire)
    (SELECT NEXTVAL('SEQ_NPARC2_CODNPARC2'), RecId, IndexLocal, Doc, SN, Eliberat, Expira, atentie, Obs, Valoare, CodIntr1, Denumire
     FROM TMP_NPARC2 WHERE CodNParc2 &lt; 0
    );

    FOR v_rec IN (SELECT * FROM TMP_NPARC2 WHERE COALESCE( CodNParc2, -1) &gt; 0 ORDER BY CodNParc2) LOOP
      UPDATE NPARC2
      SET
      IndexLocal = v_rec.IndexLocal,
      Doc        = v_rec.Doc,
      SN         = v_rec.SN,
      Eliberat   = v_rec.Eliberat,
      Expira     = v_rec.Expira,
      atentie    = v_rec.atentie,
      Obs        = v_rec.Obs,
      Valoare    = v_rec.Valoare,
      CodIntr1   = v_rec.CodIntr1,
      Denumire   = v_rec.Denumire
      WHERE
       CodNParc2 = v_rec.CodNPArc2;
    END LOOP;

    IndexCount := 1;
    FOR v_rec IN (SELECT * FROM NPARC2 WHERE Cod = RecId ORDER BY CodNParc2) LOOP
      UPDATE NPARC2 SET IndexLocal = IndexCount WHERE CodNParc2 = v_rec.CodNParc2;
      IndexCount := IndexCount + 1;
    END LOOP;

    DELETE FROM NPARC3 WHERE Cod = RecId and CodNParc3 NOT IN (SELECT CodNParc3 FROM TMP_NPARC3);
    INSERT INTO NPARC3(CodNParc3, Cod, Interventie, DataU, KmU, DataV, KmV, DataA, KMA, CodCMD, Valoare)
    (SELECT NEXTVAL('SEQ_NPARC3_CODNPARC3'), RecId, Interventie, DataU, KmU, DataV, KmV, DataA, KMA, CodCMD, Valoare
     FROM TMP_NPARC3 WHERE CodNParc3 &lt; 0
    );

    FOR v_rec IN (SELECT * FROM TMP_NPARC3 WHERE COALESCE( CodNParc3, -1) &gt; 0 ORDER BY CodNParc3) LOOP
      UPDATE NPARC3
      SET
      Interventie = v_rec.Interventie,
      DataU       = v_rec.DataU,
      KmU         = v_rec.KmU,
      DataV       = v_rec.DataV,
      KmV         = v_rec.KmV,
      DataA       = v_rec.DataA,
      KMA         = v_rec.KMA,
      CodCMD      = v_rec.CodCMD,
      Valoare     = v_rec.Valoare
      WHERE
       CodNParc3 = v_rec.CodNPArc3;
    END LOOP;

    select count(*) into acount from comanda3;
    for v_rec in (
      select c3.codcomanda3
      from comanda2 c2
      inner join comanda3 c3 on c3.codcomanda2 = c2.codcomanda2
      left join TMP_NPARCCOM1 TMP on tmp.codcomanda3 = c3.codcomanda3
      where c2.codnparcaut = RecID and tmp.codcomanda3 is null
    ) LOOP
      delete FROM comanda3 where codcomanda3 = v_rec.codcomanda3;
    END LOOP;

    select count(*) into acount1 from comanda3;

    if aCount - aCount1 &gt; 20 then
    BEGIN
      PERFORM pkg_trigar_BAGA_IN_TRIGAR_MODIF(GETUSERID(), RecID, aCount, 'COMANDA3', 'CODCOMANDA3', 'stergere mare(nom.auto)', to_char(aCount));
      EXCEPTION
        WHEN OTHERS THEN
        BEGIN
          RAISE;
        END;
      END;
    END IF;

    FOR vx IN (SELECT CodComanda2, CodLucrare, Garantie, CODREZERVARE FROM TMP_NPARCCOM1 WHERE COALESCE( CodComanda2, 0) &gt; 0) LOOP
      UPDATE COMANDA2
      SET
      CODLUCRARE   = vx.CODLUCRARE,
      GARANTIE     = vx.GARANTIE,
      CODREZERVARE = vx.CODREZERVARE
      WHERE
       CODCOMANDA2 = vx.CODCOMANDA2;
    END LOOP;

    FOR vx IN (SELECT  DISTINCT CodLucrare, COALESCE( Garantie, 0) GARANTIE, CODREZERVARE FROM TMP_NPARCCOM1 WHERE COALESCE( CodComanda2, 0) = 0) LOOP
      SELECT NEXTVAL('SEQ_COMANDA1_CODCOMANDA2') INTO VCOD;

      UPDATE TMP_NPARCCOM1 SET CODCOMANDA2 = vCod WHERE COALESCE( CodComanda2, 0) = 0 and  CodLucrare = vx.codlucrare and  COALESCE( Garantie, 0) = vx.garantie;

      INSERT INTO COMANDA2(CODCOMANDA2, CODCOMANDA, CODLUCRARE, GARANTIE, CODNPARCAUT, CODREZERVARE)
      VALUES(vCod, 0, vx.CODLUCRARE, COALESCE( vx.GARANTIE, 0), RecID, vx.CODREZERVARE);
    END LOOP;

    FOR vx IN (SELECT * FROM TMP_NPARCCOM1) LOOP
      IF  vx.codcomanda3 &lt; 0 THEN
        INSERT INTO COMANDA3(CODCOMANDA3, CODCOMANDA2, CODOPERATIE, TIP, EXECUTAT, DataStart, DATA, CODCOMANDA, CODREZERVARE, CodIntr1_1, CodIntr1_2, CodIntr1_3)
        VALUES(NEXTVAL('SEQ_COMANDA2_CODCOMANDA3'), vx.CODCOMANDA2, vx.CODOPERATIE, vx.TIP, vx.EXECUTAT, vx.DataStart, vx.DATA, 0, vx.CODREZERVARE, vx.CodIntr1_1, vx.CodIntr1_2, vx.CodIntr1_3);
      ELSE
        UPDATE COMANDA3
        SET
        CODOPERATIE  = vx.CODOPERATIE,
        TIP          = vx.TIP,
        DATA         = vx.Data,
        DATAStart    = vx.DataStart,
        CODREZERVARE = vx.CODREZERVARE,
        EXECUTAT     = vx.EXECUTAT,
        CodIntr1_1   = vx.CodIntr1_1,
        CodIntr1_2   = vx.CodIntr1_2,
        CodIntr1_3   = vx.CodIntr1_3
        WHERE
         CODCOMANDA3 = vx.CODCOMANDA3;
      END IF;
    END LOOP;

  ELSE
    SELECT NEXTVAL('SEQ_NPARCAUT_CODNPARCAUT') INTO RecId;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999'), 'MON_72'))
    THEN
      SELECT 'Nr.auto: ' || coalesce(NrInreg,'') INTO aDoc FROM TMP_NParcAut;
      PERFORM pkg_userfirme_postlogcucommit( 'NPARCAUT', current_setting('PKG_GLOBALS.USERNAME', true), 'A', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), TO_NUMBER(current_setting('PKG_GLOBALS.SUBUNITATE', true),'999999999999999999'), null, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    INSERT INTO NPARCAUT(CodNParcAut, CodArt, NrInv, NrInreg, Sofer, KmPornire, Tip, DataInreg, Marca, Model, AnF, SerieC, Culoare, Lung, Lat, Inalt, TipMotor, SerieM, Motor, Cilindree, Putere, CmM, CmU, CmE, TipIncarc, Greutate, MasaM, MasaU, MasaURDF, MasaURFDF, LocT, LocF, LocS, LocP, AnvRecomF, AnvRecomS, AnvOpt1F, AnvOpt1S, AnvOpt2F, AnvOpt2S, Kg, Kgr, Sarcina, CodPutere, GrupAuto, TipRem, InstSp, Aer, Rezervor, VolumU, CuloareC, SursaE, TipUlei, TipVehicul, CodDealer, LimitaKM, Dotari, CodRadio, Transmisie, Tractiune, GPS, CodPartGPS, Frigo, GPL, Extern, Partener, codgest, nrcontr, PartLeas, moneda, rataleas, ratarca, ratacasco, dataachiz, dataendleas, partutiliz, persutiliz, obs, Inactiv, CodExtern, CodArtComb, ConsStatH)
    SELECT RecId, COALESCE( CodArt, 0), NrInv, NrInreg, Sofer, KmPornire, Tip, DataInreg, Marca, Model, AnF, SerieC, Culoare, Lung, Lat, Inalt, TipMotor, SerieM, Motor, Cilindree, Putere, CmM, CmU, CmE, TipIncarc, Greutate, MasaM, MasaU, MasaURDF, MasaURFDF, LocT, LocF, LocS, LocP, AnvRecomF, AnvRecomS, AnvOpt1F, AnvOpt1S, AnvOpt2F, AnvOpt2S, Kg, Kgr, Sarcina, CodPutere, GrupAuto, TipRem, InstSp, Aer, Rezervor, VolumU, CuloareC, SursaE, TipUlei, TipVehicul, CodDealer, LimitaKM, Dotari, CodRadio, Transmisie, Tractiune, GPS, CodPartGPS, Frigo, GPL, Extern, Partener, codgest, nrcontr, PartLeas, moneda, rataleas, ratarca, ratacasco, dataachiz, dataendleas, partutiliz, persutiliz, obs, Inactiv, CodExtern, CodArtComb, ConsStatH
    FROM TMP_NPARCAUT;
    PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('NPARCAUT', RecId);

    INSERT INTO NPARC0(CODNPARC0, CODNPARCAUT, DATABord, KMBord, AN, LUNA, OBS, CODPERS, CodFAZ, Comb, CodCmd)
    (SELECT NEXTVAL('SEQ_NPARC0_CODNPARC0'), RecId, DATABord, KMBord, AN, LUNA, OBS, CODPERS, CodFAZ, Comb, CodCmd FROM TMP_NPARC0);

    INSERT INTO NPARC1(CodNParc1, Cod, IndexLocal, Art, Cant, Pozitie, BordInstal, atentie, codpart, Montat, Anotimp, ADANCIME, LATIME, INALTIME, DIAMETRU, GAMA, RUNFLAT, SUV, OFFROAD, XL, MS, OBS, Seria, DOT, BordDem, Codnirstoc, Codnirser)
    (SELECT NEXTVAL('SEQ_NPARC1_CODNPARC1'), RecId, IndexLocal, Art, Cant, Pozitie, BordInstal, atentie, codpart, Montat, Anotimp, ADANCIME, LATIME, INALTIME, DIAMETRU, GAMA, RUNFLAT, SUV, OFFROAD, XL, MS, OBS, Seria, DOT, BordDem, Codnirstoc, Codnirser
     FROM TMP_NPARC1
    );

    IndexCount := 1;
    FOR v_rec IN (SELECT * FROM NPARC1 WHERE Cod = RecId) LOOP
      UPDATE NPARC1 SET IndexLocal = IndexCount WHERE CodNParc1 = v_rec.CodNParc1;
      IndexCount := IndexCount + 1;
    END LOOP;

    INSERT INTO NPARC2(CodNParc2, Cod, IndexLocal, Doc, SN, Eliberat, Expira, atentie, Obs, Valoare, CodIntr1, Denumire)
    (SELECT NEXTVAL('SEQ_NPARC2_CODNPARC2'), RecId, IndexLocal, Doc, SN, Eliberat, Expira, atentie, Obs, Valoare, CodIntr1, Denumire
     FROM TMP_NPARC2
    );

    IndexCount := 1;
    FOR v_rec IN (SELECT * FROM NPARC2 WHERE Cod = RecId) LOOP
      UPDATE NPARC2 SET IndexLocal = IndexCount WHERE CodNParc2 = v_rec.CodNParc2;
      IndexCount := IndexCount + 1;
    END LOOP;

    INSERT INTO NPARC3(CodNParc3, Cod, Interventie, DataU, KmU, DataV, KmV, DataA, KMA, CodCMD, Valoare)
    (SELECT NEXTVAL('SEQ_NPARC3_CODNPARC3'), RecId, Interventie, DataU, KmU, DataV, KmV, DataA, KMA, CodCMD, Valoare FROM TMP_NPARC3);

    FOR vx IN (SELECT  DISTINCT CodLucrare, Garantie FROM TMP_NPARCCOM1) LOOP
      SELECT NEXTVAL('SEQ_COMANDA1_CODCOMANDA2') INTO VCOD;

      UPDATE TMP_NPARCCOM1 SET CODCOMANDA2 = vCod WHERE COALESCE( CodComanda2, 0) = 0 and  CodLucrare = vx.codlucrare and  Garantie = vx.garantie;

      INSERT INTO COMANDA2(CODCOMANDA2, CODCOMANDA, CODLUCRARE, GARANTIE, CODNPARCAUT)
      VALUES(vCod, 0, vx.CODLUCRARE, vx.GARANTIE, RecID);
    END LOOP;

    FOR vx IN (SELECT * FROM TMP_NPARCCOM1) LOOP
      INSERT INTO COMANDA3(CODCOMANDA3, CODCOMANDA2, CODOPERATIE, TIP, EXECUTAT, DataStart, DATA, CODCOMANDA, CODREZERVARE, CodIntr1_1, CodIntr1_2, CodIntr1_3)
      VALUES(NEXTVAL('SEQ_COMANDA2_CODCOMANDA3'), vx.CODCOMANDA2, vx.CODOPERATIE, vx.TIP, vx.EXECUTAT, vx.DataStart, vx.DATA, 0, vx.CODREZERVARE, vx.CodIntr1_1, vx.CodIntr1_2, vx.CodIntr1_3);
    END LOOP;

    aInactivOld := -1;
    aCodGestOld := -1;
    aStatus     := 6;

    SELECT COALESCE( inactiv, 0), CodGest INTO aInactivNew, aCodGestNew FROM TMP_NParcAut;

    BEGIN
      SELECT mf.codmifix INTO aNewCodMifix FROM tmp_nparcaut a INNER JOIN mifix mf ON  mf.nrinventar = a.nrinv AND Mf.tip = 'MF';
    EXCEPTION WHEN others THEN
      aNewCodMifix := 0;
    END;

    IF  aNewCodMifix &gt; 0 THEN
      UPDATE mifix1
      SET
      codauto = recid
      WHERE
       anstart = (SELECT pkg_globals_GetANLUCRU.WME_RESULT FROM pkg_globals_GetANLUCRU(NULL,NULL)) and  lunastart = (SELECT pkg_globals_GetLUNALUCRU.WME_RESULT FROM pkg_globals_GetLUNALUCRU(NULL,NULL)) and  codmifix = aNewCodMifix;
    END IF;
  END IF;

  IF  aCodGestOld &lt;&gt; aCodGestNew or  aInactivOld &lt;&gt; aInactivNew THEN
    SELECT Count( *) INTO IndexCount FROM nparcg WHERE codnparcaut = recid;
    IF  IndexCount = 1 and  aCodGestOld = 0 and  aInactivOld = aInactivNew THEN
      UPDATE NParcG SET CodGest = aCodGestNew WHERE codnparcaut = recid;
    ELSE
      IF (IndexCount = 0) and (OPERATION = 0) THEN
        aData := to_timestamp('01.' || coalesce(to_char( TO_NUMBER(current_setting('PKG_GLOBALS.LUNAINITIALA', true),'999999999999999999'), '00'),'') || '.' || coalesce(( TO_NUMBER(current_setting('PKG_GLOBALS.ANINITIAL', true),'999999999999999999'))::varchar,'') || ' 00:01', 'DD.MM.YYYY hh24:mi');
      ELSE
        aData := CURRENT_TIMESTAMP;
      END IF;
      INSERT INTO NParcG(CODNParcG, CODNPARCAUT, CodGestIni, CodGest, Status, Data)
      VALUES(NEXTVAL('SEQ_NPARCG_CODNPARCG'), RecID, aCodGestOld, aCodGestNew, aInactivNew, aData);
    END IF;
  END IF;

  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS(505);
  PERFORM NotifyModif( OPERATION, RECID, 'NPARCAUT');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomatribute_sp_postrecords</obj_name>
  <obj_hashval>b95e0d6e70809e989a65f18e3cc2be22</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomatribute_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  V_REC        RECORD;
  a            record;
  VREC         RECORD;
  vRecNo       numeric := 0;
  vAn          numeric := 0;
  vLuna        numeric := 0;
  vCod         numeric;
  aCod         numeric;
  oldColSuplim varchar := '';
  newColSuplim varchar := '';
  vExistTab    numeric := 0;
  vExistCol    numeric := 0;
  sSQL         varchar;
  sCond        varchar;
  sAux         varchar;
  sFIRMANAME   varchar := lower(current_setting('PKG_GLOBALS.FIRMANAME', true));
BEGIN
  --Stef 10.12.2024
  IF Operation = 0 THEN  -- UPDATE
    -- Master NATRIB
    SELECT CodAtribut, Upper(ColSuplim) INTO RecId, newColSuplim FROM TMP_NATRIB;
    SELECT             Upper(ColSuplim) INTO        oldColSuplim FROM NATRIB WHERE CodAtribut = RecId;

    UPDATE NATRIB
    SET ( Denumire,TipValoare,Prefix,ColSuplim ) = ( SELECT Denumire,TipValoare,Prefix,ColSuplim FROM TMP_NATRIB )
    WHERE CodAtribut = RecId ;

    -- Detail NATRIB1
    FOR V_REC IN (SELECT *  FROM NATRIB1 WHERE ( CodAtribut = RecId AND CodValAtr NOT IN ( SELECT CodValAtr FROM TMP_NATRIB1 WHERE Coalesce(CodValAtr,0) &lt;&gt; 0))) LOOP
      DELETE FROM VALATREXCEPTII WHERE CODVALATR = V_REC.CODVALATR;
      DELETE FROM NATRIB2        WHERE CODVALATR = V_REC.CODVALATR;
      DELETE FROM NATRIB1        WHERE CodValAtr = V_REC.CODVALATR;
      DELETE FROM NATRIB1TRAD    WHERE CodValAtr = V_REC.CODVALATR;
    END LOOP;

    FOR V_REC IN (SELECT  * FROM TMP_NATRIB1 WHERE CodValAtr &lt; 0) LOOP
      aCOD = nextval('SEQ_NATRIB1_CODVALATR');

      UPDATE TMP_VALATREXCEPTII SET CODVALATR = aCOD WHERE CODVALATR = V_REC.CODVALATR;
      UPDATE TMP_NATRIB2        SET CODVALATR = aCOD WHERE CODVALATR = V_REC.CODVALATR;
      UPDATE TMP_NATRIB1TRAD    SET CODVALATR = aCOD WHERE CODVALATR = V_REC.CODVALATR;

      INSERT INTO NATRIB1 ( CodValAtr,CodAtribut,Valoare,Codobiectasoc, Codextern, GRUPA, PROCMAJPU, INACTIV, INACTIVCMDONLINE, MESAJINACTIV )
      VALUES  (aCOD , RecId , V_REC.Valoare, V_REC. Codobiectasoc, V_REC.Codextern, V_REC.GRUPA, V_REC.PROCMAJPU, V_REC.INACTIV, V_REC.INACTIVCMDONLINE, V_REC.MESAJINACTIV);
    END LOOP;

    FOR v_rec IN (
      SELECT * FROM TMP_NATRIB1 WHERE Coalesce(CodValAtr,-1) &gt; 0 ORDER BY CodValAtr
    ) LOOP
      SELECT Count(1) INTO vRecNo FROM NATRIB1 WHERE CodValAtr = Coalesce(v_rec.CodValAtr,0);

      IF(vRecNo=1) THEN
        UPDATE NATRIB1
        SET CodAtribut       = RecId ,
            Valoare          = v_rec.Valoare,
            Codobiectasoc    = V_REC.Codobiectasoc,
            Codextern        = V_REC.Codextern,
            GRUPA            = V_REC.GRUPA,
            PROCMAJPU        = V_REC.PROCMAJPU,
            INACTIV          = V_REC.INACTIV,
            INACTIVCMDONLINE = V_REC.INACTIVCMDONLINE,
            MESAJINACTIV     = V_REC. MESAJINACTIV
        WHERE CodValAtr = v_rec.CodValAtr;
      END IF;
    END LOOP;

    DELETE FROM VALATREXCEPTII VE
    WHERE EXISTS (SELECT CODVALATR FROM TMP_NATRIB1 WHERE CODVALATR = VE.CODVALATR)
      AND NOT EXISTS (SELECT CODEXCEPTIE FROM TMP_VALATREXCEPTII WHERE CODEXCEPTIE = VE.CODEXCEPTIE);

    DELETE FROM NATRIB2 NA
    WHERE EXISTS (SELECT CODVALATR FROM TMP_NATRIB1 WHERE CODVALATR = NA.CODVALATR)
      AND NOT EXISTS (SELECT CODATRIB2 FROM TMP_NATRIB2 WHERE CODATRIB2 = NA.CODATRIB2);

    DELETE FROM NATRIB1TRAD NA
    WHERE EXISTS (SELECT CODVALATR FROM TMP_NATRIB1 WHERE CODVALATR = NA.CODVALATR)
      AND NOT EXISTS (SELECT CODATRIB1TRAD FROM TMP_NATRIB1TRAD WHERE CODATRIB1TRAD = NA.CODATRIB1TRAD);

    FOR V_REC IN (SELECT * FROM TMP_NATRIB2) LOOP
      IF V_REC.CODATRIB2 &gt; 0 THEN
        UPDATE NATRIB2
        SET CODARTICOL = V_REC.CODARTICOL,
            PROCMAJ    = V_REC.PROCMAJ,
            CODVALATR  = V_REC.CODVALATR
        WHERE CODATRIB2 = V_REC.CODATRIB2;

      ELSE
        INSERT INTO NATRIB2 (CODATRIB2,CODVALATR,CODARTICOL,PROCMAJ)
        VALUES (nextval('SEQ_NATRIB2_COD'), V_REC.CODVALATR, V_REC.CODARTICOL, v_rec.PROCMAJ);
      END IF;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_VALATREXCEPTII) LOOP
      IF V_REC.CODEXCEPTIE &gt; 0 THEN
        UPDATE VALATREXCEPTII
        SET CODARTICOL = V_REC.CODARTICOL,
            CODVALATR  = V_REC.CODVALATR
        WHERE CODEXCEPTIE = V_REC.CODEXCEPTIE;
      ELSE
        INSERT INTO VALATREXCEPTII (CODEXCEPTIE, CODVALATR, CODARTICOL)
        VALUES (nextval('SEQ_VALATREXCEPTII_COD'), V_REC.CODVALATR, V_REC.CODARTICOL);
      END IF;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_NATRIB1TRAD) LOOP
      IF V_REC.CODATRIB1TRAD &gt; 0 THEN
        UPDATE NATRIB1TRAD
        SET CODLIMBA     = V_REC.CODLIMBA,
            MESAJINACTIV = V_REC.MESAJINACTIV,
            DENUMIRE     = V_REC.DENUMIRE
        WHERE CODATRIB1TRAD  = V_REC.CODATRIB1TRAD;
      ELSE
        INSERT INTO NATRIB1TRAD (CODATRIB1TRAD, CODVALATR, CODLIMBA, MESAJINACTIV,DENUMIRE)
        VALUES (nextval('SEQ_NATRIB1TRAD_CODATRIB1TRAD'), V_REC.CODVALATR, V_REC.CODLIMBA, V_REC.MESAJINACTIV,V_REC.DENUMIRE);
      END IF;
    END LOOP;
  ELSE
    --Master NATRIB
    RecId := nextval('SEQ_NATRIB_CODATRIBUT');
    INSERT INTO  NATRIB ( CodAtribut,Denumire,TipValoare,Prefix,ColSuplim)
    SELECT  RecId,Denumire,TipValoare,Prefix,ColSuplim
    FROM TMP_NATRIB ;

    -- Detail NATRIB1
    FOR V_REC IN (SELECT  * FROM TMP_NATRIB1  ) LOOP
      aCOD := nextval('SEQ_NATRIB1_CODVALATR');

      UPDATE TMP_VALATREXCEPTII SET CODVALATR = aCOD WHERE CODVALATR = V_REC.CODVALATR;
      UPDATE TMP_NATRIB1TRAD    SET CODVALATR = aCOD WHERE CODVALATR = V_REC.CODVALATR;

      INSERT INTO NATRIB1 ( CodValAtr,CodAtribut,Valoare,Codobiectasoc, Codextern, GRUPA, PROCMAJPU, INACTIV, INACTIVCMDONLINE, MESAJINACTIV )
      VALUES  (aCOD , RecId , V_REC.Valoare, V_REC. Codobiectasoc, V_REC.Codextern, V_REC.GRUPA, V_REC.PROCMAJPU, V_REC.INACTIV, V_REC.INACTIVCMDONLINE, V_REC.MESAJINACTIV);
    END LOOP;

    INSERT INTO NATRIB2 (CODATRIB2,CODVALATR,CODARTICOL,PROCMAJ)
    SELECT nextval('SEQ_NATRIB2_COD'), CODVALATR, CODARTICOL, PROCMAJ FROM TMP_NATRIB2;

    INSERT INTO VALATREXCEPTII (CODEXCEPTIE, CODVALATR, CODARTICOL)
    SELECT nextval('SEQ_VALATREXCEPTII_COD'), CODVALATR, CODARTICOL FROM TMP_VALATREXCEPTII;

    FOR V_REC IN (SELECT * FROM TMP_NATRIB1TRAD)
    LOOP
      INSERT INTO NATRIB1TRAD (CODATRIB1TRAD, CODVALATR, CODLIMBA, MESAJINACTIV,DENUMIRE)
      VALUES (nextval('SEQ_NATRIB1TRAD_CODATRIB1TRAD'), V_REC.CODVALATR, V_REC.CODLIMBA, V_REC.MESAJINACTIV,V_REC.DENUMIRE);
    END LOOP;
  END IF;

  SELECT count(1) INTO vExistTab FROM information_schema.tables WHERE table_name =  'nartobjatr' AND table_schema = sFIRMANAME;
  --insert into x(test) values(RecID::TEXT||' - '||oldColSuplim||' -&gt; '||newColSuplim);

  IF Coalesce(oldColSuplim,'$') &lt;&gt; '$' THEN
    SELECT count(1) INTO vExistCol FROM information_schema.columns WHERE TABLE_NAME = 'nartobjatr' AND COLUMN_NAME  = lower(oldColSuplim) AND TABLE_SCHEMA = sFIRMANAME;
    IF vExistCol = 0
    THEN oldColSuplim := '';
    END IF;
  END IF;

  IF Coalesce(oldColSuplim,'$') &lt;&gt; Coalesce(newColSuplim,'$') THEN
    IF    Trim(Coalesce(newColSuplim, '')) = '' THEN -- stergem coloana existenta
      FOR v_rec IN (
        SELECT COLUMN_NAME FROM information_schema.columns WHERE TABLE_NAME = 'nartobjatr' AND COLUMN_NAME = Lower(oldColSuplim) AND TABLE_SCHEMA = sFIRMANAME
      ) LOOP
        EXECUTE 'ALTER TABLE '||sFIRMANAME||'.NARTOBJATR DROP COLUMN '||v_rec.COLUMN_NAME;
      END LOOP;

      IF vExistTab &gt; 0 THEN
        SELECT Count(1) INTO vExistCol FROM information_schema.columns WHERE TABLE_NAME = 'nartobjatr' AND COLUMN_NAME &lt;&gt; 'codobiect' AND TABLE_SCHEMA = sFIRMANAME;
        IF vExistCol &gt; 0 THEN
          sCond := '';
          sAux  := ' WHERE ';

          FOR vRec IN (SELECT COLUMN_NAME FROM information_schema.columns WHERE TABLE_NAME = 'nartobjatr' AND COLUMN_NAME &lt;&gt; 'codobiect' AND TABLE_SCHEMA = sFIRMANAME) LOOP
            sCond := sCond ||sAux||vRec.COLUMN_NAME||' IS NULL';
            sAux  := ' AND ';
          END LOOP;
          EXECUTE 'DELETE FROM '||sFIRMANAME||'.NARTOBJATR '||sCond;
        END IF;
      END IF;
    ELSIF Trim(Coalesce(oldColSuplim, '')) = '' THEN -- coloana noua
      PERFORM PKG_NOMATRIBUTE_REPARA_NARTOBJATR(2, RecId);
    ELSE -- redenumim coloana
      EXECUTE 'ALTER TABLE '||sFIRMANAME||'.NARTOBJATR RENAME COLUMN '||oldColSuplim||' TO '||newColSuplim;
    END IF;
  END IF;
  PERFORM NotifyModif(OPERATION, RecId, 'NATRIB');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconttert_sp_lockrecord</obj_name>
  <obj_hashval>fbb6bba4e0885beb208f64432ff4fcc6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconttert_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodContT INTO Tmp FROM NCONTT WHERE CodContT = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_gennewstare1</obj_name>
  <obj_hashval>5cd8f3d3382c9fa33ec13badcb3b499f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_gennewstare1(INOUT wme_result numeric, INOUT acodstare numeric, INOUT acodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aSet        numeric;
  aSetG       numeric;
  aAn         numeric;
  aAnG        numeric;
  aCodStare1  numeric;
  aCodOferta  numeric;
  sColEstimat varchar;
  sSQL        varchar;
  vSub        numeric := GETSUBUNITATE();
  vUser       numeric := GETUSERID();
BEGIN
  --Adina 19/04/2021 - sinc.Oracle din 19.04.2021
  BEGIN
    SELECT an, saptamana, ang, saptamanag, codoferta
    INTO aAn, aSet, aAnG, aSetG, aCodOferta
    FROM stareestimari
    WHERE codstare = aCodStare;
  EXCEPTION WHEN others THEN
    aAn := 0;
  END;

  IF  aAn = 0 THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  SELECT NEXTVAL('SEQ_STAREESTIMARI1_CODSTARE1') INTO aCodStare1;

  INSERT INTO stareestimari1(codstare, codobiect, stocmin, codstare1, pret, stocini)
  SELECT aCodStare, aCodObiect, osub.stocmin, aCodStare1, o1.pret, stoc.cant
  FROM nartobj obj
      LEFT JOIN nartobjsubunit osub ON   osub.codobiect = obj.codobiect
                                    and ( osub.codgest is null or osub.codgest = 0)
                                    and  osub.subunitate = vSub
      LEFT JOIN oferta1        o1   ON  o1.codobiect   = obj.codobiect and  o1.codoferta    = aCodOferta
      LEFT JOIN (SELECT sum( ns.rest) CANT, ns.codobiect
                 FROM nirstoc ns
                      INNER JOIN nir ON  nir.codnir = ns.codnir
                      INNER JOIN ngest g ON  g.codgest = nir.gest
                 WHERE g.codsubunit = vSub
                       and  ns.codobiect = aCodObiect
                       and  ns.rest &lt;&gt; 0
                       and  g.tip &lt;&gt; 4
                 GROUP BY ns.codobiect
                ) stoc ON  stoc.codobiect = obj.codobiect
  WHERE
     obj.codobiect = aCodObiect;

  PERFORM PKG_PLANIFCMD_UmpleTemporarGenerator( aAn * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, aAn)) + aSet, vUser, vSub, aCodObiect);

  IF  aAnG = aAn
  THEN sColEstimat := 'e1m.c' || aSetG;
  ELSE sColEstimat := 'e1m.n' || aSetG;
  END IF;

  IF  aAnG * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, aAn)) + aSetG &gt; aAn * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, aAn)) + aSet + 1
  THEN
    sSQL := 'update stareestimari1 S
         set estimat =
                (select sum(' || sColEstimat || ') estimat
                 from estimariprod1m e1m
                      inner join estimariprod   e on e.codestimareprod = e1m.codestimareprod
                      left  join nartobjsubunit osub on  osub.codobiect = e1m.codobiect
                                                     and ( osub.codgest is null or osub.codgest = 0)
                                                     and osub.subunitate = ' || vSub || '
                 where e.an = ' || aAn || ' and e.saptamana = ' || aSet || ' and coalesce(' || sColEstimat || ',0) &gt; 0
                       and e.operat = 1 and coalesce(e.anulat,0) = 0 and e.subunitatea = ' || vSub || '
                       and e1m.codobiect = s.codobiect
                  )
         where s.codstare1 = ' || aCodStare1;
    EXECUTE sSQL;
  ELSE
    IF  aAnG * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, aAn)) + aSetG = aAn * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, aAn)) + aSet + 1
    THEN
      UPDATE stareestimari1
      SET
      estimat = (SELECT sum( tmp.resta) FROM TMP_CMDTL tmp WHERE tmp.tip = 2 and  tmp.userid = vUser),
      consum  = (SELECT sum( tmp.cantc) FROM TMP_CMDTL tmp WHERE tmp.tip = 2 and  tmp.userid = vUser)
      WHERE
       codstare1 = aCodStare1;
    ELSE
      UPDATE stareestimari1
      SET
      estimat = (SELECT sum( tmp.resta) FROM TMP_CMDTL tmp WHERE tmp.tip = 1 and  tmp.userid = vUser),
      consum  = (SELECT sum( tmp.cantc) FROM TMP_CMDTL tmp WHERE tmp.tip = 1 and  tmp.userid = vUser)
      WHERE
       codstare1 = aCodStare1;
    END IF;
  END IF;

  INSERT INTO tmp_stareestimari1(codstare, codobiect, stocmin, codstare1, pret, stocini, den_umsec, den_um1, denumire, d1, d2, d3, relatieum1, estimari, consum)
  SELECT se1.codstare, se1.codobiect, se1.stocmin, se1.codstare1, se1.pret, se1.stocini, umsec.den_um1, um1.den_um, obj.denumire, art.d1, art.d2, art.d3, art.relatieum1, se1.estimat, se1.consum
  FROM stareestimari1 se1
      INNER JOIN nartobj obj   ON  se1.codobiect  = obj.codobiect
      INNER JOIN nart    art   ON  art.codarticol = obj.codarticol
      INNER JOIN num1    umsec ON  umsec.codum    = art.um and  COALESCE( umsec.secundara, 0) = 0
      LEFT JOIN num      um1   ON  um1.codum      = art.um1
  WHERE codstare1 = aCodStare1;

  IF  aSetG = aSet THEN
    INSERT INTO stareestimari2(codstare2, codstare1, codstare, codcomanda1, datadoc, nrdoc, codpart, codobiect, umsec, restacceptat, pu, codmoneda, termen, saptamana)
    SELECT NEXTVAL('SEQ_STAREESTIMARI2_CODSTARE2'), se1.codstare1, se.codstare, c1.codcomanda1, c.datadoc, c.nrdoc, c.partener, c1.codobiect, c1.umsec, c1.restacceptat, c1.pu, c.moneda, c1.termen, aSet
    FROM stareestimari1 se1, stareestimari se, comanda1 c1, comanda c
    WHERE  se1.codstare1 = aCodStare1
      and  se.codstare   = se1.codstare
      and  se1.codobiect = c1.codobiect
      and  c1.codcomanda = c.codcomanda
      and  se.an = aAn
      and  se.saptamana = aSet
      and  se.ang = aAnG
      and  se.saptamanag = aSetG
      and  COALESCE( c.anulat, 0) = 0
      and  c.operat = 1
      and  c1.termen &lt;= (SELECT iso_week_to_date.WME_RESULT FROM iso_week_to_date(NULL, aAnG, aSetG)) + 6
      and  c.tipdoc = 8
      and  c1.restacceptat &lt;&gt; 0
      and  c.subunitatea = se.subunitatea
      and  COALESCE( c.inchisa, 0) = 0
      and  NOT  EXISTS (SELECT se2.codcomanda1 FROM stareestimari2 se2 WHERE se2.codcomanda1 = c1.codcomanda1)
      and  NOT  EXISTS (SELECT l.codcomanda1   FROM planiflink l WHERE l.codcomanda1 = c1.codcomanda1);
  ELSE
    INSERT INTO stareestimari2(codstare2, codstare1, codstare, codcomanda1, datadoc, nrdoc, codpart, codobiect, umsec, restacceptat, pu, codmoneda, termen, saptamana)
    SELECT NEXTVAL('SEQ_STAREESTIMARI2_CODSTARE2'), se1.codstare1, se.codstare, c1.codcomanda1, c.datadoc, c.nrdoc, c.partener, c1.codobiect, c1.umsec, c1.restacceptat, c1.pu, c.moneda, c1.termen, aSet
    FROM stareestimari1 se1, stareestimari se, comanda1 c1, comanda c
    WHERE  se.codstare   = se1.codstare
      and  se1.codobiect = c1.codobiect
      and  c1.codcomanda = c.codcomanda
      and  se.an = aAn
      and  se.saptamana = aSet
      and  se.ang = aAnG
      and  se.saptamanag = aSetG
      and  COALESCE( c.anulat, 0) = 0
      and  c.operat = 1
      and c1.termen BETWEEN (SELECT iso_week_to_date.WME_RESULT FROM iso_week_to_date(NULL, aAnG, aSetG)) AND (SELECT iso_week_to_date.WME_RESULT FROM iso_week_to_date(NULL, aAnG, aSetG)) + 6
      and  c.tipdoc = 8
      and  c1.restacceptat &lt;&gt; 0
      and  c.subunitatea = se.subunitatea
      and  COALESCE( c.inchisa, 0) = 0
      and  NOT  EXISTS (SELECT se2.codcomanda1 FROM stareestimari2 se2 WHERE se2.codcomanda1 = c1.codcomanda1)
      and  NOT  EXISTS (SELECT l.codcomanda1   FROM planiflink l WHERE l.codcomanda1 = c1.codcomanda1);
  END IF;

  UPDATE stareestimari1 se1
  SET
  CmdF = (SELECT sum( se2.restacceptat) FROM stareestimari2 se2 WHERE se2.codstare = se1.codstare and  se2.codstare1 = se1.codstare1)
  WHERE
   se1.codstare1 = acodstare1;

  UPDATE tmp_stareestimari1 tmp
  SET
  CmdF = (SELECT se1.cmdf FROM stareestimari1 se1 WHERE se1.codstare1 = tmp.codstare1)
  WHERE
   tmp.codstare1 = acodstare1;

  WME_Result :=  aCodStare1;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_config_get_id_header</obj_name>
  <obj_hashval>dea94e61208785286362e358fffbcb98</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_config_get_id_header()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  return 200;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgest_get_locatia_curenta</obj_name>
  <obj_hashval>2a6f663434bf3b66a705f430e878f96f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgest_get_locatia_curenta(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER((current_setting('PKG_NOMGEST.Locatia_CURENTA', true)),'999999999999999999');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgest_set_gest_filtru_generator</obj_name>
  <obj_hashval>7b1830f31e6aa7ba024b83f41d769375</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgest_set_gest_filtru_generator(agest numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMGEST.GEST_FILTRU_GENERATOR',to_char(aGEST,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oferta_sp_gotorecord</obj_name>
  <obj_hashval>c7f17e4a62496f14eec5cca3df0ff07f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oferta_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aTIPOFERTA    NUMERIC;
  aModulCereale NUMERIC := COALESCE( (SELECT pkg_categconst_GetValConstanta.WME_RESULT FROM pkg_categconst_GetValConstanta(NULL, 'ModulCereale', current_setting('PKG_GLOBALS.ANLUCRU', TRUE)::NUMERIC, current_setting('PKG_GLOBALS.lunalucru', TRUE)::NUMERIC))::NUMERIC, 2);
  aPartRO       NUMERIC := 0;
  aPart         NUMERIC := 0;
  aClaseP       NUMERIC := 0;
  aTipB         NUMERIC := 0;
BEGIN
  --Florin 07.08.2025 - sinc. Oracle
  --Florin 18.11.2024 - sinc. Oracle
  --Florin 07.06.2024 - sinc. Oracle
  --Florin 25.09.2023 - sinc. Oracle
  --Florin 03.07.2023 - sinc. Oracle
  perform pkg_oferta_setct_monitor('MON_28');
  --perform pkg_oferta_CHECK_STRUCT_EXTENSIE_CLIENTI();

  INSERT INTO TMP_OFERTA (
    CodOferta, TipDoc, Anulat, Blocat, Operat, NrDoc, DataStart, DataEnd, DATACERERE, DATAOFERTA, ToateSubunit, OFERTAT,
    TipBeneficiar, CodClaseP, NRI, Partener,
    An, Luna,
    Obs, Moneda, CodLocatie, Subunitatea, CodFiscal, UserId, CarnetDoc, SeriaDoc, CodPersC, TIPLIVRARE, Agent, NRMAXAPROBARI, CodNParcAut, CodPartComis,
    SendMail, ProcDisc, CodAnaliza )
  SELECT
    CodOferta, TipDoc, Anulat, Blocat, Operat, NrDoc, DataStart, DataEnd, DATACERERE, DATAOFERTA, ToateSubunit, OFERTAT,
    coalesce( TipBeneficiar, 0), CodClaseP, NRI, Partener,
    current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric, current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric,
    Obs, Moneda, CodLocatie, Subunitatea, CodFiscal, UserId, CarnetDoc, SeriaDoc, CodPersC, TIPLIVRARE, Agent, NRMAXAPROBARI, CodNParcAut, CodPartComis,
    0 AS SendMail, ProcDisc, CodAnaliza
  FROM OFERTA
  WHERE CodOferta = RecId;

  select coalesce(o.partener,0), coalesce(o.codclasep,p.codclasa,0), coalesce(o.tipbeneficiar,0)
  into aPart, aClaseP, aTipB
  from tmp_oferta o left join npart p on p.codpart = o.partener;

  delete from tmp_nartcli;

  insert into tmp_nartcli(
    codartcli, codobiect, codpart, denumire, codextern, umsec, codmoneda, pret, tipcodafisat, umcorelat, implicit,
    codlaclient, codclasep, codgama, codintern, obs, obs2, umsecimpdoc, duratatr, zilestoc, gln, idspecific
  )
  select
    codartcli, codobiect, codpart, denumire, codextern, umsec, codmoneda, pret, tipcodafisat, umcorelat, implicit,
    codlaclient, codclasep, codgama, codintern, obs, obs2, umsecimpdoc, duratatr, zilestoc, gln, idspecific
  from nartcli
  where codpart = aPart;
  if aClaseP &gt; 0 then
    insert into tmp_nartcli(
      codartcli, codobiect, codpart, denumire, codextern, umsec, codmoneda, pret, tipcodafisat, umcorelat, implicit,
      codlaclient, codclasep, codgama, codintern, obs, obs2, umsecimpdoc, duratatr, zilestoc, gln, idspecific
    )
    select
      cli.codartcli, cli.codobiect, cli.codpart, cli.denumire, cli.codextern, cli.umsec, cli.codmoneda, cli.pret, cli.tipcodafisat, cli.umcorelat, cli.implicit,
      cli.codlaclient, cli.codclasep, cli.codgama, cli.codintern, cli.obs, cli.obs2, cli.umsecimpdoc, cli.duratatr, cli.zilestoc, cli.gln, cli.idspecific
    from nartcli cli
      left join tmp_nartcli tmp on tmp.codobiect = cli.codobiect
    where cli.codclasep = aClaseP and tmp.codobiect is null;
  end if;

  begin
    SELECT TIPDOC, CASE when upper( trim(F.CodFiscal)) like 'RO%' then 1 else 0 end PARTRO
    INTO aTIPOFERTA, aPartRO
    FROM TMP_OFERTA O left join NPARTCODFISC F ON F.COD_CODFISCAL = O.CODFISCAL;
  exception
    when others then aTIPOFERTA := 0;
  end;

  PERFORM PKG_CFGTABLES_CHECK_STRUCT_EXTENSIE_X_TIPDOC(aTIPOFERTA);
  INSERT INTO TMP_OFERTA1 (
    CodOferta1, CodOferta, CodObiect, CodArticol, UMSec, CantMin, CantMax, Pret, PretRef,
    Obs, ZileL, ZileC, ProcAdaos, ProcDiscount, CodExtOfe, CantMinUM1, CANTOPTIM, CANTOPTIMUM1, D1, D2, D3,
    IndexLocal,
    DenObiect, DenUM, Paritate,
    PROCTVA,
    DenArtCli, CodExtCli, CodLaClient, CodClaseP,
    PU,
    RelatieUM1, UM1, DenUM1, CODCATPRET, PRETUM1, TIPCATPRET, CODEXTERN, CODINTERN, CODEXTERNART,
    PeArticol, TipLinie, CodProiect, Proiect, DataCertifI, Datacertiff, Codreteta, Consum, codcentru,
    PretAchiz, CodAnalizaNod, GestAct,
    Marja,
    ValMarja,
    ValAchiz,
    ROTUNJIRE,
    DEN_GRECHIV, CODVAMAL, PRODUCATOR, CLASAARTICOL,
    PUREAL,
    DENARTCLI_INI,
    CODEXTCLI_INI,
    CODLACLIENT_INI,
    CODLINIEDOCIMP
  )
  SELECT
    O1.CodOferta1, O1.CodOferta, O1.CodObiect, O1.CodArticol, O1.UMSec, O1.CantMin/ U.Paritate, O1.CantMax/ U.Paritate, O1.Pret * U.Paritate, O1.PretRef * U.Paritate,
    O1.Obs, O1.ZileL, O1.ZileC, O1.ProcAdaos, O1.ProcDiscount, O1.CodExtOfe, O1.CantMinUM1, O1.CANTOPTIM, O1.CANTOPTIMUM1, O1.D1, O1.D2, O1.D3,
    ROW_NUMBER() OVER (PARTITION BY O1.CodOferta ORDER BY O1.IndexLocal, O1.CodOferta1 ASC),
    OBJ.Denumire, U.Den_UM1, U.Paritate,
    CASE
      WHEN aModulCereale = 1 AND Trim(obj.codd394) IS NOT NULL AND aPartRO = 1 THEN 0
      ELSE TL.PROCENT --PKG_SELECTARTICOLE.GETPROCENTTVA(a.CodArticol,PKG_GLOBALS.ANLUCRU,PKG_GLOBALS.LUNALUCRU)
    END PROCTVA,
    AC.Denumire, AC.CodExtern, AC.CodLaClient, coalesce(AC.CodClaseP,0),
    O1.Pret * U.Paritate * Coalesce(1+O1.ProcAdaos/100,1),
    A.RelatieUM1, A.UM1, UMSpec.Den_UM, O1.CODCATPRET, O1.PRETUM1, CAT.TIP, OBJ.CODEXTERN, OBJ.CODINTERN, A.CODEXTERNART,
    CASE WHEN coalesce(O1.CodArticol,0) &gt; 0 THEN 1 ELSE 0 END PeArticol, (CASE WHEN coalesce(A.TIPARTICOL, '0') = '0' THEN '=' WHEN coalesce(A.TIPARTICOL, '0') = '2' THEN '=' ELSE 'S'END) TipLinie,
    O1.Codproiect, PR.Versiune, O1.Datacertifi, O1.Datacertiff, PN.Codreteta, case when PN.CODRETETA &gt; 0 THEN 1 ELSE 0 END, O1.CODCENTRU,
    O1.PretAchiz * U.Paritate, O1.CodAnalizaNod, O1.GestAct,
    CASE WHEN Coalesce(O1.PretAchiz,0) &gt; 0 THEN (O1.Pret*(100+coalesce(O1.ProcDiscount,0))/100 - O1.PretAchiz)/(O1.Pret*(100+coalesce(O1.ProcDiscount,0))/100)*100 ELSE 0 END,
    CASE WHEN Coalesce(O1.PretAchiz,0) &gt; 0 THEN (O1.Pret*(100+coalesce(O1.ProcDiscount,0))/100 - O1.PretAchiz)*O1.CantMin ELSE 0 END,
    O1.PretAchiz*O1.CantMin,
    CASE WHEN aTIPOFERTA = 51 THEN OBJ.ROTUNJIRE ELSE OBJ.ROTVALUTA END,
    grech.denumire AS DEN_GRECHIV, OBJ.CODVAMAL, PA.DEN_PART AS PRODUCATOR, NC.DEN_CLASEA as CLASAARTICOL,
    O1.Pret * U.Paritate * Coalesce(1+O1.ProcAdaos/100,1) * Coalesce(1+O1.ProcDiscount/100,1),
    AC.Denumire, AC.CodExtern, AC.CodLaClient, O1.CODLINIEDOCIMP
  FROM OFERTA O
    INNER JOIN OFERTA1 O1 ON O1.CodOferta = O.CodOferta
    INNER JOIN NARTOBJ OBJ ON Obj.CodObiect = O1.CodObiect
    INNER JOIN NART A      ON A.CodArticol = Obj.CodArticol
    INNER JOIN NART1 AL ON AL.CODARTICOL = A.CODARTICOL and current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric*12+current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric between AL.ALSTART and AL.ALSTOP
    INNER JOIN NTVA1 TL ON TL.CODTVA = AL.CODTVA and current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric*12+current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric between TL.ALSTART and TL.ALSTOP
    INNER JOIN NUM1 U      ON U.CodUM1 = O1.UMSec
    LEFT JOIN NPART P     ON P.CodPart = CASE WHEN Coalesce(TipBeneficiar,0) = 1 THEN 0 ELSE O.Partener END
    LEFT JOIN tmp_nartcli AC ON AC.CODOBIECT = O1.CODOBIECT
    LEFT JOIN NUM UMSpec  ON UMSpec.CODUM = A.UM1
    LEFT JOIN NCATPRET CAT ON CAT.CODCATPRET = O1.CODCATPRET
    LEFT JOIN PROIECT PR ON PR.CODPROIECT = O1.CODPROIECT
    LEFT JOIN PROIECTNOD PN ON PN.CODPROIECT = PR.CODPROIECT AND PN.NODORIGINAL = 0
    LEFT JOIN NECHIV NECH   ON nech.codobiect = OBJ.codobiect
    LEFT JOIN GRECHIV GRECH ON grech.codgrechiv = nech.codgrupa
    LEFT JOIN NPART PA  ON OBJ.CODPRODUCATOR = PA.CODPART
    LEFT JOIN NCLASEA NC   ON NC.CODCLASEA = A.CLASA
  WHERE O.CodOferta = RecId;

  UPDATE TMP_OFERTA1
  SET VALOARE = Cantmin * pkg_preturi_WMROTOPRET(rotunjire, pu),
      PU      = pkg_preturi_WMROTOPRET(rotunjire, pu);

  UPDATE tmp_oferta SET valoare = (SELECT sum( Valoare * coalesce( 1 + ProcDiscount / 100, 1)) FROM tmp_oferta1 ) ;

  UPDATE tmp_oferta O
  SET DISCOUNTPART = CASE
                       WHEN TIPDOC = 50 THEN coalesce((SELECT DISCOUNT  FROM NPART WHERE CODPART = O.PARTENER), 0)
                       ELSE 0
                     END,
      valachiz = (SELECT sum(ValAchiz) FROM tmp_oferta1 ),
      valmarja = (SELECT sum(ValMarja) FROM tmp_oferta1 ) ;

  INSERT INTO TMP_CMDAPROBARI
  SELECT * FROM CMDAPROBARI WHERE CODDOC = RECID and TIPDOC = aTIPOFERTA;

  IF (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'OFERTAEXT')) = 1 AND
     (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'TMP_OFERTAEXT')) = 1
  THEN
    EXECUTE 'INSERT INTO TMP_OFERTAEXT SELECT * FROM OFERTAEXT WHERE CODOFERTA = ' || RecID::varchar;
  END IF;

  DELETE FROM TMP_OFERTA1_INITIAL;

  INSERT INTO TMP_OFERTA1_INITIAL (CODOFERTA1)
  SELECT CODOFERTA1 FROM TMP_OFERTA1;

  PERFORM PKG_CFGTABLES_EXT_GOTORECORD(aTIPOFERTA);
  DELETE FROM tmp_nartcli;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_onorarecomenzi_lck_comenzi</obj_name>
  <obj_hashval>ce40a20934609b803a27c6f19ba56071</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_onorarecomenzi_lck_comenzi(INOUT wme_result character varying, INOUT acodsubunit numeric, INOUT adatatermlivrdela character varying, INOUT adatatermlivrpanala character varying, INOUT anrcomenzi character varying, INOUT acoddelegat numeric, INOUT acodmijltransp numeric, INOUT acodtraseu numeric, INOUT acodagent numeric, INOUT acodclient numeric, INOUT acodsubunitsursa numeric, INOUT acodgestsursa numeric, INOUT aflagclaseart numeric, INOUT astadiuwms numeric, INOUT atipplata numeric DEFAULT 0, arez numeric DEFAULT 0, acmdc numeric DEFAULT 0, adl numeric DEFAULT 0, acmdg numeric DEFAULT 0, acmds numeric DEFAULT 0, aallserii numeric DEFAULT 1)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  VREC             RECORD;
  lRecID           numeric;
  lOraError        varchar;
  lCodClient       numeric;
  lCodSubunitSursa numeric;
  lCodGestSursa    numeric;
  aFacturabilCC    NUMERIC(1);
  aAprobariCmdCl   NUMERIC(1);
BEGIN
  --Florin 24.01.2023 - fixat 60725
  --Florin 18.01.2023 - sinc. Oracle
  --Florin 12.01.2023 - sinc. Oracle
  --Florin 17.03.2023 - sinc. Oracle (16.03.2023)
  --Florin 26.08.2022 - sinc. Oracle (25.08.2022)
  --Adina 18.05.2021 - sinc.Oracle din 17.05.2021 - doar restaurare la zi
  --Bogdan 25.05.2021 date empty string
  if Length(aNrComenzi) &gt; 0 THEN
    DELETE FROM tmp_manevra_liste where filtru = 'NRDOC';
    execute 'insert into tmp_manevra_liste(filtru,valoare) select ''NRDOC'',NRDOC FROM COMANDA WHERE NRDOC IN ('||aNrComenzi||')';
  END IF;

  BEGIN
    SELECT TO_NUMBER(fnc_getvalconstantalucru('FacturabilCC')) INTO aFacturabilCC;
    EXCEPTION WHEN OTHERS THEN aFacturabilCC  := 2;
  END;
  BEGIN
    SELECT TO_NUMBER(fnc_getvalconstantalucru('AprobariCmdCl')) INTO aAprobariCmdCl;
    EXCEPTION WHEN OTHERS THEN aAprobariCmdCl  := 2;
  END;

  perform set_config ('PKG_ONORARECOMENZI.pDataSys',TO_CHAR(CURRENT_DATE,'dd.mm.yyyy'),false);

  BEGIN
    perform set_config ('PKG_ONORARECOMENZI.pDataTermLivrDeLa'  , to_char(to_date(coalesce(case when aDataTermLivrDeLa = '' then null else aDataTermLivrDeLa end  ,'x'),'dd.mm.yyyy'),'dd.mm.yyyy'), false);
    perform set_config ('PKG_ONORARECOMENZI.pDataTermLivrPanaLa', to_char(to_date(coalesce(case when aDataTermLivrPanaLa = '' then null else aDataTermLivrPanaLa end,'x'),'dd.mm.yyyy'),'dd.mm.yyyy'), false);

    perform set_config ('PKG_ONORARECOMENZI.pFlagTermLivr'      , 1::varchar                                                                   , false);
  EXCEPTION
  WHEN OTHERS THEN
    perform set_config ('PKG_ONORARECOMENZI.pDataTermLivrDeLa'  , TO_CHAR(CURRENT_DATE,'dd.mm.yyyy'), false);
    perform set_config ('PKG_ONORARECOMENZI.pDataTermLivrPanaLa', TO_CHAR(CURRENT_DATE,'dd.mm.yyyy'), false);
    perform set_config ('PKG_ONORARECOMENZI.pFlagTermLivr'      , 0::varchar                        , false);
  END;

  lCodClient       := COALESCE (aCodClient, 0);
  lCodSubunitSursa := COALESCE (aCodSubunitSursa, 0);
  lCodGestSursa    := COALESCE (aCodGestSursa, 0);
  -- stef -- se vrea daca am ales un client de exemplu sa aduca doar clientul si sa nu mai aduca comenzile de la gestiuni sau subunitati
  IF lCodClient + lCodSubunitSursa + lCodGestSursa &gt; 0 THEN
    IF lCodClient       = 0 THEN lCodClient       := -1; END IF;
    IF lCodSubunitSursa = 0 THEN lCodSubunitSursa := -1; END IF;
    IF lCodGestSursa    = 0 THEN lCodGestSursa    := -1; END IF;
  END IF;

  perform set_config ('PKG_ONORARECOMENZI.pFlagClaseArt',COALESCE (aFlagClaseArt, 0) ::varchar,false);
  lOraError := '';

  FOR vRec IN ( SELECT  DISTINCT C.CodComanda, C.NrDoc, COALESCE (C.UserIDBlocaj, 0) USERIDBLOCAJ
                FROM Comanda             C
                    INNER JOIN Comanda1  C1  ON C1.CodComanda  = C.CodComanda
                    INNER JOIN NArtObj   NAO ON NAO.CodObiect  = C1.CodObiect
                    INNER JOIN NArt      NA  ON NA.CodArticol  = NAO.CodArticol
                    LEFT  JOIN RezervatS RS  ON RS.CodComanda1 = C1.CodComanda1
                    LEFT  JOIN NIRStoc   NS  ON NS.CodNIRStoc  = RS.CodNIRStoc
                    LEFT  JOIN NAgenda   Loc ON Loc.codagenda  = c.codlocatie
                WHERE C.OPERAT = 1 AND C.ANULAT = 0 AND COALESCE (C.INCHISA, 0) = 0
                  AND C.AN * 12 + C.LUNA &lt;= (SELECT PKG_GLOBALS_AnLunaLucru.WME_RESULT FROM PKG_GLOBALS_AnLunaLucru (NULL,NULL))
                  AND CASE WHEN C.TipDoc = 44 THEN C.SubunitSursa ELSE C.Subunitatea END = aCodSubunit
                  AND (
                    (C.TipDoc = 18 AND aCmdC &gt; 0 AND COALESCE(C.DISPLIVRARE,0) = 0 AND C.Partener    = (CASE WHEN lCodClient = 0 THEN C.Partener ELSE lCodClient END)) OR     -- comenzi de la clienti
                    (C.TipDoc = 18 AND aDL &gt; 0 AND C.DISPLIVRARE = 1 AND C.Partener    = (CASE WHEN lCodClient = 0 THEN C.Partener ELSE lCodClient END)) OR              -- comenzi de la clienti
                    (C.TipDoc = 43 AND aCmdG &gt; 0 AND C.CodGest     = (CASE WHEN lCodGestSursa = 0 THEN C.CodGest ELSE lCodGestSursa END)) OR         -- comenzi de la gestiuni
                    (C.TipDoc = 44 AND aCmdS &gt; 0 AND C.Subunitatea = (CASE WHEN lCodSubunitSursa = 0 THEN C.Subunitatea ELSE lCodSubunitSursa END))  -- comenzi de la subunitati
                  )
                  AND C1.RESTACCEPTAT &gt; 0
                  AND (current_setting ('PKG_ONORARECOMENZI.pFlagTermLivr', true) ::numeric = 0
                       or COALESCE (C1.Termen, to_date(current_setting ('PKG_ONORARECOMENZI.pDataSys', true),'dd.mm.yyyy')) BETWEEN to_date(current_setting ('PKG_ONORARECOMENZI.pDataTermLivrDeLa', true),'dd.mm.yyyy') AND to_date(current_setting ('PKG_ONORARECOMENZI.pDataTermLivrPanaLa', true),'dd.mm.yyyy'))
                  AND (aCodDelegat    = 0  or COALESCE (C.Delegat, 0) = aCodDelegat)
                  AND (aCodMijlTransp = 0  or COALESCE (C.MijlTransp, 0) = aCodMijlTransp)
                  AND (aCodTraseu     = 0  or Coalesce (C.CODTRASEULIVR, Loc.CodTraseu, 0) = aCodTraseu)
                  AND (aCodAgent      = 0  or COALESCE (C.Agent, 0) = aCodAgent)
                  AND (aNrComenzi is null  or Length(aNrComenzi) = 0 or C.NRDOC IN (select valoare::NUMERIC from tmp_manevra_liste where UPPER(FILTRU) = 'NRDOC'))
                  AND (current_setting ('PKG_ONORARECOMENZI.pFlagClaseArt', true) ::numeric = 1
                       or COALESCE (NA.Clasa, 0) IN (SELECT Valoare::NUMERIC FROM TMP_MANEVRA_LISTE WHERE UPPER (Filtru) = 'CODCLASEA'))
                  AND (aStadiuWMS     = -1 or COALESCE (StadiuWMS, -1) = aStadiuWMS)
                  AND (aTipPlata      =  0 or EXISTS (SELECT tc.codtermen FROM termenecmd tc WHERE tc.tipplata = aTipPlata and tc.codcomanda = c.codcomanda))
                              AND (aRez           =  0 or RS.Rest &gt; 0)
                              AND (((aFacturabilCC = 1 OR aAprobariCmdCl = 1) AND C.FACTURABIL = 1)
                                   OR
                                   (aFacturabilCC = 2 AND aAprobariCmdCl = 2 AND ((COALESCE(C.DISPLIVRARE, 0) = 0)OR(COALESCE(C.DISPLIVRARE, 0) = 1 AND C.VERIFICAT = 1 AND C.FACTURABIL = 1))
                                   )
                                  )
                              AND (aAllSerii = 1 or exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = 'SERIE' AND tmp.valoare = c.seriadoc))
                  )
  LOOP
    BEGIN
      SELECT CodComanda INTO lRecID FROM Comanda WHERE CodComanda = vRec.CodComanda FOR UPDATE NOWAIT;

      IF vRec.UserIDBlocaj &lt;&gt; 0 and vRec.UserIDBlocaj &lt;&gt; current_setting ('PKG_GLOBALS.UserID', true) ::numeric THEN
           raise exception using
                    errcode='CMBLK';
      END IF;

      UPDATE Comanda SET UserIDBlocaj = current_setting ('PKG_GLOBALS.UserID', true) ::NUMERIC WHERE CodComanda = vRec.CodComanda;
    EXCEPTION
     WHEN sqlstate 'CMBLK' then
       lOraError := coalesce (lOraError,'')|| coalesce ( (vRec.NrDoc) ::varchar::varchar ,'')|| ', ';
    END;
  END LOOP;

  WME_Result := lOraError;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_predariplus_scadecant</obj_name>
  <obj_hashval>d30a73cb8b1e4f73b76bc8f4c6bf4c70</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_predariplus_scadecant(aid numeric, descazut numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  UPDATE PREDARIPLUS SET CANTITATE = CANTITATE - DESCAZUT WHERE IDINREG = AID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_calcul_cmd_xx</obj_name>
  <obj_hashval>0917b70274aa3303047478db0b05983d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_calcul_cmd_xx(xt character varying, yt character varying, vtip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vDATASTART date;
  vDATASTOP  date;
  vZILEN     numeric;
BEGIN
  --Adina 12.07.2021 - sinc.Oracle din 10.07.2021
  --Adina 09.07.2021 - sinc.Oracle din 09.07.2021
  SELECT VDELA   INTO vDATASTART FROM TMP_PROGRAMF_MANEVRA;
  SELECT VPANALA INTO vDATASTOP  FROM TMP_PROGRAMF_MANEVRA;

  SELECT count(zn1.data) INTO vZILEN FROM zineluc1 zn1
  WHERE zn1.data BETWEEN (SELECT VDELA FROM tmp_programf_manevra limit 1) AND (SELECT VpanaLA FROM tmp_programf_manevra limit 1);

  DELETE FROM TMP_PF_MAT_CMD;
  DELETE FROM TMP_PF_SDV_CMD;
  DELETE FROM TMP_PF_LOCM_CMD;
  DELETE FROM TMP_PF_MAN_CMD;

  IF  (fnc_GetValConstantaLucru('RAPORDMAN')) = '1' THEN
    INSERT INTO TMP_PF_MAT_CMD(NRDOC, DATADOC, DENOBJ, CODEXTERN, DEN_UM, CANT, CODGEST, CODOBIECT, STOCREZ, CANTPROD, PRIORITATE, CODCOMANDA1, D1, D2, D3)
    SELECT C.NRDOC, C.DATADOC, NOBJ.DENUMIRE, NOBJ.CODEXTERN, NUM1.DEN_UM1, ROUND((CMD.CANT * TMP.CANT / MAN.CANT)::numeric, 2), C.CODGEST, BAZAM.CODOBIECT,
           COALESCE(REZ.CANTREZERVAT, 0), PF1.Cantprogramat, PF1.Prioritate, C1.CODCOMANDA1, C1.D1, C1.D2, C1.D3
    FROM TMP_PROGRAMFMAN_MANEVRA TMP
        INNER JOIN CMDPRODMAN    MAN   ON  MAN.CODCMDPRODMAN = TMP.CODCMDPRODMAN
        INNER JOIN COMANDA1      C1    ON  MAN.CODCOMANDA1   = C1.CODCOMANDA1
        INNER JOIN COMANDA       C     ON  C.CODCOMANDA      = C1.CODCOMANDA AND  C.TIPDOC = 53
        INNER JOIN NARTOBJ       NOBJ  ON  NOBJ.CODOBIECT    = C1.CODOBIECT
        INNER JOIN NART                ON  NART.CODARTICOL   = NOBJ.CODARTICOL
        INNER JOIN NUM1                ON  NUM1.CODUM1       = C1.UMSEC
        INNER JOIN CMDPRODMAT    CMD   ON  CMD.CODCMDPRODMAN = TMP.CODCMDPRODMAN
        INNER JOIN TMP_PF_MAT    BAZAM ON  CMD.CODOBIECT     = BAZAM.CODOBIECT
        INNER JOIN TMP_PROGRAMF1 PF1   ON  PF1.CODCOMANDA1   = C1.CODCOMANDA1 AND  PF1.CODPROGRAMF = TMP.CODPROGRAMF
        LEFT  JOIN (SELECT REZ.CODCMDPRODMAT, SUM(REZ.REST) CANTREZERVAT FROM REZERVATS REZ GROUP BY REZ.CODCMDPRODMAT
                   ) REZ ON  REZ.CODCMDPRODMAT = CMD.CODCMDPRODMAT
    WHERE
      (C1.CONSUM = 1 AND  CMD.TIP = 1)  OR (C1.CONSUM = 2 AND CMD.TIP IN (0, 1)) ;

    INSERT INTO TMP_PF_SDV_CMD(NRCMD, PRIORITATE, DEN_OBIECT, CODEXTERN, UM, CANTPROGRAMAT, SECTIE, CODOBIECT)
    SELECT C.NRDOC, PF1.PRIORITATE, OBJ.DENUMIRE, OBJ.CODEXTERN, NUM.DEN_UM, PF1.CANTPROGRAMAT, C.CODGEST SECTIE, SDV.CODSDV
    FROM TMP_PROGRAMFMAN_MANEVRA PFM
        INNER JOIN CMDPRODMAN    MAN ON  MAN.CODCMDPRODMAN = PFM.CODCMDPRODMAN
        INNER JOIN COMANDA1      C1  ON  C1.CODCOMANDA1    = MAN.CODCOMANDA1
        INNER JOIN COMANDA       C   ON  C1.CODCOMANDA     = C.CODCOMANDA
        INNER JOIN PRODSDV       SDV ON  SDV.CODPRODMAN    = MAN.CODMAN
        INNER JOIN NARTOBJ       OBJ ON  OBJ.CODOBIECT     = C1.CODOBIECT
        INNER JOIN NART          A   ON  OBJ.CODARTICOL    = A.CODARTICOL
        INNER JOIN NUM               ON  NUM.CODUM         = A.UM
        INNER JOIN TMP_PROGRAMF1 PF1 ON  PF1.CODCOMANDA1   = C1.CODCOMANDA1 AND  PF1.CODPROGRAMF = PFM.CODPROGRAMF;

    INSERT INTO TMP_PF_LOCM_CMD(CODLMC, CODPROGRAMF, CODGEST, CODLOC, CODCOMANDA1, DATAPROGRAMARE, NRCMD, PRIORITATE, DEN_OBIECT, CODEXTERN, NECESAR, NECESARM, DEN_UM, CANTPROD, CODOP)
    SELECT -row_number() over(), PF1.CODPROGRAMF, C.CODGEST, MAN.CODLOC, PF1.CODCOMANDA1, vDataStart, C.NRDOC, PF1.PRIORITATE, OBJ.DENUMIRE, OBJ.CODEXTERN,
           CASE WHEN  vTip &lt;&gt; 0 THEN ROUND((PFM.CANT * COALESCE(MAN.TPI, 0) + PFM.CANT * MAN.TU / 60)::numeric, 2)
                ELSE ROUND((PFM.CANT * COALESCE(MAN.TPI, 0) + PFM.CANT * MAN.TU)::numeric, 2)
           END  NECESAR,
           COALESCE(ROUND((PFM.CANT * COALESCE(MAN.TPI, 0) + PFM.CANT * MAN.TU)::numeric, 2), 0) NECESARM, NUM1.DEN_UM1, PF1.CANTPROGRAMAT, MAN.CODOP
    FROM TMP_PROGRAMFMAN_MANEVRA PFM
        INNER JOIN CMDPRODMAN    MAN ON  PFM.CODCMDPRODMAN = MAN.CODCMDPRODMAN
        INNER JOIN COMANDA1      C1  ON  C1.CODCOMANDA1    = MAN.CODCOMANDA1
        INNER JOIN COMANDA       C   ON  C1.CODCOMANDA     = C.CODCOMANDA
        INNER JOIN NARTOBJ       OBJ ON  OBJ.CODOBIECT     = C1.CODOBIECT
        INNER JOIN NUM1              ON  NUM1.CODUM1       = C1.UMSEC
        INNER JOIN PRODCOMP      PC  ON  C1.CODRETETA      = PC.CODPRODCOMP
        INNER JOIN NGEST         PG  ON  PG.CODGEST        = C.CODGEST
        INNER JOIN TMP_PROGRAMF1 PF1 ON  PF1.CODCOMANDA1   = C1.CODCOMANDA1 AND  PF1.CODPROGRAMF = PFM.CODPROGRAMF;

    INSERT INTO TMP_PF_MAN_CMD(CODOP, CODGEST, CODCOMANDA1, DATADOC, NRDOC, DENUMIRE, CODEXTERN, NECESAR, NECESARM,
                               DEN_UM, CANTPROD, VALOARE, PRIORITATE, OPERATII, CODCMDPRODMAN)
    SELECT MAN.CODOP, C.CODGEST, C1.CODCOMANDA1, C.DATADOC, C.NRDOC, OBJ.DENUMIRE, OBJ.CODEXTERN,
           CASE WHEN  vTIP &lt;&gt; 0 THEN round(((TMP.CANT * COALESCE(MAN.TPI, 0) + TMP.CANT * COALESCE(MAN.TU, 0)) / 60)::numeric, 6)
                ELSE round(((TMP.CANT * COALESCE(MAN.TPI, 0) + TMP.CANT * COALESCE(MAN.TU, 0)))::numeric, 6)
           END ,
           round(((TMP.CANT * COALESCE(MAN.TPI, 0) + TMP.CANT * COALESCE(MAN.TU, 0)))::numeric, 6),
           NUM1.DEN_UM1, PF1.CANTPROGRAMAT,
           round(((TMP.CANT * COALESCE(MAN.TPI, 0) + TMP.CANT * COALESCE(MAN.TU, 0)) / 60)::numeric, 6) * TMPM.TARIF,
           PF1.Prioritate, MAN.CANT, PFM.CODCMDPRODMAN
    FROM TMP_PROGRAMFMAN_MANEVRA TMP
        INNER JOIN CMDPRODMAN    MAN  ON  MAN.CODCMDPRODMAN = TMP.CODCMDPRODMAN
        INNER JOIN PROGRAMFMAN   PFM  ON PFM.CODCMDPRODMAN  = MAN.CODCMDPRODMAN
        INNER JOIN COMANDA1      C1   ON  C1.CODCOMANDA1    = MAN.CODCOMANDA1
        INNER JOIN COMANDA       C    ON  C.CODCOMANDA      = C1.CODCOMANDA
        INNER JOIN NARTOBJ       OBJ  ON  C1.CODOBIECT      = OBJ.CODOBIECT
        INNER JOIN PRODCOMP      PC   ON  PC.CODPRODCOMP    = C1.CODRETETA
        INNER JOIN NUM1               ON  NUM1.CODUM1       = C1.UMSEC
        LEFT  JOIN TMP_PF_MAN    TMPM ON  TMPM.CODOP        = MAN.CODOP
        LEFT  JOIN TMP_PROGRAMF1 PF1  ON  PF1.CODCOMANDA1   = C1.CODCOMANDA1 AND  PF1.CODPROGRAMF = TMP.CODPROGRAMF;
  ELSE
    INSERT INTO TMP_PF_MAT_CMD(NRDOC, DATADOC, DENOBJ, CODEXTERN, DEN_UM, CANT, CODGEST, CODOBIECT, STOCREZ, CANTPROD, PRIORITATE, CODCOMANDA1, D1, D2, D3)
    SELECT C.NRDOC, C.DATADOC, NOBJ.DENUMIRE, NOBJ.CODEXTERN, NUM1.DEN_UM1, ROUND((CMD.CANT * PF1.CANTPROGRAMAT / C1.CANTACCEPTAT)::numeric, 2), C.CODGEST, BAZAM.CODOBIECT,
           COALESCE(REZ.CANTREZERVAT, 0), PF1.Cantprogramat, PF1.Prioritate, C1.CODCOMANDA1, C1.D1, C1.D2, C1.D3
    FROM TMP_PROGRAMF1_MANEVRA PF1
        INNER JOIN comanda1   c1    ON  PF1.codcomanda1 = c1.codcomanda1
        INNER JOIN COMANDA    C     ON  C.CODCOMANDA    = C1.CODCOMANDA AND  C.TIPDOC = 53
        INNER JOIN cmdprodmat CMD   ON  C1.CODCOMANDA1  = cmd.codcomanda1
        INNER JOIN NARTOBJ    NOBJ  ON  NOBJ.CODOBIECT  = C1.CODOBIECT
        INNER JOIN NART             ON  NART.CODARTICOL = NOBJ.CODARTICOL
        INNER JOIN NUM1             ON  NUM1.CODUM1     = C1.UMsec
        INNER JOIN TMP_PF_MAT BAZAM ON  CMD.CODOBIECT   = BAZAM.CODOBIECT
        LEFT  JOIN (SELECT REZ.CODCMDPRODMAT, SUM(REZ.REST) CANTREZERVAT FROM REZERVATS REZ GROUP BY REZ.CODCMDPRODMAT
                   ) REZ ON  REZ.CODCMDPRODMAT = CMD.CODCMDPRODMAT
    WHERE
      (C1.CONSUM = 1 AND  CMD.TIP = 1)  OR (C1.CONSUM = 2 AND CMD.TIP IN (0, 1)) ;

    INSERT INTO TMP_PF_SDV_CMD(NRCMD, PRIORITATE, DEN_OBIECT, CODEXTERN, UM, CANTPROGRAMAT, SECTIE, CODOBIECT)
    SELECT C.NRDOC, PF1.PRIORITATE, OBJ.DENUMIRE, OBJ.CODEXTERN, NUM.DEN_UM, PF1.CANTPROGRAMAT, C.CODGEST SECTIE, SDV.CODSDV
    FROM TMP_PROGRAMF1_MANEVRA PF1
        INNER JOIN COMANDA1 C1  ON  C1.CODCOMANDA1  = PF1.CODCOMANDA1
        INNER JOIN COMANDA  C   ON  C1.CODCOMANDA   = C.CODCOMANDA
        INNER JOIN PRODSDV  SDV ON  SDV.CODPRODCOMP = C1.CODRETETA
        INNER JOIN NARTOBJ  OBJ ON  OBJ.CODOBIECT   = C1.CODOBIECT
        INNER JOIN NART     A   ON  OBJ.CODARTICOL  = A.CODARTICOL
        INNER JOIN NUM          ON  NUM.CODUM       = A.UM;

    INSERT INTO TMP_PF_LOCM_CMD(CODLMC, CODPROGRAMF, CODGEST, CODLOC, CODCOMANDA1, DATAPROGRAMARE, NRCMD, PRIORITATE, DEN_OBIECT, CODEXTERN, NECESAR, NECESARM, den_um, cantprod, CODOP)
    SELECT -row_number() over(), PF1.CODPROGRAMF, C.CODGEST, PMAN.CODLOC, PF1.CODCOMANDA1, vDataStart, C.NRDOC, PF1.PRIORITATE, OBJ.DENUMIRE, OBJ.CODEXTERN,
           CASE WHEN  vTip &lt;&gt; 0 THEN COALESCE(CASE WHEN  PC.CANT &lt;&gt; 1 THEN PF1.CANTPROGRAMAT / PC.CANT * COALESCE(PMAN.TPI, 0) + PF1.CANTPROGRAMAT / PMAN.BPS * PMAN.TU
                                                   ELSE COALESCE(PMAN.TPI, 0) + PF1.CANTPROGRAMAT / PMAN.BPS * PMAN.TU
                                              END , 0) / 60
                ELSE COALESCE(CASE WHEN  PC.CANT &lt;&gt; 1 THEN PF1.CANTPROGRAMAT / PC.CANT * COALESCE(PMAN.TPI, 0) + PF1.CANTPROGRAMAT / PMAN.BPS * PMAN.TU
                                   ELSE COALESCE(PMAN.TPI, 0) + PF1.CANTPROGRAMAT / PMAN.BPS * PMAN.TU
                              END , 0)
           END  NECESAR,
           COALESCE(CASE WHEN  PC.CANT &lt;&gt; 1 THEN PF1.CANTPROGRAMAT / PC.CANT * COALESCE(PMAN.TPI, 0) + PF1.CANTPROGRAMAT / PMAN.BPS * PMAN.TU
                         ELSE COALESCE(PMAN.TPI, 0) + PF1.CANTPROGRAMAT / PMAN.BPS * PMAN.TU
                    END , 0) NECESARM,
           NUM1.DEN_UM1, PF1.CANTPROGRAMAT, PMAN.CODOP
    FROM TMP_PROGRAMF1_MANEVRA PF1
        INNER JOIN COMANDA1   C1   ON  C1.CODCOMANDA1   = PF1.CODCOMANDA1
        INNER JOIN COMANDA    C    ON  C1.CODCOMANDA    = C.CODCOMANDA
        INNER JOIN NARTOBJ    OBJ  ON  OBJ.CODOBIECT    = C1.CODOBIECT
        INNER JOIN NUM1            ON  NUM1.CODUM1      = C1.UMSEC
        INNER JOIN PRODCOMP   PC   ON  C1.CODRETETA     = PC.CODPRODCOMP
        INNER JOIN CMDPRODMAN PMAN ON  PMAN.CODCOMANDA1 = C1.CODCOMANDA1
        INNER JOIN NGEST      PG   ON  PG.CODGEST       = C.CODGEST;

    INSERT INTO TMP_PF_MAN_CMD(CODOP, CODGEST, CODCOMANDA1, DATADOC, NRDOC, DENUMIRE, CODEXTERN, NECESAR, NECESARM, den_um, cantprod, valoare, Prioritate, OPERATII)
    SELECT MAN.CODOP, C.CODGEST, C1.CODCOMANDA1, C.DATADOC, C.NRDOC, OBJ.DENUMIRE, OBJ.CODEXTERN,
           CASE WHEN  vTIP &lt;&gt; 0 THEN round((sum(CASE WHEN  PC.CANT &lt;&gt; 1 THEN round((TMP.CANTPROGRAMAT / COALESCE(PC.CANT, 1) * COALESCE(MAN.TPI, 0) + TMP.CANTPROGRAMAT / COALESCE(MAN.BPS, 1) * COALESCE(MAN.TU, 0))::numeric, 6)
                                                     ELSE round((COALESCE(MAN.TPI, 0) + TMP.CANTPROGRAMAT * COALESCE(MAN.TU, 0))::numeric, 6)
                                                END ) / 60)::numeric, 6)
                ELSE round((sum(CASE WHEN  PC.CANT &lt;&gt; 1 THEN round((TMP.CANTPROGRAMAT / COALESCE(PC.CANT, 1) * COALESCE(MAN.TPI, 0) + TMP.CANTPROGRAMAT / COALESCE(MAN.BPS, 1) * COALESCE(MAN.TU, 0))::numeric, 6)
                                     ELSE round((COALESCE(MAN.TPI, 0) + TMP.CANTPROGRAMAT * COALESCE(MAN.TU, 0))::numeric, 6)
                                END ))::numeric, 6)
           END ,
           round((sum(CASE WHEN  PC.CANT &lt;&gt; 1 THEN round((TMP.CANTPROGRAMAT / COALESCE(PC.CANT, 1) * COALESCE(MAN.TPI, 0) + TMP.CANTPROGRAMAT / COALESCE(MAN.BPS, 1) * COALESCE(MAN.TU, 0))::numeric, 6)
                           ELSE round((COALESCE(MAN.TPI, 0) + TMP.CANTPROGRAMAT * COALESCE(MAN.TU, 0))::numeric, 6)
                      END ))::numeric, 6),
           TMP.UM, TMP.CANTPROGRAMAT,
           round((sum(CASE WHEN  PC.CANT &lt;&gt; 1 THEN round((TMP.CANTPROGRAMAT / COALESCE(PC.CANT, 1) * COALESCE(MAN.TPI, 0) + TMP.CANTPROGRAMAT / COALESCE(MAN.BPS, 1) * COALESCE(MAN.TU, 0))::numeric, 6)
                           ELSE round((COALESCE(MAN.TPI, 0) + TMP.CANTPROGRAMAT * COALESCE(MAN.TU, 0))::numeric, 6)
                      END ) / 60)::numeric, 6) * TMPM.TARIF,
           TMP.Prioritate, SUM(MAN.CANT)
    FROM COMANDA1 C1
        INNER JOIN TMP_PROGRAMF1_MANEVRA TMP  ON  C1.CODCOMANDA1  = TMP.CODCOMANDA1
        INNER JOIN COMANDA               C    ON  C.CODCOMANDA    = C1.CODCOMANDA
        INNER JOIN NARTOBJ               OBJ  ON  C1.CODOBIECT    = OBJ.CODOBIECT
        INNER JOIN PRODCOMP              PC   ON  PC.CODPRODCOMP  = C1.CODRETETA
        INNER JOIN CMDPRODMAN            MAN  ON  MAN.CODCOMANDA1 = C1.CODCOMANDA1
        INNER JOIN TMP_PF_MAN            TMPM ON  TMPM.CODOP      = MAN.CODOP
    GROUP BY MAN.CODOP, C.CODGEST, C1.CODCOMANDA1, C.NRDOC, C.DATADOC, OBJ.DENUMIRE, OBJ.CODEXTERN, TMP.UM, TMP.CANTPROGRAMAT, TMPM.TARIF, TMP.Prioritate;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_tras_makesqlstocini</obj_name>
  <obj_hashval>7802345c46974fd4c905e98ecbbbdfa2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_tras_makesqlstocini(pinsert text, ptipc text, pgest text)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sqlStocIni varchar;
  sqlTranz   varchar = '';
  fInterval  varchar;
  AnPrec     numeric;
  LunaPrec   numeric;
  AnTemp     numeric;
  LunaTemp   numeric;
  AnLunaMin  numeric;
  aDataI     date;
  aDataF     date;
  sAux1      varchar;
  sAux2      varchar;
  sAnPrec    VARCHAR;
  sLunaPrec  VARCHAR;
  sAnTemp    VARCHAR;
  sLunaTemp  VARCHAR;
  sALTemp    VARCHAR;
BEGIN
  --Florin 09.01.2024 - fixat 64406
  --Florin 09.12.2024 - sinc. Oracle
  -- Stef 16.06.2023
  SELECT ANINITIAL * 12 + LUNAINITIALA INTO AnLunaMin FROM FirmaLuni;

  aDataI   := Trunc(PKG_LIST_SELTRAS_getDataIni(),'MM');
  aDataF   := PKG_LIST_SELTRAS_getDataIni() - 1;

  IF  aDataF = aDataI THEN
    fInterval := '= to_date(''' || coalesce(To_Char( aDataI, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'') ';
  ELSE
    fInterval := 'BETWEEN to_date(''' || coalesce(To_Char( aDataI, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'') AND to_date(''' || coalesce(To_Char( aDataF, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'') ';
  END IF;

  AnTemp   := EXTRACT (YEAR  FROM PKG_LIST_SELTRAS_getDataIni());
  LunaTemp := EXTRACT (MONTH FROM PKG_LIST_SELTRAS_getDataIni());
  PERFORM pkg_globals_SetLunaTemp( AnTemp, LunaTemp);
  SELECT  newAn, newLuna FROM PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA(AnTemp, LunaTemp, AnPrec, LunaPrec) INTO AnPrec, LunaPrec;
  PERFORM pkg_globals_SetLunaPRECEDENTA( Anprec, LunaPrec);

  sAnPrec   := To_Char(AnPrec  , 'fm0000');
  sLunaPrec := To_Char(LunaPrec, 'fm90');
  sAnTemp   := To_Char(AnTemp  , 'fm0000');
  sLunaTemp := To_Char(LunaTemp, 'fm90');
  sALTemp   := To_Char(AnTemp*12+LunaTemp, 'fm00000');

  IF  aDataF &gt;= aDataI THEN
    sqlTranz := '
      UNION ALL
      SELECT
        NS.CODNIRSTOC, NS.CODOBIECT, NSER.CODNIRSER, SER.CODSERIE, N.GEST, Coalesce(NS.FURN,0) FURN,
        NS.PRET PINREG, (NS.PRET - NS.ADAOS) PAchiz, Coalesce(NSER.CANTNIR,NS.CANTNIR) CANT, NS.CODIOART, '||sAnTemp||' AN, '||sLunaTemp||' LUNA, NS.UMSEC, IOA1.CODIOART1
      FROM NIRSTOC NS
        INNER JOIN NIR    N    ON N.CODNIR        = NS.CODNIR
        INNER JOIN NGEST  G    ON G.CODGEST       = N.GEST
        INNER JOIN IOART1 IOA1 ON NS.CODIOART     = IOA1.CODIOART AND '||sALTemp||' BETWEEN IOA1.ALStart AND IOA1.ALStop
        LEFT JOIN NIRSER  NSER ON NSER.CODNIRSTOC = NS.CODNIRSTOC
        LEFT JOIN NSERII  SER  ON SER.CODSERIE    = NSER.CODSERIE
      WHERE N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 12, 13) AND N.DATANIR '|| fInterval ||' AND N.ANULAT = 0 AND N.OPERAT = 1 AND IOA1.MG &lt;&gt; 5
        AND EXISTS (
          SELECT 1
          FROM TMP_MANEVRA_LISTE
          WHERE FILTRU  = ''CODOBIECT'' AND VALOARE = To_Char(NS.CODOBIECT)
            AND FILTRU1 = ''CODSERIE''  AND Coalesce(VALOARE1,'''') = CASE WHEN Coalesce(VALOARE1,'''') = '''' THEN Coalesce(VALOARE1,'''') ELSE TO_CHAR(NSER.CODSERIE) END
            AND FILTRU2 = ''SERIELOT''  AND Coalesce(VALOARE2,'''') = CASE WHEN Coalesce(VALOARE2,'''') = '''' THEN Coalesce(VALOARE2,'''') ELSE NS.SERIELOT            END
            AND FILTRU3 = ''TG''        AND Coalesce(VALOARE3,'''') = CASE WHEN Coalesce(VALOARE3,'''') = '''' THEN Coalesce(VALOARE3,'''') ELSE TO_CHAR(COALESCE(NSER.TG,NS.TG),''DD.MM.YYYY'') END
        )' ||
        PKG_LIST_BASE_UTILS_COND_SUBUNIT('G','CODSUBUNIT')||
        pGest||
        pTipC||'
      UNION ALL
      SELECT
        L1.CODNIRSTOC, NS.CODOBIECT, NSER.CODNIRSER, SER.CODSERIE, N.GEST, Coalesce(NS.FURN,0) FURN,
        NS.PRET PINREG, (NS.PRET - NS.ADAOS) PAchiz, (case when L.TIPLIVR = 15 then 1 else -1 end) * L1.CANT CANT, NS.CODIOART, ' || sAnTemp || ' AN, ' || sLunaTemp || ' LUNA, NS.UMSEC, IOA1.CODIOART1
      FROM LIVR            L
        INNER JOIN LIVR1   L1   ON L1.CODLIVR     = L.CODLIVR
        INNER JOIN NIRSTOC NS   ON NS.CODNIRSTOC  = L1.CODNIRSTOC
        INNER JOIN NIR     N    ON N.CODNIR       = NS.CODNIR
        INNER JOIN NGEST   G    ON G.CODGEST      = N.GEST
        INNER JOIN IOART1  IOA1 ON NS.CODIOART    = IOA1.CODIOART AND '||sALTemp||' BETWEEN IOA1.ALStart AND IOA1.ALStop
        LEFT JOIN NIRSER   NSER ON NSER.CODNIRSER = L1.CODNIRSER
        LEFT JOIN NSERII   SER  ON SER.CODSERIE   = NSER.CODSERIE
      WHERE L.TIPLIVR IN (1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 16, 19, 20, 23, 24) AND L.DATALIVR '||fInterval||' AND L.OPERAT = 1 AND L.ANULAT = 0 AND IOA1.MG &lt;&gt; 5
        AND EXISTS (
          SELECT 1
          FROM TMP_MANEVRA_LISTE
          WHERE FILTRU  = ''CODOBIECT'' AND VALOARE = To_Char(NS.CODOBIECT)
            AND FILTRU1 = ''CODSERIE''  AND Coalesce(VALOARE1,''-1'') = CASE WHEN Coalesce(VALOARE1,''-1'') = ''-1'' THEN Coalesce(VALOARE1,''-1'') ELSE TO_CHAR(NSER.CODSERIE) END
            AND FILTRU2 = ''SERIELOT''  AND Coalesce(VALOARE2,''-1'') = CASE WHEN Coalesce(VALOARE2,''-1'') = ''-1'' THEN Coalesce(VALOARE2,''-1'') ELSE NS.SERIELOT            END
            AND FILTRU3 = ''TG''        AND Coalesce(VALOARE3,''-1'') = CASE WHEN Coalesce(VALOARE3,''-1'') = ''-1'' THEN Coalesce(VALOARE3,''-1'') ELSE TO_CHAR(COALESCE(NSER.TG,NS.TG),''DD.MM.YYYY'') END
        )' ||
        PKG_LIST_BASE_UTILS_COND_SUBUNIT('G','CODSUBUNIT')||
        pGest||
        pTipC;
  END IF;

  IF PKG_LIST_SELTRAS_isSICentralizat() THEN
    sAux1 := '0 codnirstoc, 0 codnirser, ';
    sAux2 := '';
  ELSE
    sAux1 := 'codnirstoc, codnirser, ';
    sAux2 := 'CODNIRSTOC, CODNIRSER, ';
  END IF;

  sqlStocIni := '
  WITH CRS_INI AS (
    SELECT ' || coalesce(sAux1,'') || 'codobiect, null::numeric codintr1, null::numeric coddvi1, null::numeric codlivr1, null::numeric codtransf1, null::numeric tipmiscare, null::numeric codies1, null::numeric codslivr,
      SUM(CANT) intrare, 0 iesire, (SUM(PACHIZ*CANT) )/Coalesce(Nullif(SUM(CANT),0),1) pachiz, pinreg, 0 pumaximal, NULL::date dataexp, furn,
      null::numeric coddoc, gest, 0 partener, 0 codsubunit, 0 codgestprod,
      an, luna, codioart, codioart1, 0 codlocatie, 0 ordine, NULL::numeric d1, NULL::numeric d2, NULL::numeric d3, codserie, NULL::numeric codcmdint
    FROM (
      SELECT
        NS.CODNIRSTOC, NS.CODOBIECT, NSER.CODNIRSER, SER.CODSERIE, N.GEST, Coalesce(NS.FURN,0) FURN,
        NS.PRET PINREG, (NS.PRET - NS.ADAOS) PAchiz, Coalesce(NSERL.REST,NL.REST) CANT, NS.CODIOART, '||sAnTemp|| ' AN, ' ||sLunaTemp||' LUNA, NS.UMSEC, IOA1.CODIOART1
      FROM NIRLUNA NL
        INNER JOIN NIRSTOC   NS    ON NS.CODNIRSTOC    = NL.CODNIRSTOC
        INNER JOIN NIR       N     ON N.CODNIR         = NS.CODNIR
        INNER JOIN NGEST     NG    ON NG.CODGEST       = N.GEST
        INNER JOIN IOART1    IOA1  ON NS.CODIOART      = IOA1.CODIOART AND '||sALTemp||' BETWEEN IOA1.ALStart AND IOA1.ALStop
        LEFT JOIN NIRSERLUNA NSERL ON NSERL.CODNIRSTOC = NL.CODNIRSTOC AND NSERL.AN = '||sAnprec||' AND NSERL.LUNA = '||sLunaPrec||'
        LEFT JOIN NIRSER     NSER  ON NSER.CODNIRSER   = NSERL.CODNIRSER
        LEFT JOIN NSERII     SER   ON SER.CODSERIE     = NSER.CODSERIE
      WHERE NL.AN = '||sAnprec||' AND NL.LUNA = '||sLunaPrec||' AND NL.REST &lt;&gt; 0 AND IOA1.MG &lt;&gt; 5
        AND EXISTS (
          SELECT 1
          FROM TMP_MANEVRA_LISTE
          WHERE FILTRU  = ''CODOBIECT'' AND VALOARE = To_Char(NS.CODOBIECT)
            AND FILTRU1 = ''CODSERIE''  AND Coalesce(VALOARE1,'''') = CASE WHEN Coalesce(VALOARE1,'''') = '''' THEN Coalesce(VALOARE1,'''') ELSE TO_CHAR(NSER.CODSERIE) END
            AND FILTRU2 = ''SERIELOT''  AND Coalesce(VALOARE2,'''') = CASE WHEN Coalesce(VALOARE2,'''') = '''' THEN Coalesce(VALOARE2,'''') ELSE NS.SERIELOT            END
            AND FILTRU3 = ''TG''        AND Coalesce(VALOARE3,'''') = CASE WHEN Coalesce(VALOARE3,'''') = '''' THEN Coalesce(VALOARE3,'''') ELSE TO_CHAR(COALESCE(NSER.TG,NS.TG),''DD.MM.YYYY'') END
        )' ||
        pTipC ||
        pGest ||
        PKG_LIST_BASE_UTILS_COND_SUBUNIT('NG','CODSUBUNIT') ||
      sqlTranz|| '
    ) a_pg
    GROUP BY '||sAux2||'CODSERIE, CODOBIECT, GEST, PINREG, CODIOART, AN, LUNA, UMSEC, CODIOART1, FURN )
  SELECT
    crs.coddoc::numeric, crs.tipmiscare::numeric, crs.codnirstoc, nobj.denumire, crs.intrare, crs.iesire, crs.intrare - crs.iesire stoc_fake, crs.pAchiz, crs.pInreg, crs.pumaximal, crs.dataexp::date,
    furn.den_part denfurn, prod.den_part denprod,
    ''Stoc initial'' PrefixDoc, NULL::varchar SeriaDoc, null::numeric NrDoc, PKG_LIST_SELTRAS_getDataIni() AS DataDoc, PKG_LIST_SELTRAS_getDataIni() AS DataMisc,
    ''Stoc initial'' DIntrPrefix, NULL DIntrSeria, NULL DIntrNR, PKG_LIST_SELTRAS_getDataIni() AS DIntrData,
    NULL DIesPrefix, NULL DIesSeria, NULL DIesNr, NULL DIesData,
    crs.ordine, NULL partener, ng.den_gest, io.den_ioart, ncont.simbol, loc.denumire denlocatie,
    ser.serie serii, crs.codlivr1::numeric, sub.den_subunit, crs.d1::numeric, crs.d2::numeric, crs.d3::numeric, ncls.den_claseas, nobj.codextern, um.den_um, um1.den_um, um2.den_um, cint.nrdoc, cint.datadoc ' || coalesce(current_setting('PKG_LIST_BASE_TRAS.gUserAlias', true),'') || '
  FROM crs_ini crs
    LEFT JOIN nartobj nobj   ON crs.codobiect     = nobj.codobiect
    LEFT JOIN nart n         ON n.codarticol      = nobj.codarticol
    LEFT JOIN npart furn     ON furn.codpart      = crs.furn
    LEFT JOIN npart prod     ON prod.codpart      = nobj.codproducator
    LEFT JOIN npart part     ON part.codpart      = crs.partener AND NOT crs.tipmiscare IN (6, 23, 7, 24, 12, 13)
    LEFT JOIN ngest gestdest ON gestdest.codgest  = crs.partener AND crs.tipmiscare IN (12,13)
    LEFT JOIN nsubunit nsub  ON nsub.codsubunit   = crs.codsubunit AND crs.tipmiscare IN (6,23)
    LEFT JOIN ngest gestprod ON gestprod.codgest  = crs.codgestprod AND crs.tipmiscare IN (7,24)
    LEFT JOIN ngest ng       ON ng.codgest        = crs.gest
    LEFT JOIN ioart io       ON crs.codioart      = io.codioart
    LEFT JOIN ioart1 io1     ON io1.codioart1     = crs.codioart1
    LEFT JOIN ncont ncont    ON ncont.codcont     = io1.cont
    LEFT JOIN nlocatii loc   ON loc.codlocatie    = crs.codlocatie
    LEFT JOIN nirstoc ns     ON ns.codnirstoc     = crs.codnirstoc
    LEFT JOIN nirstoc1 ns1   ON ns1.codnirstoc    = crs.codnirstoc
    LEFT JOIN nirstoc nsroot ON nsroot.codnirstoc = ns1.codnirstocorig
    LEFT JOIN nirser nser    ON nser.codnirser    = crs.codnirser
    LEFT JOIN nserii ser     ON ser.codserie      = crs.codserie
    LEFT JOIN nsubunit sub   ON sub.codsubunit    = ng.codsubunit
    LEFT JOIN nclaseas ncls  ON ncls.codclaseas   = n.clasastatist
    LEFT JOIN num um         ON um.codum          = n.um
    LEFT JOIN num um1        ON um1.codum         = n.um1
    LEFT JOIN num um2        ON um2.codum         = n.um2
    LEFT JOIN num1           ON num1.codum        = n.um and num1.secundara = 0
    LEFT JOIN nartamb aa     ON aa.codobiect      = crs.codobiect and aa.umsec = num1.codum1
    LEFT JOIN comanda cint   ON cint.codcomanda   = crs.codcmdint' ||
    coalesce(current_setting('PKG_LIST_BASE_TRAS.gSuplJoins', true),'');

  PERFORM LIST_EXECUTE_IMMEDIATE(pInsert||sqlStocIni, 0, 0);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmarireplati_processlist</obj_name>
  <obj_hashval>c1eb27a8936edc1295036d86c869a35b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmarireplati_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert       varchar := '';
  sSelect       varchar := '';
  sSelect_Ini   varchar := '';
  sSelect_Fact   varchar := '';
  An             numeric;
  Luna           numeric;
  AnS           numeric := extract( year  FROM to_date(current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true),'dd.mm.yyyy') );
  LunaS         numeric := extract( month FROM to_date(current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true),'dd.mm.yyyy') );
  ZiS           numeric := extract( day   FROM to_date(current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true),'dd.mm.yyyy') );
  sAux           varchar := '';
  sDataS         varchar := current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true);
  sDataF         varchar := current_setting('PKG_LIST_ALEGPERIOADA.gDataF', true);
  gSuplCols     VARCHAR := 'npart npart, nmonede mon, nclasep clsp, nagenda ag, nlocalit loc, njudet jud, npers agent, npers agent_inc, nsubunit substingatori, nsubunit substinsi';
   gUserFields   VARCHAR := '';
  gUserAlias     VARCHAR := '';
  gNullAlias     VARCHAR := '';
  gSuplJoins     VARCHAR := '';
BEGIN
  --Florin 16.08.2023 - fixat 59171
  --Adina 08 septembrie 2020; 25.11.2020 tichet 41274
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI' , 'STINS_IES' , 'STINSI.CODDOC::varchar = STINS_IES.CODIES::varchar AND STINSI.TIPDOC::varchar = STINS_IES.TIPDOC::varchar', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRARI', 'STINS_INTR', 'STINSI.CODDOC::varchar = STINS_INTR.CODINTR::varchar AND STINSI.TIPDOC::varchar = STINS_INTR.TIPDOC::varchar', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NC'     , 'STINS_NC'  , 'STINSI.CODDOC::varchar = STINS_NC.CODNC::varchar AND STINSI.TIPDOC::numeric = 35', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'TREZOR1', 'STINS_TR1' , 'STINSI.CODDOC::varchar = STINS_TR1.CODTREZOR1::varchar AND STINSI.TIPDOC::numeric IN (29,30,31,33)', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'TREZOR' , 'STINS_TR'  , 'STINS_TR.CODTREZOR::varchar = STINS_TR1.CODTREZOR::varchar', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMPENS', 'STINS_C'   , 'STINSI.CODDOC::varchar = STINS_C.CODCOMPENS::varchar AND STINSI.TIPDOC::numeric = 28', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'TREZOR1', 'STING_TR1' , 'STINGATORI.CODDOC1::varchar = STING_TR1.CODTREZOR1::varchar AND STINGATORI.TIPDOC::numeric IN (29,30,31,33)', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'TREZOR' , 'STING_TR'  , 'STINGATORI.CODDOC::varchar = STING_TR.CODTREZOR::varchar AND STINGATORI.TIPDOC::varchar = STING_TR.TIPDOC::varchar', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMPENS', 'STING_C'   , 'STINGATORI.CODDOC::varchar = STING_C.CODCOMPENS::varchar AND STINGATORI.TIPDOC::numeric = 28', 1);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_URMARIREPLATI.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  PERFORM pkg_setluni_GetLunaInitiala(an, luna);

  IF  ZiS &lt;&gt; 1 THEN
    sAux := '   -
      (
        SELECT coalesce(sum(stingere.valoare), 0)
        FROM stingere
          inner join obligpif   on stingere.codstingatorpif = obligpif.codobligpif
          inner join general    on obligpif.codgeneral      = general.codgeneral
          left  join trezor1 t1 on general.coddoc           = t1.codtrezor1
          LEFT  JOIN compens c  ON general.coddoc           = c.codcompens
        WHERE stingere.codstinspif = ol.codobligpif
          AND ( (g.tipdoc &lt;&gt; 28 AND t1.datadoc &lt; TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'') and t1.luna = ' || coalesce(LunaS::varchar,'') || ' and t1.an = ' || coalesce(AnS::varchar,'') || ') OR
                (g.tipdoc  = 28 AND c.datadoc  &lt; TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'') and c.luna  = ' || coalesce(LunaS::varchar,'') || ' and c.an  = ' || coalesce(AnS::varchar,'') || ') )
      )';
  END IF;

  sInsert := 'INSERT INTO ' || tmpName || '(
    NAV_CodDoc, NAV_CodDoc1, NAV_TipDoc, DOCSTINS, TOTAL_DOCUMENT, VAL_NESTINSA_DOCUMENT, VAL_STINGATOR, SOLD_DOC, DOCSTINGATOR, PARTENER, DATADECONT, DATA, DATA_STINS, ORDINE,
    TERMEN,MONEDA, SUBUNITATEA, SUBUNITATEA_ST, SCADENTA, DIFZILE, DEPZILE, CONT, CursDocStins, CursDocStingator ' || gUserFields || ') ';

  sSelect := '
  WITH stingeri AS (
    SELECT stingere.*, general.codgeneral
    FROM stingere
      INNER JOIN obligpif on stingere.codstingatorpif = obligpif.codobligpif
      INNER JOIN general  ON obligpif.codgeneral      = general.codgeneral),
  crs_sold AS (
    SELECT
      ol.codobligpif codobligpif,
      ol.rest' || coalesce(sAux,'') || ' rest
    FROM obligpifluna ol
      INNER JOIN obligpif op on ol.codobligpif = op.codobligpif
      INNER JOIN general  g  on op.codgeneral  = g.codgeneral
    WHERE g.tipdoc IN (1, 2, 3,  4, 5, 9, 35)
      AND ol.luna + ol.an*12 = ' || coalesce((AnS * 12 + Lunas - 1)::varchar,'') || '),
  stinsi as (
    SELECT
      I.CodIntr CodDoc, I.TipDoc,
      obstins.codgeneral, ''sold initial '' || i.nrdoc||''/''||to_char(i.datadoc, ''dd.mm.yyyy'') docstins, i.datadoc data_stins, i.subunitatea, g.moneda codmoneda, obstins.codobligpif, obstins.valoare, obstins.codpart,
      coalesce(i.codlocatie, 0) codlocatie, obstins.termen, PKG_LIST_BASE_UTILS_decode_iCont(obstins.icont, obstins.codpart, i.an*12+i.luna,obstins.semnificatie) cont, Coalesce(NULLIF(coalesce(g.curs,0),0),1) curs, 0 agent
    FROM intrari i
      INNER JOIN general  g       ON g.coddoc     = i.codintr and g.semnificatie &lt;&gt; 600
      INNER JOIN obligpif obstins ON g.codgeneral = obstins.codgeneral
    WHERE (coalesce(i.anulat, 0) = 0) and (coalesce(i.initializari, 0) = 1) and (g.tipdoc = i.tipdoc) AND (i.datadoc &lt;= TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy''))
          and i.tipdoc &lt;&gt; 2
    UNION ALL
    SELECT
      I.CodIntr CodDoc, I.TipDoc,
      obstins.codgeneral, i.prefixdoc ||'' ''||i.nrdoc||''/''||to_char(i.datadoc, ''dd.mm.yyyy'') docstins, i.datadoc data_stins, i.subunitatea, g.moneda codmoneda, obstins.codobligpif, obstins.valoare,  obstins.codpart,
      coalesce(i.codlocatie, 0) codlocatie, obstins.termen, PKG_LIST_BASE_UTILS_decode_iCont(obstins.icont, obstins.codpart, i.an*12+i.luna,obstins.semnificatie) cont, Coalesce(NULLIF(coalesce(g.curs,0),0),1) curs, 0 agent
    FROM intrari i
      INNER JOIN general  g       ON g.coddoc     = i.codintr and g.semnificatie &lt;&gt; 600
      INNER JOIN obligpif obstins ON g.codgeneral = obstins.codgeneral
    WHERE (coalesce(i.anulat, 0) = 0) and (coalesce(i.initializari, 0) = 0) and (g.tipdoc = i.tipdoc) AND (i.datadoc &lt;= TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy''))
          and i.tipdoc &lt;&gt; 2
    UNION ALL
    SELECT
      dvi.CodDvi CodDoc, 5 TipDoc,
      obstins.codgeneral, i.prefixdoc ||'' ''||i.nrdoc||''/''||to_char(i.datadoc, ''dd.mm.yyyy'') docstins, i.datadoc data_stins, i.subunitatea, g.moneda codmoneda, obstins.codobligpif, obstins.valoare,  obstins.codpart,
      coalesce(i.codlocatie, 0) codlocatie, obstins.termen, PKG_LIST_BASE_UTILS_decode_iCont(obstins.icont, obstins.codpart, i.an*12+i.luna,obstins.semnificatie) cont, Coalesce(NULLIF(coalesce(g.curs,0),0),1) curs, 0 agent
    FROM intrari i
      inner join dvi              on dvi.codintr  = i.codintr
      INNER JOIN general  g       ON g.coddoc     = dvi.coddvi and g.semnificatie &lt;&gt; 600 and g.tipdoc = 5
      INNER JOIN obligpif obstins ON g.codgeneral = obstins.codgeneral
    WHERE (coalesce(i.anulat, 0) = 0) and (coalesce(i.initializari, 0) = 0) and (g.tipdoc = i.tipdoc) AND (i.datadoc &lt;= TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy''))
          and i.tipdoc &lt;&gt; 2
    UNION ALL
    SELECT
      I.CodIes CodDoc, I.TipDoc,
      obstins.codgeneral, i.prefixdoc ||'' ''||i.nrdoc||''/''||to_char(i.datadoc, ''dd.mm.yyyy'') docstins, i.datadoc data_stins, i.subunitatea, g.moneda codmoneda, obstins.codobligpif, abs(obstins.valoare), obstins.codpart,
      coalesce(i.codlocatie, 0) codlocatie, obstins.termen, PKG_LIST_BASE_UTILS_decode_iCont(obstins.icont,obstins.codpart,i.an*12+i.luna,obstins.semnificatie) cont, Coalesce(NULLIF(coalesce(g.curs,0),0),1) curs, i.agent
    FROM iesiri i
      INNER JOIN general  g       ON g.coddoc     = i.codies and g.semnificatie = 200
      INNER JOIN obligpif obstins ON g.codgeneral = obstins.codgeneral
    WHERE (coalesce(i.anulat, 0) = 0) and (coalesce(i.initializari, 0) = 0) and (g.tipdoc = i.tipdoc) AND (i.datadoc &lt;= TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy''))
    UNION ALL
    SELECT
      NC.CodNc CodDoc, 35 TipDoc,
      obstins.codgeneral, ''NC ''||nc.nrdoc||''/''||to_char(nc.datadoc, ''dd.mm.yyyy'') docstins, nc.datadoc data_stins, nc.subunitatea, g.moneda codmoneda, obstins.codobligpif, obstins.valoare, obstins.codpart,
      0 codlocatie, obstins.termen, PKG_LIST_BASE_UTILS_decode_iCont(obstins.icont,obstins.codpart,nc1.an*12+nc1.luna,obstins.semnificatie) cont, Coalesce(NULLIF(coalesce(g.curs,0),0),1) curs, nc1.agent
    FROM nc
      INNER JOIN nc1              ON nc1.codnc    = nc.codnc
      INNER JOIN general  g       ON g.coddoc     = nc1.codnc1 AND g.tipdoc = 35 AND g.semnificatie = 1201
      INNER JOIN obligpif obstins ON g.codgeneral = obstins.codgeneral
    WHERE nc.datadoc &lt;= TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')
      AND obstins.icont IN (2,4,6,8,9,12,13,14,15,16)
    UNION ALL
    SELECT
      tr1.CodTrezor1 CodDoc, tr.TipDoc,
      obstins.codgeneral, tr1.doc||tr1.nrdoc||''/''||to_char(tr1.datadoc, ''dd.mm.yyyy'') docstins, tr1.datadoc data_stins, tr.subunitatea, g.moneda codmoneda, obstins.codobligpif, obstins.valoare, obstins.codpart,
      coalesce(tr1.codlocatie, 0) codlocatie, obstins.termen, PKG_LIST_BASE_UTILS_decode_iCont(obstins.icont,obstins.codpart,tr1.an*12+tr1.luna,obstins.semnificatie) cont, Coalesce(NULLIF(coalesce(tr1.curs,0),0),1) curs,
      case when coalesce(tr1.Agent,0) = 0 then coalesce(tr.agent,0) else coalesce(tr1.agent,0) end agent
    FROM trezor1 tr1
      INNER JOIN general  g       ON g.coddoc      = tr1.codtrezor1 AND g.tipdoc IN (29,30,31) AND g.semnificatie &lt;&gt; 600
      INNER JOIN obligpif obstins ON g.codgeneral  = obstins.codgeneral
      INNER JOIN trezor   tr      ON tr1.codtrezor = tr.codtrezor
    WHERE coalesce(tr1.anulat, 0) = 0 AND coalesce(tr1.OBIECTTRANZ,0) &lt;&gt; 3
      AND tr1.datadoc &lt;= TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')
      AND obstins.semnificatie IN (310,430,500)
    UNION ALL
    SELECT
      c.CodCompens CodDoc, 28 TipDoc,
      obstins.codgeneral, ''PV ''||c.nrdoc||''/''||to_char(c.datadoc, ''dd.mm.yyyy'') docstins, c.datadoc data_stins, c.subunitatea, g.moneda codmoneda, obstins.codobligpif, obstins.valoare, obstins.codpart,
      0 codlocatie, obstins.termen, PKG_LIST_BASE_UTILS_decode_iCont(obstins.icont,obstins.codpart,c.an*12+c.luna,obstins.semnificatie) cont, Coalesce(NULLIF(coalesce(g.curs,0),0),1) curs, c.agent
    FROM compens c
      INNER JOIN general  g       ON g.coddoc     = c.codcompens AND g.tipdoc = 28
      INNER JOIN obligpif obstins ON g.codgeneral = obstins.codgeneral
    WHERE c.datadoc &lt;= TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')
      AND obstins.icont IN (2,4,6,8,9,12,13,14,15,16) ),
  stingatori as (
    SELECT
      o.CodObligPIF, o.Codgeneral, t.codtrezor CodDoc, t1.codtrezor1 CodDoc1, g.TipDoc, t1.doc||'' ''||t1.nrdoc||''/''||to_char(t1.datadoc,''dd.mm.yyyy'') DOCSTINGATOR, t1.DATADECONT, t1.datadoc as DATA, o.codpart,
      case when coalesce(t1.Agent,0) = 0 then coalesce(t.agent,0) else coalesce(t1.agent,0) end agent, t.Subunitatea, Coalesce(NULLIF(coalesce(t1.curs,0),0),1) curs
    FROM trezor1 t1
      INNER JOIN trezor   t ON t1.codtrezor  = t.codtrezor
      INNER JOIN general  g ON t1.codtrezor1 = g.coddoc and g.tipdoc = t.tipdoc
      INNER JOIN obligpif o ON o.codgeneral  = g.codgeneral
    WHERE T.TIPDOC IN (29,30,31,33)
      AND g.semnificatie IN (300,320,700,701)--AND t1.TipTranz IN (0,1) AND t1.ObiectTranz IN (0,1) AND t1.TipTranz = t1.ObiectTranz
      AND T1.DATADOC BETWEEN TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'') AND TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')
      AND coalesce(t1.Initializari,0) = 0 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL),'') || '
    UNION ALL
    SELECT
      o.CodObligPIF, o.Codgeneral, c.codcompens CodDoc, NULL CodDoc1, g.TipDoc, ''PV''||'' ''||c.nrdoc||''/''||to_char(c.datadoc,''dd.mm.yyyy'') DOCSTINGATOR, null DATADECONT, c.datadoc as DATA, o.codpart,
      c.Agent, c.Subunitatea, Coalesce(NULLIF(coalesce(g.curs,0),0),1) curs
    FROM compens c
      INNER JOIN general  g ON g.coddoc     = c.codcompens AND g.tipdoc = 28
      INNER JOIN obligpif o ON o.codgeneral = g.codgeneral
    WHERE C.DATADOC BETWEEN TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'') AND TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'') AND o.icont IN (2,4,6,8,9,12,13,14,15) ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'') || '
  )
  SELECT
    (case when ts.codsubunit is NULL then NULL else stingatori.coddoc  end) NAV_CodDoc,
    (case when ts.codsubunit is NULL then NULL else stingatori.coddoc1 end) NAV_CodDoc1,
    (case when ts.codsubunit is NULL then NULL else stingatori.tipdoc  end) NAV_TipDoc,
    stinsi.DocStins, stinsi.valoare TOTAL_DOCUMENT,
    CASE
      WHEN coalesce(crs_sold.rest, 0) = 0 THEN coalesce(sign(stinsi.valoare)*stingeri.valoare + stinsi.valoare - SUM(sign(stinsi.valoare)*stingeri.valoare) over (PARTITION BY stingeri.codstinspif ORDER BY stingeri.codgeneral ROWS BETWEEN unbounded preceding AND CURRENT ROW ), 0)
      ELSE coalesce(sign(stinsi.valoare)*stingeri.valoare + crs_sold.rest - SUM(sign(stinsi.valoare)*stingeri.valoare) over (PARTITION BY stingeri.codstinspif ORDER BY stingeri.codgeneral ROWS BETWEEN unbounded preceding AND CURRENT ROW ), 0)
    END VAL_NESTINSA_DOCUMENT,
    sign(stinsi.valoare)*stingeri.valoare VAL_STINGATOR,
    CASE
      WHEN coalesce(crs_sold.rest, 0) = 0 THEN coalesce(stinsi.valoare - SUM(sign(stinsi.valoare)*stingeri.valoare) over (PARTITION BY stingeri.codstinspif ORDER BY stingeri.codgeneral ROWS BETWEEN unbounded preceding AND CURRENT ROW ), 0)
      ELSE coalesce(crs_sold.rest - SUM(sign(stinsi.valoare)*stingeri.valoare) over (PARTITION BY stingeri.codstinspif ORDER BY stingeri.codgeneral ROWS BETWEEN unbounded preceding AND CURRENT ROW ), 0)
    END SOLD_DOC,
    stingatori.DOCSTINGATOR, npart.den_part PARTENER, stingatori.DATADECONT, stingatori.DATA, stinsi.DATA_STINS, stingatori.codgeneral ORDINE, stinsi.TERMEN, mon.den_moneda MONEDA,
    SubStinsi.den_subunit SUBUNITATEA, SubStingatori.den_subunit SUBUNITATEA_ST, stinsi.termen SCADENTA, trunc(stingatori.Data::date - stinsi.data_stins::date) DIFZILE,
    CASE WHEN trunc(stingatori.data::date - stinsi.termen::date) &gt; 0 THEN trunc(stingatori.data::date - stinsi.termen::date) ELSE 0 END DEPZILE, stinsi.cont, stinsi.curs, stingatori.curs ' || gUserAlias || '
  FROM stingatori
    LEFT JOIN stingeri                          on stingeri.codstingatorpif = stingatori.codobligpif
    LEFT JOIN stinsi                            on stingeri.codstinspif     = stinsi.codobligpif
    LEFT JOIN npers               agent         on agent.codpers            = coalesce(stinsi.agent,0)
    LEFT JOIN npers               agent_inc     on agent_inc.codpers        = coalesce(stingatori.agent,0)
    LEFT JOIN crs_sold                          on stinsi.codobligpif       = crs_sold.codobligpif
    LEFT JOIN npart               npart         on npart.codpart            = coalesce(stinsi.codpart,stingatori.codpart)
    LEFT JOIN nclasep             clsp          on coalesce(npart.codclasa, 0) = clsp.codclasep
    LEFT JOIN nagenda             ag            on stinsi.codlocatie        = ag.codagenda
    LEFT JOIN nlocalit            loc           on ag.codlocalit            = loc.codlocalit
    LEFT JOIN njudet              jud           on loc.codjudet             = jud.codjudet
    LEFT JOIN nmonede             mon           ON stinsi.codmoneda         = mon.codmoneda
    LEFT JOIN nsubunit            SubStingatori ON stingatori.subunitatea   = SubStingatori.codsubunit
    LEFT JOIN nsubunit            SubStinsi     ON stinsi.subunitatea       = SubStinsi.codsubunit
    LEFT JOIN tmp_subunitdedicate ts            ON ts.codsubunit            = stingatori.subunitatea' || gSuplJoins || '
  ORDER BY stingatori.codgeneral ';

  sSelect_Fact := '
  WITH
  stinsi as (
    SELECT
      I.CodIntr CodDoc, I.TipDoc,
      obstins.codgeneral, (case when i.initializari=1 then ''sold initial'' else i.prefixdoc end)||'' '' || i.nrdoc||''/''||to_char(i.datadoc, ''dd.mm.yyyy'') docstins, i.datadoc data_stins, i.subunitatea, g.moneda codmoneda, obstins.codobligpif, obstins.valoare, obstins.codpart,
      coalesce(i.codlocatie, 0) codlocatie, obstins.termen, PKG_LIST_BASE_UTILS_decode_iCont(obstins.icont, obstins.codpart, i.an*12+i.luna,obstins.semnificatie) cont, Coalesce(NULLIF(coalesce(g.curs,0),0),1) curs, 0 agent,
      0 substingatori, 0 agent_inc
    FROM intrari i
      INNER JOIN general  g       ON g.coddoc     = i.codintr AND g.tipdoc = i.tipdoc AND g.semnificatie &lt;&gt; 600
      INNER JOIN obligpif obstins ON g.codgeneral = obstins.codgeneral
      LEFT JOIN stingere s ON s.codstinspif = obstins.codobligpif
    WHERE coalesce(i.anulat, 0) = 0 AND i.datadoc &lt;= TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'') AND coalesce(s.CodStingatorPif,0) = 0
      and i.tipdoc &lt;&gt; 2 and i.operat = 1
    UNION ALL
    SELECT
      I.CodIes CodDoc, I.TipDoc,
      obstins.codgeneral, i.prefixdoc ||'' ''||i.nrdoc||''/''||to_char(i.datadoc, ''dd.mm.yyyy'') docstins, i.datadoc data_stins, i.subunitatea, g.moneda codmoneda, obstins.codobligpif, abs(obstins.valoare), obstins.codpart,
      coalesce(i.codlocatie, 0) codlocatie, obstins.termen, PKG_LIST_BASE_UTILS_decode_iCont(obstins.icont,obstins.codpart,i.an*12+i.luna,obstins.semnificatie) cont, Coalesce(NULLIF(coalesce(g.curs,0),0),1) curs, i.agent,
      0 substingatori, 0 agent_inc
    FROM iesiri i
      INNER JOIN general  g       ON g.coddoc      = i.codies AND g.tipdoc = i.tipdoc AND g.semnificatie = 200
      INNER JOIN obligpif obstins ON g.codgeneral  = obstins.codgeneral
      LEFT  JOIN stingere s       ON s.codstinspif = obstins.codobligpif
    WHERE coalesce(i.anulat, 0) = 0 AND coalesce(i.initializari, 0) = 0 AND i.datadoc &lt;= TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'') AND coalesce(s.CodStingatorPif,0) = 0
      and i.operat = 1
   UNION ALL
    SELECT
      NC.CodNc CodDoc, 35 TipDoc,
      obstins.codgeneral, ''NC ''||nc.nrdoc||''/''||to_char(nc.datadoc, ''dd.mm.yyyy'') docstins, nc.datadoc data_stins, nc.subunitatea, g.moneda codmoneda, obstins.codobligpif, obstins.valoare, obstins.codpart,
      0 codlocatie, obstins.termen, PKG_LIST_BASE_UTILS_decode_iCont(obstins.icont,obstins.codpart,nc1.an*12+nc1.luna,obstins.semnificatie) cont, Coalesce(NULLIF(coalesce(g.curs,0),0),1) curs, nc1.agent,
      0 substingatori, 0 agent_inc
    FROM nc
      INNER JOIN nc1              ON nc1.codnc     = nc.codnc
      INNER JOIN general  g       ON g.coddoc      = nc1.codnc1 AND g.tipdoc = 35 AND g.semnificatie = 1201
      INNER JOIN obligpif obstins ON g.codgeneral  = obstins.codgeneral
      LEFT  JOIN stingere s       ON s.codstinspif = obstins.codobligpif
    WHERE nc.datadoc &lt;= TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')
      AND obstins.icont IN (2,4,6,8,9,12,13,14,15,16)
      AND coalesce(s.CodStingatorPif,0) = 0
    UNION ALL
    SELECT
      tr1.CodTrezor1 CodDoc, tr.TipDoc,
      obstins.codgeneral, tr1.doc||tr1.nrdoc||''/''||to_char(tr1.datadoc, ''dd.mm.yyyy'') docstins, tr1.datadoc data_stins, tr.subunitatea, g.moneda codmoneda, obstins.codobligpif, obstins.valoare, obstins.codpart,
      coalesce(tr1.codlocatie, 0) codlocatie, obstins.termen, PKG_LIST_BASE_UTILS_decode_iCont(obstins.icont,obstins.codpart,tr1.an*12+tr1.luna,obstins.semnificatie) cont, Coalesce(NULLIF(coalesce(tr1.curs,0),0),1) curs,
      case when coalesce(tr1.Agent,0) = 0 then coalesce(tr.agent,0) else coalesce(tr1.agent,0) end agent,
      0 substingatori, 0 agent_inc
    FROM trezor1 tr1
      INNER JOIN general  g       ON g.coddoc      = tr1.codtrezor1 AND g.tipdoc IN (29,30,31) AND g.semnificatie &lt;&gt; 600
      INNER JOIN obligpif obstins ON g.codgeneral  = obstins.codgeneral
      INNER JOIN trezor   tr      ON tr1.codtrezor = tr.codtrezor
      LEFT  JOIN stingere s       ON s.codstinspif = obstins.codobligpif
    WHERE coalesce(tr1.anulat, 0) = 0 AND tr1.OBIECTTRANZ &lt;&gt; 3
      AND tr1.datadoc &lt;= TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')
      AND obstins.semnificatie IN (310,430,500)
      AND coalesce(s.CodStingatorPif,0) = 0
    UNION ALL
    SELECT
      c.CodCompens CodDoc, 28 TipDoc,
      obstins.codgeneral, ''PV ''||c.nrdoc||''/''||to_char(c.datadoc, ''dd.mm.yyyy'') docstins, c.datadoc data_stins, c.subunitatea, g.moneda codmoneda, obstins.codobligpif, obstins.valoare, obstins.codpart,
      0 codlocatie, obstins.termen, PKG_LIST_BASE_UTILS_decode_iCont(obstins.icont,obstins.codpart,c.an*12+c.luna,obstins.semnificatie) cont, Coalesce(NULLIF(coalesce(g.curs,0),0),1) curs, c.agent,
      0 substingatori, 0 agent_inc
    FROM compens c
      INNER JOIN general  g       ON g.coddoc     = c.codcompens AND g.tipdoc = 28
      INNER JOIN obligpif obstins ON g.codgeneral = obstins.codgeneral
      LEFT JOIN stingere s ON s.codstinspif = obstins.codobligpif
    WHERE c.datadoc &lt;= TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')
      AND obstins.icont IN (2,4,6,8,9,12,13,14,15,16)
      AND coalesce(s.CodStingatorPif,0) = 0 )
  SELECT
    NULL NAV_CodDoc, NULL NAV_CodDoc1, NULL NAV_TipDoc, stinsi.DOCSTINS, stinsi.valoare TOTAL_DOCUMENT, stinsi.valoare VAL_NESTINSA_DOCUMENT, 0 VAL_STINGATOR, stinsi.valoare SOLD_DOC, NULL DOCSTINGATOR, npart.DEN_PART, NULL DATADECONT, NULL as DATA, stinsi.DATA_STINS, 0 ORDINE,
    stinsi.TERMEN, mon.DEN_MONEDA, SubStinsi.den_subunit SUBUNITATEA, SubStingatori.den_subunit SUBUNITATEA_ST, stinsi.termen SCADENTA,
    trunc(current_date::date - stinsi.data_stins::date) DIFZILE, CASE WHEN trunc(current_date::date - stinsi.termen::date) &gt; 0 THEN trunc(current_date::date - stinsi.termen::date) ELSE 0 END DEPZILE, stinsi.CONT, stinsi.curs CursDocStins, 1 CursDocStingator ' || gUserAlias || '
  FROM stinsi
    LEFT JOIN npers               agent         ON agent.codpers            = coalesce(stinsi.agent,0)
    LEFT JOIN npers               agent_inc     ON agent_inc.codpers        = stinsi.agent_inc
    LEFT JOIN npart               npart         ON stinsi.codpart           = npart.codpart
    LEFT JOIN nclasep             clsp          on coalesce(npart.codclasa, 0) = clsp.codclasep
    LEFT JOIN nagenda             ag            on stinsi.codlocatie        = ag.codagenda
    LEFT JOIN nlocalit            loc           on ag.codlocalit            = loc.codlocalit
    LEFT JOIN njudet              jud           on loc.codjudet             = jud.codjudet
    LEFT JOIN nmonede             mon           ON stinsi.codmoneda         = mon.codmoneda
    LEFT JOIN nsubunit            SubStingatori ON SubStingatori.codsubunit = stinsi.substingatori
    LEFT JOIN nsubunit            SubStinsi     ON SubStinsi.codsubunit     = stinsi.subunitatea
    LEFT JOIN tmp_subunitdedicate ts            ON ts.codsubunit            = stinsi.substingatori
    CROSS JOIN (SELECT NULL CodDoc, NULL CodDoc1, NULL TipDoc ) stingatori ' || gSuplJoins;

  sSelect_Ini := '
  WITH stingeri as (
    SELECT stingere.*, general.codgeneral
    FROM stingere
      INNER JOIN obligpif on stingere.codstingatorpif = obligpif.codobligpif
      INNER JOIN general  ON obligpif.codgeneral      = general.codgeneral),
  stinsi as (
    SELECT
      NULL CodDoc, NULL TipDoc,
      obstins.codgeneral, ''sold initial ''||i.nrdoc||''/''||to_char(i.datadoc,''dd.mm.yyyy'') docstins, i.datadoc data_stins, i.subunitatea, g.moneda codmoneda, obstins.codobligpif, obstins.valoare, obstins.codpart,
      coalesce(i.codlocatie, 0) codlocatie, obstins.termen, PKG_LIST_BASE_UTILS_decode_iCont(obstins.icont, obstins.codpart, i.an*12+i.luna,obstins.semnificatie) cont, Coalesce(NULLIF(coalesce(g.curs,0),0),1) curs, 0 agent
    FROM intrari i
      INNER JOIN general  g       ON g.coddoc     = i.codintr and g.semnificatie &lt;&gt; 600
      INNER JOIN obligpif obstins ON g.codgeneral = obstins.codgeneral
    WHERE (coalesce(i.anulat, 0) = 0) and (coalesce(i.initializari, 0) = 1) and (g.tipdoc = i.tipdoc) AND (i.datadoc &lt;= TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy''))
          and i.tipdoc &lt;&gt; 2),
  stingatori as (
    SELECT
      o.CodObligPIF, o.Codgeneral, t.codtrezor CodDoc, t1.codtrezor1 CodDoc1, g.TipDoc, t1.doc||'' ''||t1.nrdoc||''/''||to_char(t1.datadoc, ''dd.mm.yyyy'') DOCSTINGATOR, t1.DATADECONT, t1.datadoc as DATA, o.codpart,
      case when coalesce(t1.Agent,0) = 0 then coalesce(t.agent,0) else coalesce(t1.agent,0) end agent, t.Subunitatea, o.valoare, Coalesce(NULLIF(coalesce(t1.curs,0),0),1) curs
    FROM trezor1 t1
      INNER JOIN trezor   t ON t1.codtrezor  = t.codtrezor
      INNER JOIN general  g ON t1.codtrezor1 = g.coddoc and g.tipdoc = t.tipdoc
      INNER JOIN obligpif o ON o.codgeneral  = g.codgeneral
    WHERE T.TIPDOC IN (29,30,31)
      AND g.semnificatie IN (300,320,700,701)--AND t1.TipTranz IN (0,1) AND t1.ObiectTranz IN (0,1) AND t1.TipTranz = t1.ObiectTranz
      --AND T1.DATADOC BETWEEN TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'') AND TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')
      AND coalesce(T1.Initializari,0) = 1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL),'') || ' )
  SELECT
    (case when ts.codsubunit is NULL then NULL else stingatori.coddoc  end) NAV_CodDoc,
    (case when ts.codsubunit is NULL then NULL else stingatori.coddoc1 end) NAV_CodDoc1,
    (case when ts.codsubunit is NULL then NULL else stingatori.tipdoc  end) NAV_TipDoc,
    stinsi.DocStins,
    stinsi.valoare + SUM(sign(stinsi.valoare)*stingatori.valoare) over (PARTITION BY stingeri.codstinspif ORDER BY stingeri.codgeneral ROWS BETWEEN unbounded preceding AND CURRENT ROW ) TOTAL_DOCUMENT,
    stinsi.valoare + SUM(sign(stinsi.valoare)*stingatori.valoare) over (PARTITION BY stingeri.codstinspif ORDER BY stingeri.codgeneral ROWS BETWEEN unbounded preceding AND CURRENT ROW )  VAL_NESTINSA_DOCUMENT,
    sign(stinsi.valoare)*stingatori.valoare VAL_STINGATOR,
    stinsi.valoare - sign(stinsi.valoare)*stingatori.valoare + SUM(sign(stinsi.valoare)*stingatori.valoare) over (PARTITION BY stingeri.codstinspif ORDER BY stingeri.codgeneral ROWS BETWEEN unbounded preceding AND CURRENT ROW ) SOLD_DOC,
    stingatori.DocStingator, npart.den_part PARTENER, stingatori.DataDecont, stingatori.Data, stinsi.Data_stins, stingatori.codgeneral ORDINE, stinsi.TERMEN, mon.den_moneda MONEDA,
    SubStinsi.den_subunit SUBUNITATEA, SubStingatori.den_subunit SUBUNITATEA_ST, stinsi.termen SCADENTA, trunc(stingatori.Data::date - stinsi.data_stins::date) DIFZILE,
    CASE WHEN trunc(stingatori.data::date - stinsi.termen::date) &gt; 0 THEN trunc(stingatori.data::date - stinsi.termen::date) ELSE 0 END DEPZILE, stinsi.cont, stinsi.curs, stingatori.curs ' || gUserAlias || '
  FROM stingatori
    INNER JOIN stingeri                          on stingeri.codstingatorpif    = stingatori.codobligpif
    INNER JOIN stinsi                            on stingeri.codstinspif        = stinsi.codobligpif
    LEFT  JOIN npers               agent         on agent.codpers               = coalesce(stinsi.agent,0)
    LEFT  JOIN npers               agent_inc     on agent_inc.codpers           = coalesce(stingatori.agent,0)
    LEFT  JOIN npart               npart         on npart.codpart               = coalesce(stinsi.codpart,stingatori.codpart)
    LEFT  JOIN nclasep             clsp          on coalesce(npart.codclasa, 0) = clsp.codclasep
    LEFT  JOIN nagenda             ag            on stinsi.codlocatie           = ag.codagenda
    LEFT  JOIN nlocalit            loc           on ag.codlocalit               = loc.codlocalit
    LEFT  JOIN njudet              jud           on loc.codjudet                = jud.codjudet
    LEFT  JOIN nmonede             mon           ON stinsi.codmoneda            = mon.codmoneda
    LEFT  JOIN nsubunit            SubStingatori ON stingatori.subunitatea      = SubStingatori.codsubunit
    LEFT  JOIN nsubunit            SubStinsi     ON stinsi.subunitatea          = SubStinsi.codsubunit
    LEFT  JOIN tmp_subunitdedicate ts            ON ts.codsubunit               = stingatori.subunitatea' || gSuplJoins || '
  ORDER BY stingatori.codgeneral ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);

  IF  current_setting('PKG_LIST_ALEGPERIOADA.gOpt1', true)::boolean THEN
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect_Ini, aListID, aListVer);
  END IF;

  IF current_setting('PKG_LIST_ALEGPERIOADA.gOpt2', true)::boolean THEN
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect_Fact, aListID, aListVer);
  END IF;

  IF current_setting('PKG_LIST_ALEGPERIOADA.gOpt3', true)::boolean THEN
    PERFORM LIST_EXECUTE_IMMEDIATE('UPDATE ' || tmpName || ' SET TOTAL_DOCUMENT = TOTAL_DOCUMENT*CursDocStins, VAL_NESTINSA_DOCUMENT = VAL_NESTINSA_DOCUMENT*CursDocStins, VAL_STINGATOR = VAL_STINGATOR*CursDocStingator, SOLD_DOC = SOLD_DOC*CursDocStins', aListID, aListVer);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmartpefurn_processlist</obj_name>
  <obj_hashval>e0cfd51ad115c200bf51554ef5af8192</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmartpefurn_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar := '';
  sArticole   varchar := '';
  bToateArt   boolean;
  vCodPart    NUMERIC;
  g_DataIni    VARCHAR := '';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplCols   VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Stef   08.11.2022 - corectie gSuplCols
  --Florin 23.09.2022 - sin. Oracle (22.09.2022)
  --Adina  07 septembrie 2020
  bToateArt := current_setting('PKG_LIST_BASE_URMARTPEFURN.g_bToateArt', true)::boolean;
  vCodPart  := current_setting('PKG_LIST_BASE_URMARTPEFURN.g_CodPart',   true)::NUMERIC;
  g_DataIni := current_setting('PKG_LIST_BASE_URMARTPEFURN.g_DataIni',   true);
  gSuplCols := 'nartobj nobj, nart nart';
  CALL pkg_list_struct_StartSuplCols();
  CALL pkg_list_struct_GetSuplCols(aLISTID,alistver,gUserFields,gUserAlias,gNullAlias,gSuplJoins,gSuplCols);
  PERFORM set_config('pkg_list_base_urmartpefurn.gSuplCols',gSuplCols,false);
  PERFORM pkg_list_base_urmartpefurn_setDataCodObiect();

  IF  NOT bToateArt THEN
    sArticole := ' AND NS.CODOBIECT::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'') ';
  END IF;

  sInsert := 'INSERT INTO ' || TMPNAME || '(
    DENUMIRE, DATAMISCARE, INTRARI_UM, INTRARI_UM1, INTRARI_UM2,IESIRI_UM, IESIRI_UM1,
    IESIRI_UM2, MANIPULARE_UM, MANIPULARE_UM1, MANIPULARE_UM2, STOC_FAKE_UM,
    STOC_FAKE_UM1, STOC_FAKE_UM2,stoc_data_art,stoc_data_art_um1,stoc_data_art_um2, DEN_UM, DEN_UM1,DEN_UM2'||gUserFields||')
  WITH CRS_MISCARI AS (
    SELECT
      NS.CODOBIECT CODOBIECT,
      CASE WHEN NIR.TIPNIR IN (1,2,3,4,5,6,7,14,15,16,19,20,21,22,23,24) THEN coalesce(pkg_list_base_urmArtPeFurn_get_cant_umprinc(ns.cantnir,ns.umsec),0) ELSE 0 END INTRARE_UM,
      CASE WHEN NIR.TIPNIR IN (1,2,3,4,5,6,7,14,15,16,19,20,21,22,23,24) THEN coalesce(NS.CANTUM1,0) ELSE 0 END INTRARE_UM1,
      CASE WHEN NIR.TIPNIR IN (1,2,3,4,5,6,7,14,15,16,19,20,21,22,23,24) THEN coalesce(NS.CANTUM2,0) ELSE 0 END INTRARE_UM2,
      0 IESIRE_UM,
      0 IESIRE_UM1,
      0 IESIRE_UM2,
      NIR.DATANIR  DATAMISCARE,
      CASE WHEN NIR.TIPNIR IN (1,2,3,4,5,6,7,14,15,16,19,20,21,22,23,24) THEN abs(pkg_list_base_urmArtPeFurn_get_cant_umprinc(NS.CANTNIR,ns.umsec)) ELSE 0 END stoc_fake_UM,
      CASE WHEN NIR.TIPNIR IN (1,2,3,4,5,6,7,14,15,16,19,20,21,22,23,24) THEN abs(NS.CANTUM1) ELSE 0 END stoc_fake_UM1,
      CASE WHEN NIR.TIPNIR IN (1,2,3,4,5,6,7,14,15,16,19,20,21,22,23,24) THEN abs(NS.CANTUM2) ELSE 0 END stoc_fake_UM2
    FROM  NIRSTOC NS
      LEFT JOIN NIR          ON NS.CODNIR    = NIR.CODNIR
      LEFT JOIN INTRARI INTR ON INTR.CODINTR = NIR.CODINTR
      LEFT JOIN NGEST   NG   ON NG.CODGEST   = NIR.GEST
    WHERE NS.FURN = ' || vCodPart::varchar || ' ' || coalesce(pkg_list_base_utils_cond_subunit('NG', 'CODSUBUNIT',NULL,NULL) ,'') || sArticole || '
    UNION ALL
    SELECT
      NS.CODOBIECT CODOBIECT,
      CASE
        WHEN L.TIPLIVR IN (1,2,3,4,5,6,7,14,15,16,19,20,21,22,23,24) AND L1.CANT &lt; 0 THEN -pkg_list_base_urmArtPeFurn_get_cant_umprinc(L1.CANT,L1.UMSEC)
        WHEN L.TIPLIVR = 15 AND L1.CANT &gt; 0 THEN pkg_list_base_urmArtPeFurn_get_cant_umprinc(L1.CANT,L1.UMSEC)
        ELSE 0
      END INTRARE_UM,
      CASE WHEN L.TIPLIVR IN (1,2,3,4,5,6,7,14,15,16,19,20,21,22,23,24) AND L1.CANTUM1 &lt; 0 THEN -L1.CANTUM1 WHEN L.TIPLIVR = 15 AND L1.CANTUM1 &gt; 0 THEN L1.CANTUM1 ELSE 0 END INTRARE_UM1,
      CASE WHEN L.TIPLIVR IN (1,2,3,4,5,6,7,14,15,16,19,20,21,22,23,24) AND L1.CANTUM2 &lt; 0 THEN -L1.CANTUM2 WHEN L.TIPLIVR = 15 AND L1.CANTUM2 &gt; 0 THEN L1.CANTUM2 ELSE 0 END INTRARE_UM2,
      CASE WHEN L.TIPLIVR IN (1,2,3,4,5,6,7,14,16,19,20,21,22,23,24)    AND L1.CANT &gt; 0    THEN pkg_list_base_urmArtPeFurn_get_cant_umprinc(L1.CANT,L1.UMSEC)      ELSE 0 END IESIRE,
      CASE WHEN L.TIPLIVR IN (1,2,3,4,5,6,7,14,16,19,20,21,22,23,24)    AND L1.CANTUM1 &gt; 0 THEN L1.CANTUM1 ELSE 0 END IESIRE_UM1,
      CASE WHEN L.TIPLIVR IN (1,2,3,4,5,6,7,14,16,19,20,21,22,23,24)    AND L1.CANTUM2 &gt; 0 THEN L1.CANTUM2 ELSE 0 END IESIRE_UM2,
      coalesce(l.datalivr,nir.datanir) DATAMISCARE,
      CASE
        WHEN L.TIPLIVR IN (1,2,3,4,5,6,7,14,16,19,20,21,22,23,24) THEN    -pkg_list_base_urmArtPeFurn_get_cant_umprinc(L1.CANT,L1.UMSEC)
        WHEN L.TIPLIVR = 15                                       THEN ABS(pkg_list_base_urmArtPeFurn_get_cant_umprinc(L1.CANT,L1.UMSEC))
        ELSE 0
      END stoc_fake_UM,
      CASE
        WHEN L.TIPLIVR IN (1,2,3,4,5,6,7,14,16,19,20,21,22,23,24) THEN -L1.CANTUM1
        WHEN L.TIPLIVR = 15                                       THEN ABS(L1.CANTUM1)
        ELSE 0
      END stoc_fake_UM1,
      CASE
        WHEN L.TIPLIVR IN (1,2,3,4,5,6,7,14,16,19,20,21,22,23,24) THEN -L1.CANTUM2
        WHEN L.TIPLIVR = 15                                       THEN ABS(L1.CANTUM2)
        ELSE 0
      END stoc_fake_UM2
    FROM LIVR L
      LEFT JOIN LIVR1   L1 ON L1.CODLIVR    = L.CODLIVR
      LEFT JOIN NIRSTOC NS ON NS.CODNIRSTOC = L1.CODNIRSTOC
      LEFT JOIN NIR        ON NS.CODNIR     = NIR.CODNIR
      LEFT JOIN NGEST   NG ON NG.CODGEST    = NIR.GEST
    WHERE NS.FURN = ' || vCodPart::varchar || ' ' || coalesce(pkg_list_base_utils_cond_subunit('NG', 'CODSUBUNIT',NULL,NULL),'') || sArticole || '
    UNION ALL
    SELECT
      NS.CODOBIECT,
      0 INTRARI_UM,
      0 INTRARI_UM1,
      0 INTRARI_UM2,
      0 IESIRI_UM,
      0 IESIRI_UM1,
      0 IESIRI_UM2,
      TO_DATE(''' || g_DataIni || ''', ''DD.MM.YYYY'') - 1 DATAMISCARE,
      SUM(NL.REST) STOC_FAKE_UM,
      SUM(NL.RESTUM1) STOC_FAKE_UM1,
      SUM(NL.RESTUM2) STOC_FAKE_UM2
    FROM NIRLUNA NL
      INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = NL.CODNIRSTOC
      LEFT  JOIN NIR        ON NS.CODNIR     = NIR.CODNIR
      LEFT  JOIN NGEST   NG ON NG.CODGEST    = NIR.GEST
    WHERE NS.FURN = ' || vCodPart::varchar || ' '  || coalesce(pkg_list_base_utils_cond_subunit('NG', 'CODSUBUNIT',NULL,NULL),'') || sArticole || '
    GROUP BY NS.CODOBIECT
  ),
  CRS_GRUP AS (
    SELECT
      C_DATA.CODOBIECT,C_DATA.DATA DATAMISCARE,
      coalesce(SUM(MISC.INTRARE_UM)   ,0) INTRARI_UM,
      coalesce(SUM(MISC.INTRARE_UM1)  ,0) INTRARI_UM1,
      coalesce(SUM(MISC.INTRARE_UM2)  ,0) INTRARI_UM2,
      coalesce(SUM(MISC.IESIRE_UM)    ,0) IESIRI_UM,
      coalesce(SUM(MISC.IESIRE_UM1)   ,0) IESIRI_UM1,
      coalesce(SUM(MISC.IESIRE_UM2)   ,0) IESIRI_UM2,
      coalesce(SUM(MISC.INTRARE_UM)   ,0) + coalesce(SUM(MISC.IESIRE_UM) ,0) MANIPULARE_UM,
      coalesce(SUM(MISC.INTRARE_UM1)  ,0) + coalesce(SUM(MISC.IESIRE_UM1),0) MANIPULARE_UM1,
      coalesce(SUM(MISC.INTRARE_UM2)  ,0) + coalesce(SUM(MISC.IESIRE_UM2),0) MANIPULARE_UM2,
      coalesce(SUM(MISC.STOC_FAKE_UM) ,0) STOC_FAKE_UM,
      coalesce(SUM(MISC.STOC_FAKE_UM1),0) STOC_FAKE_UM1,
      coalesce(SUM(MISC.STOC_FAKE_UM2),0) STOC_FAKE_UM2
    FROM TMP_LST_URMARTPEFURN C_DATA
      LEFT JOIN CRS_MISCARI MISC ON C_DATA.CODOBIECT = MISC.CODOBIECT AND C_DATA.DATA = MISC.DATAMISCARE
    GROUP BY C_DATA.CODOBIECT,C_DATA.DATA
  )
  SELECT
    NOBJ.DENUMIRE, C_GRUP.DATAMISCARE, C_GRUP.INTRARI_UM, C_GRUP.INTRARI_UM1, C_GRUP.INTRARI_UM2, C_GRUP.IESIRI_UM, C_GRUP.IESIRI_UM1, C_GRUP.IESIRI_UM2,
    C_GRUP.MANIPULARE_UM, C_GRUP.MANIPULARE_UM1, C_GRUP.MANIPULARE_UM2, C_GRUP.STOC_FAKE_UM, C_GRUP.STOC_FAKE_UM1, C_GRUP.STOC_FAKE_UM2 ,
    sum(c_grup.stoc_fake_um)  over (partition by nobj.denumire order by nobj.denumire,c_grup.datamiscare rows between unbounded preceding and current row ) stoc_data_art ,
    sum(c_grup.stoc_fake_um1) over (partition by nobj.denumire order by nobj.denumire,c_grup.datamiscare rows between unbounded preceding and current row ) stoc_data_art_um1 ,
    sum(c_grup.stoc_fake_um2) over (partition by nobj.denumire order by nobj.denumire,c_grup.datamiscare rows between unbounded preceding and current row ) stoc_data_art_um2 ,
    UM.DEN_UM DEN_UM, UM1.DEN_UM DEN_UM1, UM2.DEN_UM DEN_UM2'||gUserAlias||'
  FROM CRS_GRUP C_GRUP
    INNER JOIN NARTOBJ NOBJ ON C_GRUP.CODOBIECT = NOBJ.CODOBIECT
    INNER JOIN NART    NART ON NART.CODARTICOL  = NOBJ.CODARTICOL
    LEFT  JOIN NUM     UM   ON UM.CODUM         = NART.UM
    LEFT  JOIN NUM     UM1  ON UM1.CODUM        = NART.UM1
    LEFT  JOIN NUM     UM2  ON UM2.CODUM        = NART.UM2 '||gSuplJoins;

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmcomfactsa_processlist</obj_name>
  <obj_hashval>5d8c7345d129b3d951e68cf90ed665d6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmcomfactsa_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sSelect1         varchar := '';
  sSelect2         varchar := '';
  sSelect3         varchar := '';
  sSelect4         varchar := '';
  sJoinAux         varchar := '';
  sPer             varchar := '';
  sFiltruInchise   varchar := '';
  gSuplCols        VARCHAR := '';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  gDataS          varchar := current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true);
  gDataF          varchar := current_setting('PKG_LIST_ALEGPERIOADA.gDataF', true);
  gOpt1            boolean := current_setting('PKG_LIST_ALEGPERIOADA.gOpt1' , true)::boolean;
BEGIN
  --Florin 05.06.2024 - fixat 62253
  --Adina 16.10.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDC'   , 'CV'   , 'CV.CODCOMANDA   = C.CODCOMANDA'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDC1'  , 'CV1'  , 'CV1.CODCOMANDA1 = C1.CODCOMANDA1',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT' , 'OEXT.CODOBIECT  = C1.CODOBIECT'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR' , 'OATR.CODOBIECT  = C1.CODOBIECT'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CENTRECOST', 'CCOST', 'CCOST.CODCENTRU = coalesce(C1.CODCENTRU,0)');
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_URMCOMFACTSA.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  IF  to_date(gDataS,'dd.mm.yyyy') = to_date(gDataF,'dd.mm.yyyy') THEN
    sPer := '= TO_DATE(''' || coalesce(gDataS,'') || ''',''dd.mm.yyyy'')';
  ELSE
    sPer := 'BETWEEN TO_DATE(''' || coalesce(gDataS,'') || ''',''dd.mm.yyyy'') AND TO_DATE(''' || coalesce(gDataF,'') || ''',''dd.mm.yyyy'')';
  END IF;

  IF  NOT gOpt1 THEN
    sFiltruInchise := ' AND C.INCHISA = 0 ';
  END IF;

  sInsert :=
  'INSERT INTO ' || tmpName || '(
    NAV_CodDoc,NAV_TipDoc, Com, Doc, Part,
    Art, UM, Cant, CantCom, CantPrel, RestC, RestV,
    NrLinCom, Ordine,
    DenLaCli, CodLaCli,
    CodListat,
    SUBUNITATEA,
    TipRez,
    CodExtern,
    MODEL,
    MARCA,
    NRINREG,
    ANFABRICATIE,
    CULOAREC,
    SERIECAROSERIE,
    SERIEMOTOR' || gUserFields || ')';

  sSelect1 := '
  SELECT
    c.codcomanda, c.tipdoc, c.PrefixDoc||c.NrDoc||''/''||c.Datadoc::date,c.PrefixDoc||c.NrDoc||''/''||c.Datadoc::date, p.Den_Part,
    o.denumire, u.den_um1, c1.cantacceptat/u.paritate, c1.cantacceptat/u.paritate, 0, c1.cantacceptat/u.paritate, c1.cantacceptat*coalesce(c1.pu,0),
    c1.codcomanda1, 0,
    --ROW_NUMBER() OVER (PARTITION BY C.CodComanda ORDER BY C1.CodComanda1 ASC), 0,
    COALESCE(ac.denumire,trad.denumiretrad,o.denumire), coalesce(ac.codextern,o.codextern),
    coalesce((case ac.tipcodafisat when 1 then gre.cod when 2 then ac.codextern when 3 then o.codextern when 4 then o.codintern when 5 then o.codvamal when 6 then o.codplu::varchar when 7 then o1.codextofe end),o.codextern),
    s.den_subunit, (case C.FaraFactura when 0 then ''-'' when 1 then ''Comanda interna'' end), o.CodExtern,
    NMo.Model, NMa.Marca, NPA.NRINREG, NPA.ANF AnFabricatie, NPA.CULOAREC,NPA.SERIEC SerieCaroserie, NPA.Seriem SerieMotor ' || gUserAlias || '
  FROM comanda c
    INNER JOIN comanda1 c1      ON c1.codcomanda    = c.codcomanda
    INNER JOIN nartobj o        ON o.codobiect      = c1.codobiect
    INNER JOIN nart art         ON o.codarticol     = art.codarticol
    INNER JOIN num1 u           ON u.codum1         = c1.umsec
    LEFT  JOIN npart p          ON p.codpart        = c.partener
    LEFT  JOIN nclasea cla      on cla.codclasea    = art.clasa
    LEFT  JOIN nclasep clp      on clp.codclasep    = p.codclasa
    LEFT  JOIN nagenda slvr     on slvr.codagenda   = c.codlocatie
    LEFT  JOIN nlocalit llivr   ON llivr.codlocalit = slvr.codlocalit
    LEFT  JOIN njudet jlivr     ON jlivr.codjudet   = llivr.codjudet
    LEFT  JOIN ntari tlivr      ON tlivr.codtara    = llivr.codtara
    LEFT  JOIN traseulivr t     on t.codtraseulivr  = slvr.codtraseu
    LEFT  JOIN npart prod       ON prod.codpart     = o.codproducator
    LEFT  JOIN ncarsupart cs    ON cs.codcarsupart  = o.codcaract
    LEFT  JOIN nparttr d        ON d.codparttr      = c.delegat
    LEFT  JOIN nartcli ac       ON ac.codobiect     = c1.codobiect AND ac.codpart = c.partener
    LEFT  JOIN nartobjtrad trad ON trad.codlimba    = tlivr.codlimba and trad.codobiect = c1.codobiect
    LEFT  JOIN nechiv e         ON e.codobiect      = c1.codobiect
    LEFT  JOIN grechiv gre      ON gre.codgrechiv   = e.codgrupa
    LEFT  JOIN oferta1 o1       ON o1.codoferta1    = c1.codsursa
    LEFT  JOIN nsubunit s       On s.codsubunit     = c.subunitatea
    -- joinuri false pt coloane suplimentare
    LEFT  JOIN iesiri i         ON i.codies         = (c1.codcomanda-c1.codcomanda)
    LEFT  JOIN iesiri1 i1       ON i1.codies1       = (c1.codcomanda-c1.codcomanda)
    LEFT  JOIN comanda1 cst1    ON cst1.codcomanda1 = (c1.codcomanda-c1.codcomanda)
    LEFT  JOIN comanda cst      ON cst.codcomanda   = (c1.codcomanda-c1.codcomanda)
    LEFT  JOIN Nparccom NPC     on NPC.CodComanda   = C.CodComanda
    LEFT  JOIN NparcAut NPA     on NPA.CodNparcaut  = NPC.CodNparcaut
    LEFT  JOIN Nmarciauto NMa   on Nma.Codmarciauto = NPA.Marca
    LEFT  JOIN NModeleauto NMo  on NMo.CodModeleauto= NPA.Model' || gSuplJoins || '
  WHERE c.tipdoc = 92 AND c.operat = 1 ' || sFiltruInchise || ' AND c.anulat = 0 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'') || '
    AND NOT (C1.MODINCHIDERE=2 AND ART.TIPARTICOL=''1'') AND c.DataDoc  ' || sPer;

  sSelect2 := '
  SELECT
    cst.codcomanda, cst.tipdoc, c.PrefixDoc||c.NrDoc||''/''||c.Datadoc::date Com,cst.PrefixDoc||cst.NrDoc||''/''||cst.Datadoc::date, p.Den_Part,
    o.denumire, u.den_um1, cl.cant/u.paritate, -cl.cant/u.paritate, 0, -cl.cant/u.paritate, -cl.cant*coalesce(c1.pu,0),
    c1.codcomanda1, 1,
    --ROW_NUMBER() OVER (PARTITION BY C.CodComanda ORDER BY C1.CodComanda1 ASC), 1,
    COALESCE(ac.denumire,trad.denumiretrad,o.denumire), coalesce(ac.codextern,o.codextern),
    coalesce((case ac.tipcodafisat when 1 then gre.cod when 2 then ac.codextern when 3 then o.codextern when 4 then o.codintern when 5 then o.codvamal when 6 then o.codplu::varchar when 7 then o1.codextofe end),o.codextern),
    s.den_subunit, (case C.FaraFactura when 0 then ''-'' when 1 then ''Comanda interna'' end),o.CodExtern,
    NMo.Model, NMa.Marca, NPA.NRINREG, NPA.ANF AnFabricatie, NPA.CULOAREC,NPA.SERIEC SerieCaroserie, NPA.Seriem SerieMotor ' || gUserAlias || '
  FROM comanda c
    INNER JOIN comanda1 c1       ON c1.codcomanda      = c.codcomanda
    INNER JOIN nartobj o         ON o.codobiect        = c1.codobiect
    INNER JOIN nart art         ON o.codarticol       = art.codarticol
    INNER JOIN num1 u           ON u.codum1           = c1.umsec
    INNER JOIN cmdlivrlink cl   ON cl.codliniecomanda = c1.codcomanda1
    INNER JOIN comanda1 cst1     ON cst1.codcomanda1   = cl.codcomanda1
    INNER JOIN comanda cst       ON cst.codcomanda     = cst1.codcomanda
    LEFT  JOIN npart p           ON p.codpart          = c.partener
    LEFT  JOIN nclasea cla       on art.clasa          = cla.codclasea
    LEFT  JOIN nclasep clp       on p.codclasa         = clp.codclasep
    LEFT  JOIN nagenda slvr     on slvr.codagenda     = c.codlocatie
    LEFT  JOIN nlocalit llivr   ON llivr.codlocalit   = slvr.codlocalit
    LEFT  JOIN njudet jlivr     ON jlivr.codjudet     = llivr.codjudet
    LEFT  JOIN ntari tlivr       ON tlivr.codtara      = llivr.codtara
    LEFT  JOIN traseulivr t     on slvr.codtraseu     = t.codtraseulivr
    LEFT  JOIN npart prod       ON prod.codpart       = o.codproducator
    LEFT  JOIN ncarsupart cs     ON cs.codcarsupart    = o.codcaract
    LEFT  JOIN nparttr d         ON d.codparttr        = c.delegat
    LEFT  JOIN nartcli ac       ON ac.codobiect       = c1.codobiect AND ac.codpart = c.partener
    LEFT  JOIN nartobjtrad trad ON trad.codlimba      = tlivr.codlimba and trad.codobiect = c1.codobiect
    LEFT  JOIN nechiv e         ON e.codobiect        = c1.codobiect
    LEFT  JOIN grechiv gre       ON gre.codgrechiv     = e.codgrupa
    LEFT  JOIN oferta1 o1       ON o1.codoferta1      = c1.codsursa
    LEFT  JOIN nsubunit s       On s.codsubunit       = c.subunitatea
    -- joinuri false pt coloane suplimentare
    LEFT  JOIN iesiri i         ON i.codies           = (c1.codcomanda-c1.codcomanda)
    LEFT  JOIN iesiri1 i1       ON i1.codies1         = (c1.codcomanda-c1.codcomanda)
    LEFT  JOIN Nparccom NPC     on NPC.CodComanda     = C.CodComanda
    LEFT  JOIN NparcAut NPA     on NPA.CodNparcaut    = NPC.CodNparcaut
    LEFT  JOIN Nmarciauto NMa   on Nma.Codmarciauto   = NPA.Marca
    LEFT  JOIN NModeleauto NMo   on NMo.CodModeleauto  = NPA.Model' || gSuplJoins || '
  WHERE c.tipdoc = 92 AND c.operat = 1 ' || sFiltruInchise || ' AND c.anulat = 0
    AND cl.cant &lt;&gt; 0 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'') || '
    AND cst.tipdoc = 65 AND cst.operat = 1 AND cst.anulat = 0
    AND NOT (C1.MODINCHIDERE=2 AND ART.TIPARTICOL=''1'') AND c.DataDoc  ' || sPer;

  sSelect3 := '
  SELECT
    i.codies, i.tipdoc, c.PrefixDoc||c.NrDoc||''/''||c.Datadoc::date Com,i.PrefixDoc||i.NrDoc||''/''||i.Datadoc::date, p.Den_Part,
    o.denumire, u.den_um1, il.cant/u.paritate, 0, il.cant/u.paritate, -il.cant/u.paritate, -il.cant*coalesce(c1.pu,0),
    c1.codcomanda1, 2,
    --ROW_NUMBER() OVER (PARTITION BY C.CodComanda ORDER BY C1.CodComanda1 ASC), 2,
    COALESCE(ac.denumire,trad.denumiretrad,o.denumire), coalesce(ac.codextern,o.codextern),
    coalesce((case ac.tipcodafisat when 1 then gre.cod when 2 then ac.codextern when 3 then o.codextern when 4 then o.codintern when 5 then o.codvamal when 6 then o.codplu::varchar when 7 then o1.codextofe end),o.codextern),
    s.den_subunit,  (case C.FaraFactura when 0 then ''-'' when 1 then ''Comanda interna'' end),o.CodExtern,
    NMo.Model, NMa.Marca, NPA.NRINREG, NPA.ANF AnFabricatie, NPA.CULOAREC,NPA.SERIEC SerieCaroserie, NPA.Seriem SerieMotor ' || gUserAlias || '
  FROM comanda c
    INNER JOIN comanda1 c1       ON c1.codcomanda      = c.codcomanda
    INNER JOIN nartobj o         ON o.codobiect        = c1.codobiect
    INNER JOIN nart art         ON o.codarticol       = art.codarticol
    INNER JOIN num1 u           ON u.codum1           = c1.umsec
    INNER JOIN ieslink il       ON il.codliniecomanda = c1.codcomanda1
    INNER JOIN iesiri1 i1       ON i1.codies1         = il.codies1
    INNER JOIN iesiri i         ON i.codies           = i1.codies
    LEFT  JOIN npart p           ON p.codpart          = c.partener
    LEFT  JOIN nclasea cla       on art.clasa          = cla.codclasea
    LEFT  JOIN nclasep clp       on p.codclasa         = clp.codclasep
    LEFT  JOIN nagenda slvr     on slvr.codagenda     = c.codlocatie
    LEFT  JOIN nlocalit llivr   ON llivr.codlocalit   = slvr.codlocalit
    LEFT  JOIN njudet jlivr     ON jlivr.codjudet     = llivr.codjudet
    LEFT  JOIN ntari tlivr       ON tlivr.codtara      = llivr.codtara
    LEFT  JOIN traseulivr t     on slvr.codtraseu     = t.codtraseulivr
    LEFT  JOIN npart prod       ON prod.codpart       = o.codproducator
    LEFT  JOIN ncarsupart cs     ON cs.codcarsupart    = o.codcaract
    LEFT  JOIN nparttr d         ON d.codparttr        = c.delegat
    LEFT  JOIN nartcli ac       ON ac.codobiect       = c1.codobiect AND ac.codpart = c.partener
    LEFT  JOIN nartobjtrad trad ON trad.codlimba      = tlivr.codlimba and trad.codobiect = c1.codobiect
    LEFT  JOIN nechiv e         ON e.codobiect        = c1.codobiect
    LEFT  JOIN grechiv gre       ON gre.codgrechiv     = e.codgrupa
    LEFT  JOIN oferta1 o1       ON o1.codoferta1      = c1.codsursa
    LEFT  JOIN nsubunit s       On s.codsubunit       = c.subunitatea
    -- joinuri false pt coloane suplimentare
    LEFT  JOIN comanda1 cst1     ON cst1.codcomanda1   = (c1.codcomanda-c1.codcomanda)
    LEFT  JOIN comanda cst       ON cst.codcomanda     = (c1.codcomanda-c1.codcomanda)
    LEFT  JOIN Nparccom NPC     on NPC.CodComanda     = C.CodComanda
    LEFT  JOIN NparcAut NPA     on NPA.CodNparcaut    = NPC.CodNparcaut
    LEFT  JOIN Nmarciauto NMa   on Nma.Codmarciauto   = NPA.Marca
    LEFT  JOIN NModeleauto NMo   on NMo.CodModeleauto  = NPA.Model' || gSuplJoins || '
  WHERE c.tipdoc = 92 AND c.operat = 1 ' || sFiltruInchise || ' AND c.anulat = 0 AND il.cant &lt;&gt; 0 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'') || '
    AND i.operat = 1 AND i.anulat = 0 AND NOT (C1.MODINCHIDERE=2 AND ART.TIPARTICOL=''1'')
    AND c.DataDoc   ' || sPer;

  sSelect4 := '
  SELECT
    i.codies, i.tipdoc, c.PrefixDoc||c.NrDoc||''/''||c.Datadoc::date Com,i.PrefixDoc||i.NrDoc||''/''||i.Datado::datec, p.Den_Part,
    o.denumire, u.den_um1, i1.cant/u.paritate, 0, i1.cant/u.paritate, -i1.cant/u.paritate, -i1.cant*coalesce(c1.pu,0),
    c1.codcomanda1, 3,
    --ROW_NUMBER() OVER (PARTITION BY C.CodComanda ORDER BY C1.CodComanda1 ASC), 2,
    COALESCE(ac.denumire,trad.denumiretrad,o.denumire), coalesce(ac.codextern,o.codextern),
    coalesce((case ac.tipcodafisat when 1 then gre.cod when 2 then ac.codextern when 3 then o.codextern when 4 then o.codintern when 5 then o.codvamal when 6 then o.codplu::varchar when 7 then o1.codextofe end),o.codextern),
    s.den_subunit,  (case C.FaraFactura when 0 then ''-'' when 1 then ''Comanda interna'' end),o.CodExtern,
    NMo.Model, NMa.Marca, NPA.NRINREG, NPA.ANF AnFabricatie, NPA.CULOAREC,NPA.SERIEC SerieCaroserie, NPA.Seriem SerieMotor ' || gUserAlias || '
  FROM comanda c
    INNER JOIN comanda1 c1       ON c1.codcomanda    = c.codcomanda
    INNER JOIN nartobj o         ON o.codobiect      = c1.codobiect
    INNER JOIN nart art         ON o.codarticol     = art.codarticol
    INNER JOIN num1 u           ON u.codum1         = c1.umsec
    INNER JOIN iesiri1 i1       ON i1.codcmdint1    = c1.codcomanda1
    INNER JOIN iesiri i         ON i.codies         = i1.codies
    LEFT  JOIN npart p           ON p.codpart        = c.partener
    LEFT  JOIN nclasea cla       on art.clasa        = cla.codclasea
    LEFT  JOIN nclasep clp       on p.codclasa       = clp.codclasep
    LEFT  JOIN nagenda slvr     on slvr.codagenda   = c.codlocatie
    LEFT  JOIN nlocalit llivr   ON llivr.codlocalit = slvr.codlocalit
    LEFT  JOIN njudet jlivr     ON jlivr.codjudet   = llivr.codjudet
    LEFT  JOIN ntari tlivr       ON tlivr.codtara    = llivr.codtara
    LEFT  JOIN traseulivr t     on slvr.codtraseu   = t.codtraseulivr
    LEFT  JOIN npart prod       ON prod.codpart     = o.codproducator
    LEFT  JOIN ncarsupart cs     ON cs.codcarsupart  = o.codcaract
    LEFT  JOIN nparttr d         ON d.codparttr      = c.delegat
    LEFT  JOIN nartcli ac       ON ac.codobiect     = c1.codobiect AND ac.codpart = c.partener
    LEFT  JOIN nartobjtrad trad ON trad.codlimba    = tlivr.codlimba and trad.codobiect = c1.codobiect
    LEFT  JOIN nechiv e         ON e.codobiect      = c1.codobiect
    LEFT  JOIN grechiv gre       ON gre.codgrechiv   = e.codgrupa
    LEFT  JOIN oferta1 o1       ON o1.codoferta1    = c1.codsursa
    LEFT  JOIN nsubunit s       On s.codsubunit     = c.subunitatea
    -- joinuri false pt coloane suplimentare
    LEFT  JOIN comanda1 cst1     ON cst1.codcomanda1 = (c1.codcomanda-c1.codcomanda)
    LEFT  JOIN comanda cst       ON cst.codcomanda   = (c1.codcomanda-c1.codcomanda)
    LEFT  JOIN Nparccom NPC     on NPC.CodComanda   = C.CodComanda
    LEFT  JOIN NparcAut NPA     on NPA.CodNparcaut  = NPC.CodNparcaut
    LEFT  JOIN Nmarciauto NMa   on Nma.Codmarciauto = NPA.Marca
    LEFT  JOIN NModeleauto NMo   on NMo.CodModeleauto= NPA.Model' || gSuplJoins || '
  WHERE c.tipdoc = 92 AND c.operat = 1 ' || sFiltruInchise || ' AND c.anulat = 0 AND i1.cant &lt;&gt; 0 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'') || '
    AND i.operat = 1 AND i.anulat = 0 AND NOT (C1.MODINCHIDERE=2 AND ART.TIPARTICOL=''1'')
    AND c.DataDoc  ' || sPer;

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect1, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect2, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect3, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect4, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmcomfurn_processlist</obj_name>
  <obj_hashval>afb0db5733ea980ac5cda05ebd9024fe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmcomfurn_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplCols   VARCHAR := '';
  gSuplJoins  VARCHAR := '';

  sInsert     varchar;
  sSelect1    varchar;
  sSelect2    varchar;
  sSelect3    varchar;
  sPer        varchar;
BEGIN
  --Florin 14.12.2022 - fixat 56546
  --Florin 18.11.2022 - fixat 56301
  --Bogdan 01.09.2020
  gSuplCols :=
      'comanda c, comanda1 c1, nartobj o, nart art, num1 u, npart p, intrari1 i1, intrari i, comanda cst, comanda1 cst1, nclasea cla, nclasep clp, traseulivr t,'||
      'npart prod, ncarsupart cs, nparttr d ';

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDF'   , 'CVC'  , 'CVC.CODCOMANDA = C.CODCOMANDA'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDF1'  , 'CVC1' , 'CVC1.CODCOMANDA1 = C1.CODCOMANDA1',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT' , 'OEXT.CODOBIECT = C1.CODOBIECT'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR' , 'OATR.CODOBIECT = C1.CODOBIECT'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CENTRECOST', 'CCOST', 'CCOST.CODCENTRU = coalesce(C1.CODCENTRU,0)');
  CALL pkg_list_struct_getsuplcols( aLISTID, aLISTVER, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config('PKG_LIST_BASE_URMCOMFURN.gSuplCols',gSuplCols,false);

  sInsert := 'INSERT INTO ' || coalesce(tmpName,'') || '(
            NAV_CodDoc,NAV_TipDoc,Com, Doc, Part,
            Art, UM, Cant, CantCom, CantPrel, RestC, RestV,
            NrLinCom, Ordine,
            DenLaCli, CodLaCli,
            CodListat,
            SUBUNITATEA, CATUSER, FACTURABIL,
            NIV1Stare, NIV1User, NIV2Stare, NIV2User, NIV3Stare, NIV3User, NIV4Stare, NIV4User,
          NIV5Stare, NIV5User, STARE' || coalesce(gUserFields,'') || ')';

  IF  (SELECT PKG_LIST_ALEGPERIOADA_getDataS.WME_RESULT FROM PKG_LIST_ALEGPERIOADA_getDataS(NULL,NULL))
      =
      (SELECT PKG_LIST_ALEGPERIOADA_getDataF.WME_RESULT FROM PKG_LIST_ALEGPERIOADA_getDataF(NULL,NULL))
  THEN
      sPer := '= TO_DATE(''' || coalesce(To_Char((SELECT PKG_LIST_ALEGPERIOADA_getDataS.WME_RESULT FROM PKG_LIST_ALEGPERIOADA_getDataS(NULL,NULL)), 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
  ELSE
      sPer := 'BETWEEN TO_DATE(''' || coalesce(To_Char((SELECT PKG_LIST_ALEGPERIOADA_getDataS.WME_RESULT FROM PKG_LIST_ALEGPERIOADA_getDataS(NULL,NULL)), 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')
                   AND TO_DATE(''' || coalesce(To_Char((SELECT PKG_LIST_ALEGPERIOADA_getDataF.WME_RESULT FROM PKG_LIST_ALEGPERIOADA_getDataF(NULL,NULL)), 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
  END IF;

  sSelect1 := '
      select
        c.codcomanda, c.tipdoc, c.PrefixDoc||c.NrDoc||''/''||c.Datadoc::date, c.PrefixDoc||c.NrDoc||''/''||c.Datadoc::date, p.Den_Part,
        o.denumire, u.den_um1, c1.cantacceptat/u.paritate, c1.cantacceptat/u.paritate, 0, c1.cantacceptat/u.paritate, c1.cantacceptat*coalesce(c1.pu,0),
        ROW_NUMBER() OVER (PARTITION BY C.CodComanda ORDER BY C1.CodComanda1 ASC), 0 ,
        COALESCE(ac.denumire,trad.denumiretrad,o.denumire), coalesce(ac.codextern,o.codextern),
        coalesce((CASE ac.tipcodafisat
                    WHEN 1 THEN gre.cod :: varchar
                    WHEN 2 THEN ac.codextern :: varchar
                    WHEN 3 THEN o.codextern :: varchar
                    WHEN 4 THEN o.codintern :: varchar
                    WHEN 5 THEN o.codvamal :: varchar
                    WHEN 6 THEN o.codplu :: varchar
                    WHEN 7 THEN o1.codextofe :: varchar
                  END),o.codextern),
        s.den_subunit,
        (SELECT wme_result from WINMADMIN.PKG_USERFIRME_GET_NUME_GRUP_USER(null, c.USerId)),
        CASE WHEN coalesce(c.nrmaxaprobari,0) &lt;= coalesce(Aprob.NRAprob,0) THEN ''DA'' ELSE ''NU'' END,
        (case Aprob.Niv1Stare
            when 0 then ''Incert''
            when 1 then ''Aprobat''
            when 2 then  ''Respins'' end), Niv1User,
        (case Aprob.Niv2Stare
            when 0 then ''Incert''
            when 1 then ''Aprobat''
            when 2 then  ''Respins'' end), Niv2User,
        (case Aprob.Niv3Stare
            when 0 then ''Incert''
            when 1 then ''Aprobat''
            when 2 then  ''Respins'' end), Niv3User,
        (case Aprob.Niv4Stare
            when 0 then ''Incert''
            when 1 then ''Aprobat''
            when 2 then  ''Respins'' end), Niv4User,
        (case Aprob.Niv5Stare
            when 0 then ''Incert''
            when 1 then ''Aprobat''
            when 2 then  ''Respins'' end), Niv5User,
        CASE
          WHEN c.FARAFACTURA = 1 THEN ''FARA FACTURARE''
          WHEN (SELECT coalesce(SUM(CTMP1.CANTACCEPTAT), 0) FROM COMANDA1 CTMP1 WHERE CTMP1.CODCOMANDA = C.CODCOMANDA) = 0 THEN ''NECONFIRMATA''
          WHEN (SELECT coalesce(SUM(CTMP1.CANTACCEPTAT), 0) FROM COMANDA1 CTMP1 WHERE CTMP1.CODCOMANDA = C.CODCOMANDA) = (SELECT coalesce(SUM(CTMP1.RESTACCEPTAT), 0) FROM COMANDA1 CTMP1 WHERE CTMP1.CODCOMANDA = C.CODCOMANDA) THEN ''NEFACTURATA''
          WHEN (SELECT coalesce(SUM(CTMP1.CANTACCEPTAT), 0) FROM COMANDA1 CTMP1 WHERE CTMP1.CODCOMANDA = C.CODCOMANDA) &lt;&gt; 0 AND (SELECT coalesce(COUNT(*), 0) FROM COMANDA1 CTMP1 WHERE CTMP1.CODCOMANDA = C.CODCOMANDA AND coalesce(CTMP1.CANTACCEPTAT, 0) &gt; 0 AND coalesce(CTMP1.RESTACCEPTAT, 0) &gt; 0) = 0 THEN ''FACTURATA INTEGRAL''
          WHEN (SELECT coalesce(SUM(CTMP1.CANTACCEPTAT), 0) FROM COMANDA1 CTMP1 WHERE CTMP1.CODCOMANDA = C.CODCOMANDA) &gt; (SELECT coalesce(SUM(CTMP1.RESTACCEPTAT), 0) FROM COMANDA1 CTMP1 WHERE CTMP1.CODCOMANDA = C.CODCOMANDA)  THEN ''FACTURATA PARTIAL''
          ELSE ''''
        END STARE ' || coalesce(gUserAlias,'') || '
      FROM comanda c
        INNER JOIN comanda1    c1   ON c1.codcomanda   = c.codcomanda
        INNER JOIN nartobj     o    ON o.codobiect     = c1.codobiect
        INNER JOIN nart        art  ON o.codarticol    = art.codarticol
        INNER JOIN num1        u    ON u.codum1        = c1.umsec
        INNER JOIN npart       p    ON p.codpart       = c.partener
        LEFT  JOIN nclasea     cla  on art.clasa       = cla.codclasea
        LEFT  JOIN nclasep     clp  on p.codclasa      = clp.codclasep
        LEFT  JOIN nagenda     ag   on c.codlocatie    = ag.codagenda
        LEFT  JOIN traseulivr  t    on ag.codtraseu    = t.codtraseulivr
        LEFT  JOIN npart       prod ON prod.codpart    = o.codproducator
        LEFT  JOIN ncarsupart  cs   ON cs.codcarsupart = o.codcaract
        LEFT  JOIN nparttr     d    ON d.codparttr     = c.delegat
        LEFT  JOIN nartcli     ac   ON ac.codobiect    = c1.codobiect AND ac.codpart = c.partener
        LEFT  JOIN nlocalit    loc  ON loc.codlocalit  = ag.codlocalit
        LEFT  JOIN ntari       tari ON tari.codtara    = loc.codtara
        LEFT  JOIN nartobjtrad trad ON trad.codlimba   = tari.codlimba and trad.codobiect = c1.codobiect
        LEFT  JOIN nechiv      e    ON e.codobiect     = c1.codobiect
        LEFT  JOIN grechiv     gre  ON gre.codgrechiv  = e.codgrupa
        LEFT  JOIN oferta1     o1   ON o1.codoferta1   = c1.codsursa
        LEFT  JOIN nsubunit    s    On s.codsubunit    = c.subunitatea
        LEFT  JOIN (
                    SELECT
                      c.codcomanda, Sum(case when ca.stare = 1 then 1 else 0 end) NRAprob,
                      Max(case when ca.nivel = 1 then ca.stare end) Niv1Stare,
                      Max(case when ca.nivel = 1 then (select wme_result from WINMADMIN.PKG_USERFIRME_GetUserName(null,ca.USerId)) end) Niv1User,
                      Max(case when ca.nivel = 2 then ca.stare end) Niv2Stare,
                      Max(case when ca.nivel = 2 then (select wme_result from WINMADMIN.PKG_USERFIRME_GetUserName(null,ca.USerId)) end) Niv2User,
                      Max(case when ca.nivel = 3 then ca.stare end) Niv3Stare,
                      Max(case when ca.nivel = 3 then (select wme_result from WINMADMIN.PKG_USERFIRME_GetUserName(null,ca.USerId)) end) Niv3User,
                      Max(case when ca.nivel = 4 then ca.stare end) Niv4Stare,
                      Max(case when ca.nivel = 4 then (select wme_result from WINMADMIN.PKG_USERFIRME_GetUserName(null,ca.USerId)) end) Niv4User,
                      Max(case when ca.nivel = 5 then ca.stare end) Niv5Stare,
                      Max(case when ca.nivel = 5 then (select wme_result from WINMADMIN.PKG_USERFIRME_GetUserName(null,ca.USerId)) end) Niv5User
                    FROM comanda c INNER JOIN cmdaprobari ca ON ca.coddoc = c.codcomanda AND ca.tipdoc = c.tipdoc
                    GROUP BY c.codcomanda
                   )          Aprob ON Aprob.CodComanda = C.CodComanda
        -- joinuri false pt coloane suplimentare
        LEFT  JOIN intrari1    i1   ON i1.codintr1      = (c1.codcomanda-c1.codcomanda)
        LEFT  JOIN intrari     i    ON i.codintr        = (c1.codcomanda-c1.codcomanda)
        LEFT  JOIN comanda1    cst1 ON cst1.codcomanda1 = (c1.codcomanda-c1.codcomanda)
        LEFT  JOIN comanda     cst  ON cst.codcomanda   = (c1.codcomanda-c1.codcomanda)' || coalesce(gSuplJoins,'') || '
      WHERE c.tipdoc = 8 AND c.operat = 1 AND c.anulat  = 0 '
          || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'C',NULL,NULL,NULL)),'') || '
        AND c.DataDoc ' || coalesce(sPer,'');
  sSelect2 := '
      SELECT
        cst.codcomanda, cst.tipdoc, c.PrefixDoc||c.NrDoc||''/''||c.Datadoc::date Com,cst.PrefixDoc||cst.NrDoc||''/''||cst.Datadoc::date, p.Den_Part,
        o.denumire, u.den_um1, cl.cant/u.paritate, -cl.cant/u.paritate, 0, -cl.cant/u.paritate, -cl.cant*coalesce(c1.pu,0),
        ROW_NUMBER() OVER (PARTITION BY C.CodComanda ORDER BY C1.CodComanda1 ASC), 1,
        COALESCE(ac.denumire,trad.denumiretrad,o.denumire), coalesce(ac.codextern,o.codextern),
        coalesce((CASE ac.tipcodafisat
                    WHEN 1 THEN gre.cod :: varchar
                    WHEN 2 THEN ac.codextern :: varchar
                    WHEN 3 THEN o.codextern :: varchar
                    WHEN 4 THEN o.codintern :: varchar
                    WHEN 5 THEN o.codvamal :: varchar
                    WHEN 6 THEN o.codplu :: varchar
                    WHEN 7 THEN o1.codextofe :: varchar
                  END),o.codextern),
        s.den_subunit,
      (select wme_result from WINMADMIN.PKG_USERFIRME_GET_NUME_GRUP_USER(null,c.USerId)),
      CASE WHEN coalesce(c.nrmaxaprobari,0) &lt;= coalesce(Aprob.NRAprob,0) THEN ''DA'' ELSE ''NU'' END,
        (case Aprob.Niv1Stare
            when 0 then ''Incert''
            when 1 then ''Aprobat''
            when 2 then  ''Respins'' end), Niv1User,
        (case Aprob.Niv2Stare
            when 0 then ''Incert''
            when 1 then ''Aprobat''
            when 2 then  ''Respins'' end), Niv2User,
        (case Aprob.Niv3Stare
            when 0 then ''Incert''
            when 1 then ''Aprobat''
            when 2 then  ''Respins'' end), Niv3User,
        (case Aprob.Niv4Stare
            when 0 then ''Incert''
            when 1 then ''Aprobat''
            when 2 then  ''Respins'' end), Niv4User,
        (case Aprob.Niv5Stare
            when 0 then ''Incert''
            when 1 then ''Aprobat''
            when 2 then  ''Respins'' end), Niv5User,
        CASE
          WHEN c.FARAFACTURA = 1 THEN ''FARA FACTURARE''
          WHEN (SELECT coalesce(SUM(CTMP1.CANTACCEPTAT), 0) FROM COMANDA1 CTMP1 WHERE CTMP1.CODCOMANDA = C.CODCOMANDA) = 0 THEN ''NECONFIRMATA''
          WHEN (SELECT coalesce(SUM(CTMP1.CANTACCEPTAT), 0) FROM COMANDA1 CTMP1 WHERE CTMP1.CODCOMANDA = C.CODCOMANDA) = (SELECT coalesce(SUM(CTMP1.RESTACCEPTAT), 0) FROM COMANDA1 CTMP1 WHERE CTMP1.CODCOMANDA = C.CODCOMANDA) THEN ''NEFACTURATA''
          WHEN (SELECT coalesce(SUM(CTMP1.CANTACCEPTAT), 0) FROM COMANDA1 CTMP1 WHERE CTMP1.CODCOMANDA = C.CODCOMANDA) &lt;&gt; 0 AND (SELECT coalesce(COUNT(*), 0) FROM COMANDA1 CTMP1 WHERE CTMP1.CODCOMANDA = C.CODCOMANDA AND coalesce(CTMP1.CANTACCEPTAT, 0) &gt; 0 AND coalesce(CTMP1.RESTACCEPTAT, 0) &gt; 0) = 0 THEN ''FACTURATA INTEGRAL''
          WHEN (SELECT coalesce(SUM(CTMP1.CANTACCEPTAT), 0) FROM COMANDA1 CTMP1 WHERE CTMP1.CODCOMANDA = C.CODCOMANDA) &gt; (SELECT coalesce(SUM(CTMP1.RESTACCEPTAT), 0) FROM COMANDA1 CTMP1 WHERE CTMP1.CODCOMANDA = C.CODCOMANDA)  THEN ''FACTURATA PARTIAL''
          ELSE ''''
        END STARE ' || coalesce(gUserAlias,'') || '
      FROM comanda c
        INNER JOIN comanda1    c1   ON c1.codcomanda      = c.codcomanda
        INNER JOIN nartobj     o    ON o.codobiect        = c1.codobiect
        INNER JOIN nart        art  ON o.codarticol       = art.codarticol
        INNER JOIN num1        u    ON u.codum1           = c1.umsec
        INNER JOIN npart       p    ON p.codpart          = c.partener
        INNER JOIN cmdlivrlink cl   ON cl.codliniecomanda = c1.codcomanda1
        INNER JOIN comanda1    cst1 ON cst1.codcomanda1   = cl.codcomanda1
        INNER JOIN comanda     cst  ON cst.codcomanda     = cst1.codcomanda
        LEFT  JOIN nclasea     cla  on art.clasa          = cla.codclasea
        LEFT  JOIN nclasep     clp  on p.codclasa         = clp.codclasep
        LEFT  JOIN nagenda     ag   on c.codlocatie       = ag.codagenda
        LEFT  JOIN traseulivr  t    on ag.codtraseu       = t.codtraseulivr
        LEFT  JOIN npart       prod ON prod.codpart       = o.codproducator
        LEFT  JOIN ncarsupart  cs   ON cs.codcarsupart    = o.codcaract
        LEFT  JOIN nparttr     d    ON d.codparttr        = c.delegat
        LEFT  JOIN nartcli     ac   ON ac.codobiect       = c1.codobiect AND ac.codpart = c.partener
        LEFT  JOIN nlocalit    loc  ON loc.codlocalit     = ag.codlocalit
        LEFT  JOIN ntari       tari ON tari.codtara       = loc.codtara
        LEFT  JOIN nartobjtrad trad ON trad.codlimba      = tari.codlimba and trad.codobiect = c1.codobiect
        LEFT  JOIN nechiv      e    ON e.codobiect        = c1.codobiect
        LEFT  JOIN grechiv     gre  ON gre.codgrechiv     = e.codgrupa
        LEFT  JOIN oferta1     o1   ON o1.codoferta1      = c1.codsursa
        LEFT  JOIN nsubunit    s    On s.codsubunit       = c.subunitatea
        LEFT  JOIN (
                    SELECT
                      c.codcomanda, Sum(case when ca.stare=1 then 1 else 0 end) NRAprob,
                      Max(case when ca.nivel = 1 then ca.stare end) Niv1Stare,
                      Max(case when ca.nivel = 1 then (select wme_result from WINMADMIN.PKG_USERFIRME_GetUserName(null,ca.USerId)) end) Niv1User,
                      Max(case when ca.nivel = 2 then ca.stare end) Niv2Stare,
                      Max(case when ca.nivel = 2 then (select wme_result from WINMADMIN.PKG_USERFIRME_GetUserName(null,ca.USerId)) end) Niv2User,
                      Max(case when ca.nivel = 3 then ca.stare end) Niv3Stare,
                      Max(case when ca.nivel = 3 then (select wme_result from WINMADMIN.PKG_USERFIRME_GetUserName(null,ca.USerId)) end) Niv3User,
                      Max(case when ca.nivel = 4 then ca.stare end) Niv4Stare,
                      Max(case when ca.nivel = 4 then (select wme_result from WINMADMIN.PKG_USERFIRME_GetUserName(null,ca.USerId)) end) Niv4User,
                      Max(case when ca.nivel = 5 then ca.stare end) Niv5Stare,
                      Max(case when ca.nivel = 5 then (select wme_result from WINMADMIN.PKG_USERFIRME_GetUserName(null,ca.USerId)) end) Niv5User
                    FROM comanda c INNER JOIN cmdaprobari ca ON ca.coddoc = c.codcomanda AND ca.tipdoc = c.tipdoc
                    GROUP BY c.codcomanda
                   )           Aprob ON Aprob.CodComanda = C.CodComanda
        -- joinuri false pt coloane suplimentare
        LEFT  JOIN intrari1    i1   ON i1.codintr1        = (c1.codcomanda-c1.codcomanda)
        LEFT  JOIN intrari     i    ON i.codintr          = (c1.codcomanda-c1.codcomanda)' || coalesce(gSuplJoins,'') || '
      WHERE c.tipdoc = 8 AND c.operat = 1 AND coalesce(c.inchisa, 0) = 0 AND c.anulat = 0
        AND cl.cant &lt;&gt; 0 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'C',NULL,NULL,NULL)),'') || '
        AND cst.tipdoc = 66 AND cst.operat = 1 AND cst.anulat = 0
        AND c.DataDoc ' || coalesce(sPer,'');
  sSelect3 := '
      SELECT
        i.codintr, i.tipdoc, c.PrefixDoc||c.NrDoc||''/''||c.Datadoc::date Com,i.PrefixDoc||i.NrDoc||''/''||i.Datadoc::date, p.Den_Part,
        o.denumire, u.den_um1, il.cant/u.paritate, 0, il.cant/u.paritate, -il.cant/u.paritate, -il.cant*coalesce(c1.pu,0),
        ROW_NUMBER() OVER (PARTITION BY C.CodComanda ORDER BY C1.CodComanda1 ASC), 2,
        COALESCE(ac.denumire,trad.denumiretrad,o.denumire), coalesce(ac.codextern,o.codextern),
        coalesce((CASE ac.tipcodafisat
                    WHEN 1 THEN gre.cod :: varchar
                    WHEN 2 THEN ac.codextern :: varchar
                    WHEN 3 THEN o.codextern :: varchar
                    WHEN 4 THEN o.codintern :: varchar
                    WHEN 5 THEN o.codvamal :: varchar
                    WHEN 6 THEN o.codplu :: varchar
                    WHEN 7 THEN o1.codextofe :: varchar
                  END),o.codextern),
        s.den_subunit,
        (select wme_result from WINMADMIN.PKG_USERFIRME_GET_NUME_GRUP_USER(null,c.USerId)),
        CASE WHEN coalesce(c.nrmaxaprobari,0) &lt;= coalesce(Aprob.NRAprob,0) THEN ''DA'' ELSE ''NU'' END,
        (case Aprob.Niv1Stare
            when 0 then ''Incert''
            when 1 then ''Aprobat''
            when 2 then  ''Respins'' end), Niv1User,
        (case Aprob.Niv2Stare
            when 0 then ''Incert''
            when 1 then ''Aprobat''
            when 2 then  ''Respins'' end), Niv2User,
        (case Aprob.Niv3Stare
            when 0 then ''Incert''
            when 1 then ''Aprobat''
            when 2 then  ''Respins'' end), Niv3User,
        (case Aprob.Niv4Stare
            when 0 then ''Incert''
            when 1 then ''Aprobat''
            when 2 then  ''Respins'' end), Niv4User,
        (case Aprob.Niv5Stare
            when 0 then ''Incert''
            when 1 then ''Aprobat''
            when 2 then  ''Respins'' end), Niv5User,
        CASE
          WHEN c.FARAFACTURA = 1 THEN ''FARA FACTURARE''
          WHEN (SELECT coalesce(SUM(CTMP1.CANTACCEPTAT), 0) FROM COMANDA1 CTMP1 WHERE CTMP1.CODCOMANDA = C.CODCOMANDA) = 0 THEN ''NECONFIRMATA''
          WHEN (SELECT coalesce(SUM(CTMP1.CANTACCEPTAT), 0) FROM COMANDA1 CTMP1 WHERE CTMP1.CODCOMANDA = C.CODCOMANDA) = (SELECT coalesce(SUM(CTMP1.RESTACCEPTAT), 0) FROM COMANDA1 CTMP1 WHERE CTMP1.CODCOMANDA = C.CODCOMANDA) THEN ''NEFACTURATA''
          WHEN (SELECT coalesce(SUM(CTMP1.CANTACCEPTAT), 0) FROM COMANDA1 CTMP1 WHERE CTMP1.CODCOMANDA = C.CODCOMANDA) &lt;&gt; 0 AND (SELECT coalesce(COUNT(*), 0) FROM COMANDA1 CTMP1 WHERE CTMP1.CODCOMANDA = C.CODCOMANDA AND coalesce(CTMP1.CANTACCEPTAT, 0) &gt; 0 AND coalesce(CTMP1.RESTACCEPTAT, 0) &gt; 0) = 0 THEN ''FACTURATA INTEGRAL''
          WHEN (SELECT coalesce(SUM(CTMP1.CANTACCEPTAT), 0) FROM COMANDA1 CTMP1 WHERE CTMP1.CODCOMANDA = C.CODCOMANDA) &gt; (SELECT coalesce(SUM(CTMP1.RESTACCEPTAT), 0) FROM COMANDA1 CTMP1 WHERE CTMP1.CODCOMANDA = C.CODCOMANDA)  THEN ''FACTURATA PARTIAL''
          ELSE ''''
        END STARE ' || coalesce(gUserAlias,'') || '
      FROM comanda c
        INNER JOIN comanda1    c1   ON c1.codcomanda      = c.codcomanda
        INNER JOIN nartobj     o    ON o.codobiect        = c1.codobiect
        INNER JOIN nart        art  ON o.codarticol       = art.codarticol
        INNER JOIN num1        u    ON u.codum1           = c1.umsec
        INNER JOIN npart       p    ON p.codpart          = c.partener
        INNER JOIN intrlink    il   ON il.codliniecomanda = c1.codcomanda1
        INNER JOIN intrari1    i1   ON i1.codintr1        = il.codintr1
        INNER JOIN intrari     i    ON i.codintr          = i1.codintr
        LEFT  JOIN nclasea     cla  on art.clasa          = cla.codclasea
        LEFT  JOIN nclasep     clp  on p.codclasa         = clp.codclasep
        LEFT  JOIN nagenda     ag   on c.codlocatie       = ag.codagenda
        LEFT  JOIN traseulivr  t    on ag.codtraseu       = t.codtraseulivr
        LEFT  JOIN npart       prod ON prod.codpart       = o.codproducator
        LEFT  JOIN ncarsupart  cs   ON cs.codcarsupart    = o.codcaract
        LEFT  JOIN nparttr     d    ON d.codparttr        = c.delegat
        LEFT  JOIN nartcli     ac   ON ac.codobiect       = c1.codobiect AND ac.codpart = c.partener
        LEFT  JOIN nlocalit    loc  ON loc.codlocalit     = ag.codlocalit
        LEFT  JOIN ntari       tari ON tari.codtara       = loc.codtara
        LEFT  JOIN nartobjtrad trad ON trad.codlimba      = tari.codlimba and trad.codobiect = c1.codobiect
        LEFT  JOIN nechiv      e    ON e.codobiect        = c1.codobiect
        LEFT  JOIN grechiv     gre  ON gre.codgrechiv     = e.codgrupa
        LEFT  JOIN oferta1     o1   ON o1.codoferta1      = c1.codsursa
        LEFT  JOIN nsubunit    s    On s.codsubunit       = c.subunitatea
        LEFT  JOIN (
                    SELECT
                      c.codcomanda, Sum(case when ca.stare=1 then 1 else 0 end) NRAprob,
                      Max(case when ca.nivel = 1 then ca.stare end) Niv1Stare,
                      Max(case when ca.nivel = 1 then (select wme_result from WINMADMIN.PKG_USERFIRME_GetUserName(null,ca.USerId)) end) Niv1User,
                      Max(case when ca.nivel = 2 then ca.stare end) Niv2Stare,
                      Max(case when ca.nivel = 2 then (select wme_result from WINMADMIN.PKG_USERFIRME_GetUserName(null,ca.USerId)) end) Niv2User,
                      Max(case when ca.nivel = 3 then ca.stare end) Niv3Stare,
                      Max(case when ca.nivel = 3 then (select wme_result from WINMADMIN.PKG_USERFIRME_GetUserName(null,ca.USerId)) end) Niv3User,
                      Max(case when ca.nivel = 4 then ca.stare end) Niv4Stare,
                      Max(case when ca.nivel = 4 then (select wme_result from WINMADMIN.PKG_USERFIRME_GetUserName(null,ca.USerId)) end) Niv4User,
                      Max(case when ca.nivel = 5 then ca.stare end) Niv5Stare,
                      Max(case when ca.nivel = 5 then (select wme_result from WINMADMIN.PKG_USERFIRME_GetUserName(null,ca.USerId)) end) Niv5User
                    FROM comanda c INNER JOIN cmdaprobari ca ON ca.coddoc = c.codcomanda AND ca.tipdoc = c.tipdoc
                    GROUP BY c.codcomanda
                   )          Aprob ON Aprob.CodComanda   = C.CodComanda
        -- joinuri false pt coloane suplimentare
        LEFT  JOIN comanda1    cst1 ON cst1.codcomanda1   = (c1.codcomanda-c1.codcomanda)
        LEFT  JOIN comanda     cst  ON cst.codcomanda     = (c1.codcomanda-c1.codcomanda)' || coalesce(gSuplJoins,'') || '
      WHERE c.tipdoc = 8 AND c.operat = 1 AND c.anulat    = 0 AND il.cant &lt;&gt; 0 '
          || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'C',NULL,NULL,NULL)),'') || '
        AND i.operat = 1 AND i.anulat = 0
        AND c.DataDoc ' || coalesce(sPer,'');

  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect1,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect2,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect3,''), aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmcontrarenda_processlist</obj_name>
  <obj_hashval>948e58539c10733f9653a08dc911da42</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmcontrarenda_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sGolTMP       varchar := 'TRUNCATE TABLE TMP_LST_URMCONTRARENDA';
  sInsTMP       varchar := '';
  sInsert       varchar := '';
  sData1         varchar := 'to_date(''' || coalesce(current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true),'') || ''',''dd.mm.yyyy'')';
  sData2         varchar := 'to_date(''' || coalesce(current_setting('PKG_LIST_ALEGPERIOADA.gDataF', true),'') || ''',''dd.mm.yyyy'')';
  gSuplCols     VARCHAR := 'contract c, contract1 c1, iesiri i, npart p, nmonede mc';
   gUserFields   VARCHAR := '';
  gUserAlias     VARCHAR := '';
  gNullAlias     VARCHAR := '';
  gSuplJoins     VARCHAR := '';
BEGIN
  --Laura 15.09.2021 - sinc Oracle (14.09.2021)
  --Laura 13.09.2021 - sinc Oracle (11.09.2021)
  --Adina 10 septembrie 2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_URMCONTRARENDA.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  sInsTMP := 'INSERT INTO TMP_LST_URMCONTRARENDA (
    CODCONTRACT, CODCONTRACT1,
    CODBONA,
    CODFPN,
    CODAEPN)
  SELECT
    c.codcontract, c1.codcontract1,
    ( SELECT coalesce(I.CodIntr,0)
      FROM Intrari1 I1 INNER JOIN Intrari I on I.CodIntr = I1.CodIntr
      WHERE I.TipFactura = 20 and I.TipDoc = 4 AND I.CODCONTRACT = C.CODCONTRACT AND I1.CodContract1 = C1.CodContract1 LIMIT 1
    ) CODBONA,
    ( SELECT coalesce(I.CodIes, 0)
      FROM Iesiri1 I1 inner join Iesiri I on I.CodIes = I1.CodIes
      WHERE I.TipFactura = 20 and I.TipDoc = 19 AND I.CODCONTRACT = C.CODCONTRACT AND I1.CodContract1 = C1.CodContract1 LIMIT 1
    ) CODFPN,
    ( SELECT coalesce(I.CodIes,0)
      FROM Iesiri1 I1 inner join Iesiri I on I.CodIes = I1.CodIes
      WHERE I.TipFactura = 20 and I.TipDoc = 20 AND I.CODCONTRACT = C.CODCONTRACT AND I1.CodContract1 = C1.CodContract1 LIMIT 1
    ) CODAEPN
  FROM contract c
    INNER JOIN contract1 c1 ON c1.codcontract = c.codcontract
  WHERE
    c.tipdoc = 10 AND c.tipcontract = 3 AND c.operat = 1 AND c.anulat = 0
    AND c.DataStart between ' || coalesce(sData1,'') || ' AND ' || coalesce(sData2,'') ||' OR c.DataStop between ' || coalesce(sData1,'') || ' AND ' || coalesce(sData2,'') ||
   coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'');

  sInsert := 'INSERT INTO ' || tmpName || '(
    NAV_CodDoc, NAV_TipDoc,
    CONTRNR, CONTRDATA, CONTRDATAI, CONTRDATAS, CONTRPart, CONTRMoneda,
    Stopaj, CASS,
    TipLinie,
    ArtContr, UMContr,
    PretContr, PUContr, PretStContr,
    CantContr,
    CantGlobal, CantUnitar,
    CantPlata, ArtPlata, CantEchivPlata,
    BONAPrefixDoc, BONANrDoc, BONADataDoc,
    FPNPrefixDoc , FPNNrDoc,  FPNDataDoc,
    AEPNPrefixDoc, AEPNNrDoc, AEPNDataDoc ' || gUserFields || ')
  SELECT
    c.codcontract NAV_CodDoc, c.tipdoc NAV_TipDoc,
    c.NrDoc CONTRNR, c.Datadoc CONTRDATA, c.DataStart CONTRDATAI, c.DataStop CONTRDATAS, p.den_part CONTRPart, mc.den_moneda CONTRMoneda,
    tstopaj.den_taxa Stopaj, tcass.den_taxa CASS,
    CASE c1.tipobiect
      WHEN 0 THEN ''Scop contract''
      WHEN 1 THEN ''Avans facturat''
      WHEN 2 THEN ''Dobanda avans''
      WHEN 3 THEN ''Asig.baza materiala''
      WHEN 4 THEN ''Garantie materiala''
      WHEN 5 THEN ''Plata in natura''
    END TipLinie,
    obj1.denumire ArtContr, u.den_um1 UMContr,
    Coalesce(C1.Pret * U.Paritate, 0) PretContr, Coalesce(C1.Pret * U.Paritate * (1 + Coalesce(C1.AdDim/ 100,0)), 0) PUContr, Coalesce(C1.PretStandard * U.Paritate, 0) PretStContr,
    Sum(C1.Cant/U.Paritate) OVER (PARTITION BY tmp.codcontract, c1.indexlocal) CantContr,
    C1.CantGlobal, Sum(CASE WHEN Coalesce(C1.Cantglobal,0) &lt;&gt; 0 THEN C1.Cant/C1.cantglobal ELSE 0 END) OVER (PARTITION BY tmp.codcontract, c1.indexlocal) CantUnitar,
    C1.Cant/U.Paritate CantPlate, CASE WHEN Coalesce(C1.CodObiectSec,0) = 0 THEN ''...Plata numerar...'' ELSE obj2.denumire END ArtPlata, c1.LimitaCadouSec CantEchivPlata,
    bona.prefixdoc BONAPrefixDoc, bona.nrdoc BONANrDoc, bona.datadoc BONADataDoc,
    fpn.prefixdoc  FPNPrefixDoc , fpn.nrdoc  FPNNrDoc,  fpn.datadoc  FPNDataDoc,
    aepn.prefixdoc AEPNPrefixDoc, aepn.nrdoc AEPNNrDoc, aepn.datadoc AEPNDataDoc ' || gUserAlias || '
  FROM TMP_LST_URMCONTRARENDA tmp
    LEFT JOIN contract  c       ON c.codcontract   = tmp.codcontract
    LEFT JOIN contract1 c1      ON c1.codcontract1 = tmp.codcontract1
    LEFT JOIN ntaxe     tstopaj ON tstopaj.codtaxa = c.Stopaj
    LEFT JOIN ntaxe     tcass   ON tcass.codtaxa   = c.CASS
    LEFT JOIN nartobj   obj1    ON obj1.codobiect  = c1.codobiect
    LEFT JOIN nartobj   obj2    ON obj2.codobiect  = c1.codobiectsec
    LEFT JOIN num1      u       ON u.codum1        = c1.umsec
    LEFT JOIN intrari   bona    ON bona.codintr    = tmp.codbona
    LEFT JOIN iesiri    fpn     ON fpn.codies      = tmp.codfpn
    LEFT JOIN iesiri    aepn    ON aepn.codies     = tmp.codaepn
    LEFT JOIN npart     p       ON p.codpart       = c.partener
    LEFT JOIN nmonede   mc      ON mc.codmoneda    = c.moneda' || gSuplJoins;

  PERFORM LIST_EXECUTE_IMMEDIATE(sGolTMP, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsTMP, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmcontrcom_processlist</obj_name>
  <obj_hashval>100ac9d0090dc867fd3484ec2549fb15</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmcontrcom_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  gUserFields  VARCHAR := '';
  gUserAlias   VARCHAR := '';
  gNullAlias   VARCHAR := '';
  gSuplCols    VARCHAR := '';
  gSuplJoins   VARCHAR := '';

  sInsert      varchar;
  sSelect1     varchar;
  sSelect2     varchar;
  sData1       varchar := 'to_date(''' || coalesce (To_Char((SELECT PKG_LIST_ALEGPERIOADA_getDataS.WME_RESULT FROM PKG_LIST_ALEGPERIOADA_getDataS (NULL,NULL)) ,'dd.mm.yyyy') ,'') || ''',''dd.mm.yyyy'')';
  sData2       varchar := 'to_date(''' || coalesce (To_Char((SELECT PKG_LIST_ALEGPERIOADA_getDataF.WME_RESULT FROM PKG_LIST_ALEGPERIOADA_getDataF (NULL,NULL)) ,'dd.mm.yyyy') ,'') || ''',''dd.mm.yyyy'')';
  sTabla       varchar := 'iesiri';
  sTabla1      varchar := 'iesiri1';
  sCodDoc      varchar := 'codies';
  sTipDoc      varchar := '27';
  sAuxWhere    varchar;
  vAnLunaLucru numeric;
BEGIN
  --Adina 28.04.2021 - alstart,alstop
  --Bogdan 07.09.2020
  vAnLunaLucru := getAnLunaLucru();

  IF aLISTID = 305 THEN
    sTabla  := 'intrari';
    sTabla1 := 'intrari1';
    sCodDoc := 'codintr';
    sTipDoc := '10';
  END IF;

  gSuplCols := 'contract c, contract1 c1, contract2 c2, notecredit nc, notecreditfact ncf, '||sTabla||' i, '||sTabla1||' i1, npart p, nartobj o, num1 um, ncont ncont, nclasep clsp, npers agent, nartobj1 objluna';

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs (gSuplCols , 'NARTOBJEXT', 'OEXT'   , 'OEXT.CODOBIECT    = O.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs (gSuplCols , 'NARTOBJATR', 'OATR'   , 'OATR.CODOBIECT    = O.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs (gSuplCols , 'NARTOBJ1'  , 'OBJLUNA', 'OBJLUNA.CODOBIECT = O.CODOBIECT',NULL);

  CALL pkg_list_struct_getsuplcols( aLISTID, aLISTVER, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config ('PKG_LIST_BASE_URMCONTRCOM.gSuplCols',gSuplCols,false);

  IF InStr (gSuplJoins , ' OBJLUNA ') &gt; 0 THEN
    CALL PRC_AL_CHECK('nartobj1',0);

    sAuxWhere := '
        AND ' || coalesce (vAnLunaLucru::varchar,'') || ' BETWEEN objluna.ALStart and objluna.ALStop ';
  END IF;

  sInsert := 'INSERT INTO ' || tmpName || '(
                NAV_CodDoc,NAV_TipDoc, CONTRNR, CONTRDATA, CONTRDATAI, CONTRDATAS, NCDATAI, NCDATAS,
                PrefixDoc, NrDoc, DataDoc, Part, Art, Cont,
                UM, Cant,
                Pret, PU, PD,
                VAL, VALTVA,
                PROCTVA, CONTRTIP ' || coalesce (gUserFields ,'') || ')';

  sSelect1 := '
      SELECT c.codcontract,
        c.tipdoc,
        c.NrDoc,
        c.Datadoc,
        c.DataStart,
        c.DataStop,
        nc.datastart,
        nc.datastop,
        i.prefixdoc,
        i.nrdoc,
        i.datadoc,
        p.den_part,
        o.denumire,
        ncont.simbol,
        CASE WHEN i1.tiplinie IN (''T'',''G'') THEN ''%'' ELSE um.den_um1 END UM,
        i1.cant     / coalesce (um.paritate,1) Cant,
        i1.pretorig * um.paritate         Pret,
        i1.pu       * um.paritate         PU,
        i1.pretorig * um.paritate * (case i1.coefdiscmaj
                                       when 0 then 1
                                       when NULL then 1
                                       else i1.coefdiscmaj end) PD,
        CASE WHEN i1.tiplinie IN (''T'',''G'') THEN i1.restfact ELSE i1.cant  * i1.pu END  VAL,
        i1.tva VALTVA,
        CASE
          WHEN coalesce (i1.tva,0) = 0  THEN 0
          WHEN i.tipdoc IN (16,21) AND i1.pu  * i1.cant = coalesce (i1.tva,0) THEN 0
          WHEN i.tipdoc IN (16,21) THEN coalesce (i1.tva,0) /  (case when  (i1.pu * i1.cant - coalesce (i1.tva,0)) = 0 then 1
                                                                     else (i1.pu * i1.cant - coalesce (i1.tva,0)) end)
          WHEN i1.pu * i1.cant = 0 THEN 0
          ELSE coalesce (i1.tva,0) /  ( case when (i1.pu * i1.cant) = 0 THEN 1 else (i1.pu * i1.cant) end)
        END * 100 PROCTVA,
        CASE
          WHEN (select count(*) from contract cop where cop.codgeneric = c.codcontract) &gt; 0 THEN ''CADRU''
          WHEN case when coalesce (c.codgeneric,0) &gt; 0 then 1 else 0 end &gt; 0                THEN ''SUBCONTRACT''
          ELSE ''NORMAL''
        END ' || coalesce (gUserAlias ,'') || '
      FROM contract                               c
        LEFT JOIN contract1                         c1    ON c1.codcontract = c.codcontract - c.codcontract
        INNER JOIN contract2                        c2    ON c2.codcontract = c.codcontract
        INNER JOIN notecredit                       nc    ON nc.codncredit  = c2.coddoc AND nc.tipdoc = c2.tipdoc
        INNER JOIN notecreditfact                   ncf   ON ncf.codncredit = nc.codncredit
        INNER JOIN ' || coalesce (sTabla ,'') || '  i     ON i.'  || coalesce (sCodDoc::varchar ,'') || ' = ncf.coddoc AND i.tipdoc = ncf.tipdoc
        INNER JOIN ' || coalesce (sTabla1,'') || '  i1    ON i1.' || coalesce (sCodDoc::varchar ,'') || ' = i.' || coalesce (sCodDoc::varchar ,'') || '
        LEFT  JOIN npart                            p     ON p.codpart      = i.partener
        LEFT  JOIN nclasep                          clsp  on p.codclasa     = clsp.codclasep
        LEFT  JOIN npers                            agent on agent.codpers  = c.agent
        LEFT  JOIN nartobj                          o     ON o.codobiect    = i1.codobiect
        LEFT  JOIN num1                             um    ON um.codum1      = i1.umsec
        LEFT  JOIN ncont                                  ON ncont.codcont  = Coalesce (i1.contserv,i1.contdiscount,0) '
        || coalesce (gSuplJoins ,'') || '
      WHERE
        c.tipdoc = ' || coalesce (sTipDoc,'') || '
        AND c.operat = 1
        AND c.anulat = 0 '
        || coalesce ( (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT (NULL,'C',NULL,NULL,NULL)) ,'') || '
        AND i.DataDoc BETWEEN ' || coalesce (sData1 ,'') || ' AND ' || coalesce (sData2 ,'')
        || coalesce (sAuxWhere,'');

  sSelect2 := '
      SELECT distinct c.codcontract,
        c.tipdoc,
        c.NrDoc,
        c.Datadoc,
        c.DataStart,
        c.DataStop,
        null::date,
        null::date,
        i.prefixdoc,
        i.nrdoc,
        i.datadoc,
        p.den_part,
        o.denumire,
        ncont.simbol,
        um.den_um1                                                                                   UM,
        c1.cant / coalesce (um.paritate,1)                                                           CANT,
        c1.pret * um.paritate                                                                        Pret,
        c1.pret * Coalesce (1 + c1.addim / 100,1) * um.paritate                                      PU,
        c1.pret * Coalesce (1 + c1.addim / 100,1) * Coalesce (1 + c1.procdisc / 100,1) * um.paritate PD,
        C1.cant * C1.pret                                                                            VAL,
        NULL::numeric                                                                                VALTVA,
        NULL::numeric                                                                                PROCTVA,
        CASE
          WHEN (select count(*) from contract cop where cop.codgeneric = c.codcontract) &gt; 0 THEN ''CADRU''
          WHEN case when coalesce (c.codgeneric,0) &gt; 0 then 1 else 0 end &gt; 0                THEN ''SUBCONTRACT''
          ELSE ''NORMAL''
        END '
        || coalesce (gUserAlias ,'') || '
      FROM contract                               c
        LEFT JOIN contract1                       c1    ON c1.codcontract = c.codcontract
        LEFT JOIN contract2                       c2    ON c2.codcontract = c.codcontract
        LEFT JOIN notecredit                      nc    ON nc.codncredit  = c2.coddoc AND nc.tipdoc = c2.tipdoc
        LEFT JOIN notecreditfact                  ncf   ON ncf.codncredit = nc.codncredit
        LEFT JOIN ' || coalesce (sTabla ,'') || ' i     ON i.'  || coalesce (sCodDoc::varchar ,'') || ' = ncf.coddoc AND i.tipdoc = ncf.tipdoc AND i.DataDoc BETWEEN ' || coalesce (sData1 ,'') || ' AND ' || coalesce (sData2 ,'') || '
        LEFT JOIN ' || coalesce (sTabla1,'') || ' i1    ON i1.' || coalesce (sCodDoc::varchar ,'') || ' = i.' || coalesce (sCodDoc::varchar ,'') || '
        LEFT JOIN npart                           p     ON p.codpart      = c.partener
        LEFT JOIN nclasep                         clsp  on p.codclasa     = clsp.codclasep
        LEFT JOIN npers                           agent on agent.codpers  = c.agent
        LEFT JOIN nartobj                         o     ON o.codobiect    = c1.codobiect
        LEFT JOIN num1                            um    ON um.codum1      = c1.umsec
        LEFT JOIN ncont                                 ON ncont.codcont  = Coalesce (i1.contserv,i1.contdiscount,0) '
        || coalesce (gSuplJoins,'') || '
      WHERE
        c.tipdoc = ' || coalesce (sTipDoc,'') || '
        AND c.operat = 1
        AND c.anulat = 0 '
        || coalesce ( (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT (NULL,'C',NULL,NULL,NULL)) ,'') || '
        AND i.' || coalesce (sCodDoc::varchar ,'') || ' IS NULL
        AND c.DataStop &gt;= ' || coalesce (sData1 ,'') || '
        AND c.DataStart &lt;= ' || coalesce (sData2 ,'')
        || coalesce (sAuxWhere,'');

  PERFORM LIST_EXECUTE_IMMEDIATE (coalesce (sInsert,'')|| coalesce (sSelect1,'') , aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE (coalesce (sInsert,'')|| coalesce (sSelect2,'') , aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmplatidoc_processlist</obj_name>
  <obj_hashval>e4dd4c9884716c57f5c11bb2055c2143</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmplatidoc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
VREC RECORD;
  sInsert       varchar := '';
  sSelect       varchar := '';
  aSitV         numeric;
  aBancaV       numeric;
  aMonedaV       numeric;
  sCursRef       varchar := '';
  vCursRef       numeric;
  vSitVal       BOOLEAN;
  gSuplCols     VARCHAR := 'nmonede mon, nsubunit sub';
   gUserFields   VARCHAR := '';
  gUserAlias     VARCHAR := '';
  gNullAlias     VARCHAR := '';
  gSuplJoins     VARCHAR := '';
BEGIN
  --Florin 13.01.2023 - sinc. Oracle
  --Florin 11.01.2023 - fixat 56770
  --Adina 08 septembrie 2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_URMPLATIDOC.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  --vSitVal := (SELECT WME_RESULT FROM pkg_list_base_utils_GetInfoSitValuta(NULL,aSitV, aBancaV, aMonedaV));
  SELECT WME_RESULT, psitvaluta, pbancavaluta, pmonedavaluta
  INTO vSitVal, aSitV, aBancaV, aMonedaV
  FROM pkg_list_base_utils_GetInfoSitValuta(NULL,aSitV, aBancaV, aMonedaV);

  sInsert :=
  'INSERT INTO ' || tmpName || ' (NAV_CodDoc, NAV_CodDoc1, NAV_TipDoc, PREFIXDOC, DATADOC, NRDOC, TERMEN, MONEDA, MAJORARE, OBLIG, PLATA, SOLD, OBS, ORDINE, CURS_REF ' || gUserFields || ' )';

  IF vSitVal THEN
    sCursRef := '(Select wme_result From PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null,' || coalesce(aMonedaV::varchar,'') || ',' || coalesce(aBancaV::varchar,'') || ', to_char(I.DATADOC,''dd.mm.yyyy'')) )';
  ELSE
    sCursRef := ' 1 ';
  END IF;

  sSelect := '
  SELECT G.CodDoc, NULL CodDoc1, G.TipDoc , I.Prefixdoc , I.Datadoc, I.Nrdoc, O.Termen, MON.Simbol, 0 Majorare, O.Valoare, 0 Plata, O.Valoare, I.Obs, 0 Ordine,' || coalesce(sCursRef,'') || gUserAlias || '
  FROM INTRARI I
    INNER JOIN GENERAL  G   ON G.CODDOC       = I.CODINTR AND G.TIPDOC = I.TIPDOC
    INNER JOIN OBLIGPIF O   ON O.CODGENERAL   = G.CODGENERAL
    LEFT  JOIN NMONEDE  MON ON MON.CODMONEDA    = I.Moneda
    LEFT  JOIN NSUBUNIT SUB ON SUB.CODSUBUNIT = I.SUBUNITATEA' || gSuplJoins || '
  WHERE I.PARTENER = PKG_LIST_SELURMDOCPART_CODPART()
    AND I.NRDOC = PKG_LIST_SELURMDOCPART_NRDOC()
    AND I.DATADOC = PKG_LIST_SELURMDOCPART_DATADOC()
    AND O.SEMNIFICATIE IN (100,130)';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);

  IF vSitVal THEN
    sCursRef := '(Select wme_result From PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null,' || coalesce(aMonedaV::varchar,'') || ',' || coalesce(aBancaV::varchar,'') || ', to_char(COALESCE(C.DATADOC,T1.DATADOC,NC.DATADOC,I.DATADOC),''dd.mm.yyyy'')) )';
  ELSE
    sCursRef := ' 1 ';
  END IF;

  sSelect := '
  SELECT
    CASE WHEN TS.CODSUBUNIT IS NULL THEN NULL WHEN G.TipDoc IN (29,30,31,33) THEN T.CODTREZOR ELSE G.CODDOC END NAV_CodDoc,
    CASE WHEN TS.CODSUBUNIT IS NULL THEN NULL WHEN G.TipDoc IN (29,30,31,33) THEN T1.CODTREZOR1 ELSE NULL END NAV_CodDoc,
    CASE WHEN TS.CODSUBUNIT IS NULL THEN NULL ELSE G.TipDoc END NAV_TipDoc,
    CASE WHEN G.TipDoc = 28 THEN ''PV'' WHEN G.TipDoc IN (29,30,31,33) THEN T1.DOC WHEN G.TipDoc = 35 THEN ''NC'' ELSE I.PREFIXDOC END PREFIXDOC,
    CASE WHEN G.TipDoc = 28 THEN C.DATADOC WHEN G.TipDoc IN (29,30,31,33) THEN T1.DATADOC WHEN G.TipDoc = 35 THEN NC.DATADOC ELSE I.DATADOC END DATADOC,
    CASE WHEN G.TipDoc = 28 THEN C.NRDOC WHEN G.TipDoc IN (29,30,31,33) THEN T1.NRDOC WHEN G.TipDoc = 35 THEN NC.NRDOC ELSE I.NRDOC END NRDOC,
    O.TERMEN, MON.SIMBOL, O.MAJORARI, 0,
    CASE WHEN G.SEMNIFICATIE IN (320,1350) THEN - O.VALOARE ELSE O.VALOARE END VALOARE,
    CASE WHEN G.SEMNIFICATIE IN (320,1350) THEN O.VALOARE ELSE - O.VALOARE END SOLD,
    CASE WHEN G.TipDoc = 28 AND G.SEMNIFICATIE IN (1300) THEN C.OBSD WHEN G.TipDoc = 28 AND G.SEMNIFICATIE IN (1350) THEN C.OBSC WHEN G.TipDoc IN (29,30,31,33) THEN T1.OBS WHEN G.TipDoc = 35 THEN NC.OBS ELSE I.OBS END OBS,
    1 ORDINE,' || coalesce(sCursRef,'') || gUserAlias || '
  FROM STINGERE S
    INNER JOIN OBLIGPIF            O   ON O.CODOBLIGPIF  = S.CODSTINGATORPIF
    INNER JOIN GENERAL             G   ON G.CODGENERAL   = O.CODGENERAL
    LEFT  JOIN INTRARI             I   ON I.CODINTR      = G.CODDOC AND I.TIPDOC = G.CODDOC
    LEFT  JOIN COMPENS             C   ON C.CODCOMPENS   = G.CODDOC AND G.TIPDOC = 28
    LEFT  JOIN TREZOR1             T1  ON T1.CODTREZOR1  = G.CODDOC AND G.TIPDOC IN (29,30,31,33)
    LEFT  JOIN TREZOR              T   ON T1.CODTREZOR   = T.CODTREZOR
    LEFT  JOIN NC                      ON NC.CODNC       = G.CODDOC AND G.CODDOC = 35
    LEFT  JOIN NMONEDE             MON ON MON.CODMONEDA  = G.MONEDA
    LEFT  JOIN tmp_subunitdedicate ts  ON ts.codsubunit  = COALESCE(NC.SUBUNITATEA, T.SUBUNITATEA, C.SUBUNITATEA, I.SUBUNITATEA)
    LEFT  JOIN nsubunit            sub ON sub.codsubunit = COALESCE(NC.SUBUNITATEA, T.SUBUNITATEA, C.SUBUNITATEA, I.SUBUNITATEA)' || gSuplJoins || '
  WHERE s.codstinspif = $1';

  FOR vRec IN (
      SELECT O.Codobligpif
      FROM   INTRARI I
            INNER JOIN GENERAL  G ON  G.CODDOC     = I.CODINTR AND  G.TIPDOC = I.TIPDOC
            INNER JOIN OBLIGPIF O ON  O.CODGENERAL = G.CODGENERAL
      WHERE I.PARTENER     = PKG_LIST_SELURMDOCPART_CODPART()
            AND  I.NRDOC   = PKG_LIST_SELURMDOCPART_NRDOC()
            AND  I.DATADOC = PKG_LIST_SELURMDOCPART_DATADOC()
            AND O.SEMNIFICATIE IN (100, 130)
              )
  LOOP
    EXECUTE sInsert || sSelect  USING vRec.CodObligPif ;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_dropj130</obj_name>
  <obj_hashval>40a227b65a96b0e716b47d481e55162b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_dropj130()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR v_rec IN (SELECT distinct TABLE_NAME FROM information_schema.COLUMNS WHERE table_schema = getfirmaname() and TABLE_NAME LIKE 'j130_%')
  LOOP
    EXECUTE 'Drop table ' || coalesce(v_rec.TABLE_NAME,'');
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getcodartcli</obj_name>
  <obj_hashval>2f5d2949a45458864da11311270d1043</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getcodartcli(INOUT wme_result numeric, INOUT pcodobiect numeric, INOUT pcodpart numeric, INOUT pcodclasep numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Stef 03.08.2022
  WME_Result :=  pkg_list_base_utils_getcodartcli(pcodobiect, pcodpart, pcodclasep);
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getoldcod_iopart1</obj_name>
  <obj_hashval>cf34815c58d413968a0b052ff7083a7c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getoldcod_iopart1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_UTILS.oldCod_IOPART1', true),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getpartdoc</obj_name>
  <obj_hashval>a8c323b71f5178044ca8ce5ed195e911</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getpartdoc(INOUT wme_result numeric, INOUT acoddoc numeric, INOUT atipdoc numeric, INOUT acoddoc1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vResult varchar := '';
begin
  IF  Coalesce( aCodDoc, 0) = 37 THEN
    vResult := '';
  ELSIF Coalesce( aCodDoc, 0) = 52 THEN
    vResult := '';
  END IF;
  WME_Result :=  vResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_match_tva</obj_name>
  <obj_hashval>72b734ecc45267c992a2db2fe0d224cb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_match_tva(INOUT wme_result numeric, INOUT p_pjtva numeric, INOUT p_anluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCazTva  numeric;
  vProcTVA numeric;
BEGIN
  --Florin 21.09.2020
  SELECT out_caztva FROM pkg_list_base_utils_MATCH_TVA_COMBI(p_PJTVA, p_AnLuna, vCazTva, vProcTVA) INTO vCazTva;
  WME_Result :=  vCazTva;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_match_tva_proc</obj_name>
  <obj_hashval>bd265d1ab2e2a619ca7572bd35ad9740</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_match_tva_proc(p_pjtva numeric, p_anluna numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCazTva  numeric;
  vProcTVA numeric;
BEGIN
  --Bogdan 20.11.2020
  SELECT out_proctva FROM pkg_list_base_utils_MATCH_TVA_COMBI( p_PJTVA, p_AnLuna, vCazTva, vProcTVA) INTO vProcTVA;
  RETURN vProcTVA;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvsdd_coddoc</obj_name>
  <obj_hashval>8e52fb64cc5640c0147c5ecc07c1e803</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvsdd_coddoc(avsdd_coddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vSDD_CodDoc',to_char(avSDD_CodDoc,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_setvsdd_dendoc</obj_name>
  <obj_hashval>95aec511f940b3706ed25318eb0bb368</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_setvsdd_dendoc(avsdd_dendoc character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_UTILS.vSDD_DenDoc',avSDD_DenDoc,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_verif_imp_ies_setjoinuri</obj_name>
  <obj_hashval>92031b8c864309849ed7577da321fe58</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_verif_imp_ies_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 05.08.2020
  PERFORM pkg_list_struct_SetTableSpec( (current_setting('PKG_LIST_BASE_VERIF_IMP_IES.gSuplCols', true)));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_config_get_col_type</obj_name>
  <obj_hashval>20317fbd9b8c77cb5501a15c7383e57f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_config_get_col_type(INOUT wme_result character varying, INOUT scol character varying, INOUT stab character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  sType varchar;
begin
  select DATA_TYPE into  sType from information_schema.columns where TABLE_NAME = lower(sTab) and COLUMN_NAME = lower(sCol);
  WME_Result := sType;
  return;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_config_get_sid_footer</obj_name>
  <obj_hashval>a75bf4bd2d407781691131af4d243a05</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_config_get_sid_footer()
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
begin
  return '999999999';
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selcomenzi_perioada</obj_name>
  <obj_hashval>7e28f7653b140d2e7d7a9032e7f5e87c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selcomenzi_perioada()
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 01.09.2020

  return current_setting('PKG_LIST_SELCOMENZI.vPerioada', true);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selcont_getcuobs</obj_name>
  <obj_hashval>4e8c90e62bf909a0c6679f5d1524b27d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selcont_getcuobs()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Stef 19.03.2024
  RETURN current_setting('PKG_LIST_SELCONT.gCuObs', true)::boolean;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selcont_getlunastart</obj_name>
  <obj_hashval>7fcebb44c2c26b050939c756b171c940</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selcont_getlunastart()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 03.08.2020
  return current_setting('PKG_LIST_SELCONT.gLunaS', true)::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selcont_getlunastop</obj_name>
  <obj_hashval>aef881d1ee6923085f9a1a231cba3cef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selcont_getlunastop()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 03.08.2020
  return current_setting('PKG_LIST_SELCONT.gLunaF', true)::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscadentar_valsapt</obj_name>
  <obj_hashval>b5e134ed718eab84a93eddf607a24fb6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscadentar_valsapt()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.09.2020
  return current_setting ('PKG_LIST_SELECTSCADENTAR.g_ValSapt', true)::boolean;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_setp_stoclazi</obj_name>
  <obj_hashval>fbccc3ecdfe1e2c834e5284e28ce2d01</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_setp_stoclazi(ap_stoclazi boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_SELFISAMAG.p_StoclaZi',ap_StoclaZi,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selmoment_setallparams</obj_name>
  <obj_hashval>401db78a271eda26c00d9c78c03497d4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selmoment_setallparams(ptip numeric, pdataref character varying, pextra1 boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 05.08.2020
  --Florin 07.04.2021 - fixat 46802
  perform set_config('PKG_LIST_SELMOMENT.vTip'    , COALESCE(pTip, 0)::varchar,false);
  perform set_config('PKG_LIST_SELMOMENT.vDataRef', pDataRef         ::varchar,false);
  perform set_config('PKG_LIST_SELMOMENT.vExtra1' , pExtra1          ::varchar, false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_goleste_param</obj_name>
  <obj_hashval>239406af3d7af99324dd2fca19ef9f81</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_goleste_param()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 31.07.2020
  DELETE FROM TMP_LIST_PARAMS;
  perform set_config('PKG_LIST_STRUCT.v_IdxParamLista',0::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_split_column</obj_name>
  <obj_hashval>ffcc4432c42f9cb2c8177be1d6034481</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_split_column(tbl_name character varying, col_name character varying, sep character varying, tmp_name character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  s     varchar;
  val   varchar;
  idx   numeric := 1;
BEGIN
  EXECUTE 'DELETE FROM ' || tmp_name;
  EXECUTE 'INSERT INTO ' || tmp_name || '(SIMBOL) SELECT DISTINCT ' || col_name || ' FROM ' || tbl_name;
  FOR v_rec IN (SELECT simbol FROM tmp_level1)
  LOOP
    s := v_rec.simbol || sep;
    idx := 1;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_utilfisacont_getpartjurnal</obj_name>
  <obj_hashval>b59dd5b34d3ab3a568e9ee45fd8af7cf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_utilfisacont_getpartjurnal(acodjurnal numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  Rez NUMERIC(20);
BEGIN
  --Florin 10.05.2023 - sinc. Oracle (09.05.2023)
  --Florin 13.05.2022
  begin
    select
      case
        when j.tipdoc in (1,2,3,4,5,6,7,9) then (SELECT i.partener FROM intrari i WHERE i.codintr = j.coddoc)
        when j.tipdoc in (14,15,16,19,20,23,24,26) then (SELECT i.partener FROM iesiri i WHERE i.codies = j.coddoc)
        when j.tipdoc in (25) then (SELECT c.partener FROM contract c WHERE c.codcontract = j.coddoc)
        when j.tipdoc in (29,30,31,33) then (SELECT t1.codpart
                                             FROM trezor1 t1
                                               INNER JOIN trezor t on t.codtrezor = t1.codtrezor
                                               LEFT JOIN general g on g.coddoc = t1.codtrezor1 AND g.tipdoc = t.codtrezor
                                             WHERE t1.codtrezor = j.coddoc and t1.codtrezor1 = j.indexlocal and t1.obiecttranz in (0,1))
        when j.tipdoc in (35) then (SELECT nc1.codpart
                                    FROM nc1
                                         INNER JOIN nc on nc.codnc = nc1.codnc
                                    WHERE nc.codnc = j.coddoc AND j.indexlocal = nc1.codnc1)
       when j.tipdoc in (28) then (SELECT distinct(case when coalesce(c.partd,0) = 0 then c.partc else coalesce(c.partd,0) end)
                                   FROM compens c
                                   WHERE c.codcompens = j.coddoc)
       when j.tipdoc in (46) then (select o.codpart
                                   FROM reg r
                                        inner join reg1 r1 on r.codreg = r1.codreg
                                        inner join obligpif o on o.codobligpif = r1.codobligpif
                                   WHERE r.codreg = j.coddoc and r1.codreg1 = j.indexlocal)
      end
    into Rez
    from jurnal j
    where j.codjurnal = aCodJurnal;
  exception when others then Rez := null;
  end;
  return Rez;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_locmunca_sp_lockrecord</obj_name>
  <obj_hashval>0b94c3bcff373bd1e31bbd5245f028af</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_locmunca_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodLoc INTO Tmp FROM LOCMUNCA WHERE CodLoc = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mifix_inconservare</obj_name>
  <obj_hashval>553d6422ec5f1d565b556f38101dc4ea</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mifix_inconservare(acodmifix1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  UPDATE mifix1  SET stare = 2 WHERE codmifix1 = acodmifix1;
  UPDATE jurnal1 SET dirty = 1 WHERE coddoc = (SELECT codmifix FROM mifix1 WHERE codmifix1 = aCodMifix1) and  tipdoc = 36;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_getdocommit</obj_name>
  <obj_hashval>8fdf48d51590e48db50799a98a47e39d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_getdocommit(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_MISCARI_INTERNE.DoCommit'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := true;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_getnrdoc_i</obj_name>
  <obj_hashval>d698e58b0fa2f0f167ae9088e1b10785</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_getnrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_MISCARI_INTERNE.NRDOC_I', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_sp_insertrecord</obj_name>
  <obj_hashval>a25a891972278ac2173687a80bfd3e28</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 12.04.2023 - sinc. Oracle (11.04.2023)
  PERFORM PKG_CFGTABLES_CHECK_STRUCT_EXTENSIE_X_TIPDOC((SELECT wme_result FROM PKG_GLOBALS_GetTipMiscareInterna(NULL, NULL)));
  INSERT INTO TMP_TRANSF (CODTRANSF) VALUES(0);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD((SELECT wme_result FROM PKG_GLOBALS_GetTipMiscareInterna(NULL, NULL)));
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_sp_lockrecord</obj_name>
  <obj_hashval>54f6296eaeed18bb4213284047f1f64c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMP numeric;
begin
  SELECT CODTRANSF INTO TMP FROM TRANSF WHERE CODTRANSF = RECID FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_updatecodalt</obj_name>
  <obj_hashval>6e2421e47979bc71d50aa6718398f716</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_updatecodalt(acodobiect numeric, acodalt character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric;
begin
  SELECT COUNT(*) INTO NR FROM CODEXTALT WHERE CODOBIECT = aCODOBIECT AND  CODEXTERN = aCODALT;
  IF  NR = 0 THEN
    INSERT INTO CODEXTALT(COD, CODOBIECT, CODEXTERN)
    VALUES(NEXTVAL('SEQ_CODEXTALT_COD'), aCODOBIECT, aCODALT);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomautorizatiiauto_sp_lockrecord</obj_name>
  <obj_hashval>8b89329246457da184d53d357b55cfe9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomautorizatiiauto_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT codautorizatii INTO Tmp FROM nautorizatiiauto WHERE codautorizatii = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomcasemarcat_test_unicitate_numar</obj_name>
  <obj_hashval>b2a46e184fee4d55262a5d1eca16c990</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomcasemarcat_test_unicitate_numar(INOUT wme_result numeric, INOUT nrlogic numeric, INOUT cod numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  Nr numeric;
begin
  SELECT COUNT( *) INTO Nr FROM NCASEMARCAT WHERE Numar = NrLogic AND  CodCaseMarcat &lt;&gt; Cod;

  WME_Result :=  Nr;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgest_getcodcaractluna</obj_name>
  <obj_hashval>0fa86961ceb49960eb165b69aec44956</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgest_getcodcaractluna(INOUT wme_result numeric, INOUT acodgest numeric, INOUT an numeric, INOUT luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODGEST1 numeric := 0;
begin
  --Florin 05.01.2022 - sinc. Oracle (29.12.2021)
  BEGIN
    SELECT CODGEST1
    INTO aCODGEST1
    FROM NGEST1 i1
      WHERE i1.CODGEST = aCODGEST AND An * 12 + Luna BETWEEN i1.alstart AND i1.alstop;
  EXCEPTION WHEN OTHERS THEN
    aCodGEST1 := 0;
  END;

  WME_Result :=  aCodGEST1;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgest_getct_monitor</obj_name>
  <obj_hashval>c5c2ec806b81cddcbae4cf1581a775ed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgest_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_NOMGEST.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_2';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgest_sp_postrecords</obj_name>
  <obj_hashval>5ca2adb4a37938f0d6155e7f36aa9fe9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgest_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  vRecNo NUMERIC := 0;
  vAn    NUMERIC := 0;
  vLuna  NUMERIC := 0;
  vCod   numeric;
  NR     numeric := 0;
  aDoc   varchar;
BEGIN
  --Florin 01.06.2023 - monitor
  --Florin 12.04.2023 - sinc. Oracle
  --Laura 10.12.2021 - sinc. Oracle (10.12.2021)
  --Adina 11.03.2021 - add prc_al_refresh
  --Adina 04.02.2021 - sinc.Oracle cu modif. din 04.02.2021 (add Coefcheltmat,Coefcheltman)
  --Adina 27.01.2021 - sinc.Oracle cu modif.din 25.01.2021 (add orastart la insert)
  --Bogdan 04.01.2021
  perform pkg_nomgest_setct_monitor('MON_2');
  SELECT 'Gestiune "' || coalesce (DEN_GEST,'') || '"' INTO aDoc FROM TMP_NGEST;
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT (506);
  IF Operation = 0 THEN   -- UPDATE
    -- Master NGEST
    SELECT codgest INTO RecId FROM TMP_NGEST;

    IF (SELECT WME_RESULT
        FROM PKG_USERFIRME_ValidPostLog (NULL,current_setting ('PKG_GLOBALS.USERID', true) ::numeric, current_setting ('PKG_NOMGEST.CT_MONITOR', true))) THEN
      PERFORM pkg_userfirme_postlogcucommit ('NGEST', current_setting ('PKG_GLOBALS.USERNAME', true) , 'M', RECID, current_setting ('PKG_GLOBALS.FIRMANAME', true) , current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric, null, aDoc, null, current_setting ('PKG_GLOBALS.EXE_VERSION', true));
    END IF;

    UPDATE NGEST
    SET
      (
        den_gest, gmaster, simbol, codclasa,
        codactivit, codcont, codcatpret, codgestionar,
        custodie, codsubunit, verdisplivr, verdisplivrtransf,
        verdisplivrsubunit, vernir, vernirtransf, vernirsubunit,
        verEmulare, verFactIes, CODPOSTRETAIL, ANALITICCONT,
        CANTITATE, tip, nrschimburi, oreschimb,
        orastart, Coefcheltmat, Coefcheltman, INACTIV,
        verChitanta, codcaensec, codgesttr, Ziletermen,
        zilelucr, CODANTREPOZIT, capprod, carnetcmdint,
        carnetbc, carnetnp, carnetrp, Obs
      )
      = (SELECT den_gest, gmaster, simbol, codclasa,
          codactivit, codcont, codcatpret, codgestionar,
          custodie, codsubunit, verdisplivr, verdisplivrtransf,
          verdisplivrsubunit, vernir, vernirtransf, vernirsubunit,
          verEmulare, verFactIes, CODPOSTRETAIL, ANALITICCONT,
          CANTITATE, tip, nrschimburi, oreschimb,
          orastart, Coefcheltmat, Coefcheltman, INACTIV,
          verChitanta, codcaensec, codgesttr, ziletermen,
          zilelucr, CODANTREPOZIT, capprod, carnetcmdint,
          carnetbc, carnetnp, carnetrp, Obs
        FROM TMP_NGEST)
    WHERE
      codgest = RecId;

    -- Detail NAGENDA
    DELETE FROM NAGENDA WHERE (codgest = RecId AND codagenda NOT IN (SELECT codagenda FROM TMP_NAGENDA WHERE COALESCE (codagenda, 0) &lt;&gt; 0));

    INSERT INTO NAGENDA (obs, codagenda, tip, codlocalit, sediusocial, telefon, fax, email, sector, strada, nr1, nr2, bloc, scara, etaj, apart,
                         codpostal, km, codbankcont, codpart, codgest, codsubunit, longitudine, latitudine, obs2)
    SELECT obs, NEXTVAL ('SEQ_NAGENDA_CODAGENDA') , tip, codlocalit, sediusocial, telefon, fax, email, sector, strada, nr1, nr2, bloc, scara, etaj, apart,
           codpostal, km, codbankcont, codpart, RecId, codsubunit, longitudine, latitudine, obs2
    FROM TMP_NAGENDA
    WHERE codagenda &lt; 0;

    FOR v_rec IN (SELECT * FROM TMP_NAGENDA WHERE COALESCE (codagenda, -1) &gt; 0 ORDER BY codagenda) LOOP
      SELECT count(*) INTO vRecNo FROM NAGENDA WHERE codagenda = COALESCE (v_rec.codagenda, 0);

      IF (vRecNo = 1) THEN
        UPDATE NAGENDA
        SET
          obs         = v_rec.obs,
          tip         = v_rec.tip,
          codlocalit  = v_rec.codlocalit,
          sediusocial = v_rec.sediusocial,
          telefon     = v_rec.telefon,
          fax         = v_rec.fax,
          email       = v_rec.email,
          sector      = v_rec.sector,
          strada      = v_rec.strada,
          nr1         = v_rec.nr1,
          nr2         = v_rec.nr2,
          bloc        = v_rec.bloc,
          scara       = v_rec.scara,
          etaj        = v_rec.etaj,
          apart       = v_rec.apart,
          codpostal   = v_rec.codpostal,
          km          = v_rec.km,
          codbankcont = v_rec.codbankcont,
          codpart     = v_rec.codpart,
          codgest     = RecId,
          codsubunit  = v_rec.codsubunit,
          longitudine = v_rec.longitudine,
          latitudine  = v_rec.latitudine,
          obs2        = v_rec.obs2
        WHERE
          codagenda = v_rec.codagenda;
      END IF;
    END LOOP;
  -- Detail NGEST1

    DELETE FROM NGEST1 WHERE CODGEST = RECID AND CODGEST1 NOT IN (SELECT CODGEST1 FROM TMP_NGEST1);

    INSERT INTO NGEST1 (CODGEST1, CODGEST, TipGest, Cheltuieli, CheltuieliAux, CheltuieliInd, CheltuieliAdmin, CheltuieliDesf,
                        Venituri, VENITURIK, Suprafata, ANSTART, LUNASTART)
    SELECT NEXTVAL ('SEQ_NGEST1_CODGEST1') , RecId, TipGest, Cheltuieli, CheltuieliAux, CheltuieliInd, CheltuieliAdmin, CheltuieliDesf,
           Venituri, VENITURIK, Suprafata, ANSTART, LUNASTART
    FROM TMP_NGEST1 WHERE CODGEST1 &lt; 0;

    FOR V_REC IN (SELECT * FROM TMP_NGEST1 WHERE COALESCE (CODGEST1, -1) &gt; 0 ORDER BY codGEST1) LOOP
      UPDATE NGEST1
      SET
        TipGest         = v_rec.TipGest,
        Cheltuieli      = v_rec.Cheltuieli,
        CheltuieliAux   = v_rec.CheltuieliAux,
        CheltuieliInd   = v_rec.CheltuieliInd,
        CheltuieliAdmin = v_rec.CheltuieliAdmin,
        CheltuieliDesf  = v_rec.CheltuieliDesf,
        Venituri        = v_rec.Venituri,
        VENITURIK       = v_rec.VENITURIK,
        Suprafata       = v_rec.Suprafata
      WHERE
        CODGEST1 = v_rec.CODGEST1;
    END LOOP;

  ELSE    -- INSERT
-- MASTER NGEST
    SELECT NEXTVAL ('SEQ_NGEST_CODGEST') INTO RECID;
    PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('NGEST', RecId);

    IF (SELECT WME_RESULT
        FROM winmadmin.PKG_USERFIRME_ValidPostLog (NULL,current_setting ('PKG_GLOBALS.USERID', true) ::numeric, current_setting ('PKG_NOMGEST.CT_MONITOR', true))) THEN
      PERFORM winmadmin.pkg_userfirme_postlogcucommit ('NGEST', current_setting ('PKG_GLOBALS.USERNAME', true) , 'A', RECID, current_setting ('PKG_GLOBALS.FIRMANAME', true) , current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric, null, aDoc, null, current_setting ('PKG_GLOBALS.EXE_VERSION', true));
    END IF;

    INSERT INTO NGEST (codgest, den_gest, GMaster, simbol, codclasa, codactivit, codcont, codcatpret, codgestionar, custodie, codsubunit, verdisplivr,
                       verdisplivrtransf, verdisplivrsubunit, vernir, vernirtransf, vernirsubunit, verEmulare, verFactIes, CODPOSTRETAIL,
                       ANALITICCONT, CANTITATE, tip, nrschimburi, oreschimb, INACTIV, verChitanta, codcaensec, codgesttr, ziletermen, zilelucr, CODANTREPOZIT,
                       capprod, carnetcmdint, carnetbc, carnetnp, carnetrp, Orastart,Coefcheltmat,Coefcheltman, Obs)
    SELECT RecId, den_gest, GMaster, simbol, codclasa, codactivit, codcont, codcatpret, codgestionar, custodie, codsubunit, verdisplivr,
           verdisplivrtransf, verdisplivrsubunit, vernir, vernirtransf, vernirsubunit, verEmulare, verFactIes, CODPOSTRETAIL,
           ANALITICCONT, CANTITATE, tip, nrschimburi, oreschimb, INACTIV, verChitanta, codcaensec, codgesttr, ziletermen, zilelucr, CODANTREPOZIT,
           capprod, carnetcmdint, carnetbc, carnetnp, carnetrp, Orastart,Coefcheltmat,Coefcheltman, Obs
    FROM TMP_NGEST;

  -- Detail NAGENDA
    INSERT INTO NAGENDA (obs, codagenda, tip, codlocalit, sediusocial, telefon, fax, email, sector, strada, nr1, nr2, bloc, scara, etaj, apart,
                         codpostal, km, codbankcont, codpart, codgest, codsubunit, longitudine, latitudine, obs2)
    SELECT obs, NEXTVAL ('SEQ_NAGENDA_CODAGENDA') , tip, codlocalit, sediusocial, telefon, fax, email, sector, strada, nr1, nr2, bloc, scara, etaj, apart,
           codpostal, km, codbankcont, codpart, RecId, codsubunit, longitudine, latitudine, obs2
    FROM TMP_NAGENDA;

    -- Detail IOFILIAL1
    INSERT INTO NGEST1 (CODGEST1, CODGEST, TipGest, Cheltuieli, CheltuieliAux, CheltuieliInd, CheltuieliAdmin, CheltuieliDesf,
                        Venituri, VENITURIK, Suprafata, ANSTART, LUNASTART)
    SELECT NEXTVAL ('SEQ_NGEST1_CODGEST1') , RecId, TipGest, Cheltuieli, CheltuieliAux, CheltuieliInd, CheltuieliAdmin, CheltuieliDesf,
           Venituri, VENITURIK, Suprafata, ANSTART, LUNASTART
    FROM TMP_NGEST1;
  END IF;

-- DETAIL NLOCATII
  UPDATE NLOCATII SET CODGEST = 0 WHERE CODGEST = RECID;

  FOR V_REC IN (SELECT * FROM TMP_LOCATIIGEST) LOOP
    IF V_REC.CODLOCATIE &gt; 0 THEN
      UPDATE NLOCATII
      SET CODGEST = RecId
      WHERE
        CODLOCATIE = V_REC.CODLOCATIE;
    END IF;
  END LOOP;

  BEGIN
    SELECT COUNT(*) INTO NR FROM TMP_GESTDEDICATE WHERE CODGEST = RECID;
  EXCEPTION
  WHEN OTHERS THEN
    NR := 0;
  END;

  IF NR = 0 THEN
    INSERT INTO TMP_GESTDEDICATE (CODGEST) VALUES (RECID);
  END IF;

  CALL PRC_AL_REFRESH('ngest1', RECID);
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS(506);
  PERFORM NotifyModif (OPERATION, RECID, 'NGEST');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nommodeleauto_sp_insertrecord</obj_name>
  <obj_hashval>1e28982320f27d43f1f6a96233e310bf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nommodeleauto_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NMODELEAUTO(CodModeleAuto) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_conditieclasa</obj_name>
  <obj_hashval>38c667cf60f09ff9caf8c4296874c733</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_conditieclasa(INOUT wme_result numeric, INOUT aclasa numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  TO_NUMBER((current_setting('PKG_NOMPART.CLASA_PART',true)),'999999999999999999') = 0 THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    IF  aCLASA = TO_NUMBER((current_setting('PKG_NOMPART.CLASA_PART',true)),'999999999999999999') THEN
      WME_Result :=  1;
      RETURN;
    ELSE
      WME_Result :=  0;
      RETURN;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_getpartener_curent</obj_name>
  <obj_hashval>c3b99f94e912ffac9ba7c30176346aa2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_getpartener_curent(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_NOMPART.PARTENER_CURENT')),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_make_obligpart_la_zi</obj_name>
  <obj_hashval>47f28e1c1dbad0583ee9c2a3826da904</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_make_obligpart_la_zi(acodpart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  aPREFIXDOC   varchar := NULL;
  aDATADOC     date := NULL;
  aNRDOC       numeric := NULL;
  aSUBUNITATEA numeric := NULL;
  aAGENT       numeric := NULL;
BEGIN
  --Florin 13.12.2022 - fixat 56526
  PERFORM PKG_NOMPART_SET_PART_CURENT( ACODPART);
  PERFORM PKG_NOMPART_MAKE_CURS_GENERAL_LUNA( TO_CHAR( CURRENT_TIMESTAMP, 'DD.MM.YYYY'));
  perform set_config('PKG_GLOBALS.DATASOLDPART',CURRENT_TIMESTAMP::varchar,false);
  PERFORM PKG_REGPART_MAKE_STINGERI_LA_DATA_PART();
  PERFORM V_OBLIGPART_LA_DATA_PE_PART();
  DELETE FROM TMP_OBLIGPART_LA_DATA;
  INSERT INTO TMP_OBLIGPART_LA_DATA(CODOBLIGPIF, CODGENERAL, CODDOC, VALOARE, REST, ICONT, SEMNIFICATIE, CODPART, CODGEST, CURS, TVA, MONEDA, TIPDOC, TERMEN)
  SELECT RG.CODOBLIGPIF, RG.CODGENERAL, RG.CODDOC, (  VALOARE - ROUND( Coalesce( STINS, 0), 7))  VALOARE, VALOARE - ROUND( Coalesce( STINS, 0), 7) REST, RG.ICONT, RG.SEMNIFICATIE, RG.CODPART, RG.CODGEST, RG.CURS, RG.TVA, RG.MONEDA, RG.TIPDOC, RG.TERMEN
  FROM (SELECT CODOBLIGPIF, CODGENERAL, CODDOC, ICONT, SEMNIFICATIE, CODPART, CODGEST, CURS, TVA, STINS, VALOARE, MONEDA, TIPDOC, TERMEN
        FROM V_OBLIGPART_LA_DATA_PE_PART
       ) RG
  WHERE
     ROUND( Coalesce( VALOARE, 0), 4) - ROUND( Coalesce( STINS, 0), 4) &lt;&gt; 0;

  FOR V_REC IN (SELECT * FROM TMP_OBLIGPART_LA_DATA) LOOP
    aPREFIXDOC   := NULL;
    aDATADOC     := NULL;
    aNRDOC       := NULL;
    aSUBUNITATEA := NULL;

    IF V_REC.SEMNIFICATIE IN (100, 110, 140) THEN
      BEGIN
        SELECT PREFIXDOC, DATADOC, NRDOC, SUBUNITATEA, AGENT
        INTO aPREFIXDOC, aDATADOC, aNRDOC, aSUBUNITATEA, aAGENT
        FROM INTRARI I, GENERAL G
        WHERE G.CODGENERAL = V_REC.CODGENERAL AND  CODINTR = G.CODDOC;
      EXCEPTION WHEN OTHERS THEN
        aPREFIXDOC   := NULL;
        aDATADOC     := NULL;
        aNRDOC       := NULL;
        aSUBUNITATEA := NULL;
        aAGENT       := NULL;
      END;
    ELSE
      IF V_REC.SEMNIFICATIE IN (130) THEN
        BEGIN
          SELECT 'DVI', I.DATADOC, I.NRDOC, INTR.SUBUNITATEA, INTR.AGENT
          INTO aPREFIXDOC, aDATADOC, aNRDOC, aSUBUNITATEA, aAGENT
          FROM DVI I, GENERAL G, INTRARI INTR
          WHERE G.CODGENERAL = V_REC.CODGENERAL AND  CODDVI = G.CODDOC AND  INTR.CODINTR = I.CODINTR;
        EXCEPTION WHEN OTHERS THEN
          aPREFIXDOC   := NULL;
          aDATADOC     := NULL;
          aNRDOC       := NULL;
          aSUBUNITATEA := NULL;
          aAGENT       := NULL;
        END;
      ELSE
        IF V_REC.SEMNIFICATIE IN (200, 210, 240) THEN
          BEGIN
            SELECT PREFIXDOC, DATADOC, NRDOC, SUBUNITATEA, AGENT
            INTO aPREFIXDOC, aDATADOC, aNRDOC, aSUBUNITATEA, aAGENT
            FROM IESIRI I, GENERAL G
            WHERE G.CODGENERAL = V_REC.CODGENERAL AND  CODIES = G.CODDOC;
          EXCEPTION WHEN OTHERS THEN
            aPREFIXDOC := NULL;
            aDATADOC   := NULL;
            aNRDOC     := NULL;
            aAGENT     := NULL;
          END;
        ELSE
          IF V_REC.SEMNIFICATIE IN (310, 410, 330, 430) THEN
            BEGIN
              SELECT SUBSTR( T1.DOC, 1, 2), T1.DATADOC, T1.NRDOC, T.SUBUNITATEA, T1.AGENT
              INTO aPREFIXDOC, aDATADOC, aNRDOC, aSUBUNITATEA, aAGENT
              FROM TREZOR1 T1, GENERAL G, TREZOR T
              WHERE G.CODGENERAL = V_REC.CODGENERAL AND  CODTREZOR1 = G.CODDOC AND  T.CODTREZOR = T1.CODTREZOR;
            EXCEPTION WHEN OTHERS THEN
              aPREFIXDOC   := NULL;
              aDATADOC     := NULL;
              aNRDOC       := NULL;
              aSUBUNITATEA := NULL;
              aAGENT       := NULL;
            END;
          ELSE
            IF V_REC.SEMNIFICATIE IN (1200, 1201) THEN
              BEGIN
                SELECT 'NC', DATADOC, NRDOC, SUBUNITATEA, N1.AGENT
                INTO aPREFIXDOC, aDATADOC, aNRDOC, aSUBUNITATEA, aAGENT
                FROM NC1 N1, GENERAL G, NC N
                WHERE G.CODGENERAL = V_REC.CODGENERAL AND  CODNC1 = G.CODDOC AND  N1.CODNC = N.CODNC;
              EXCEPTION WHEN OTHERS THEN
                aPREFIXDOC   := NULL;
                aDATADOC     := NULL;
                aNRDOC       := NULL;
                aSUBUNITATEA := NULL;
                aAGENT       := NULL;
              END;
            ELSE
              IF  V_REC.SEMNIFICATIE = 1303 THEN
                BEGIN
                  SELECT I.PREFIXDOC, I.DATADOC, I.NRDOC, I.SUBUNITATEA, I.AGENT
                  INTO aPREFIXDOC, aDATADOC, aNRDOC, aSUBUNITATEA, aAGENT
                  FROM OBLIGPIF O
                      LEFT JOIN GENERAL  G  ON  G.CODGENERAL   = O.CODGENERAL
                      LEFT JOIN OBLIGPIF OA ON  OA.CODOBLIGPIF = O.CODOBLIGASOCIAT
                      LEFT JOIN GENERAL  GA ON  GA.CODGENERAL  = OA.CODGENERAL
                      LEFT JOIN IESIRI   I  ON  I.CODIES       = GA.CODDOC
                  WHERE G.CODGENERAL = V_REC.CODGENERAL;
                EXCEPTION WHEN OTHERS THEN
                  aPREFIXDOC := NULL;
                  aDATADOC   := NULL;
                  aNRDOC     := NULL;
                  aAGENT     := NULL;
                END;
              ELSE
                BEGIN
                  SELECT 'PV', DATADOC, NRDOC, SUBUNITATEA, COMPENS.AGENT
                  INTO aPREFIXDOC, aDATADOC, aNRDOC, aSUBUNITATEA, aAGENT
                  FROM COMPENS, GENERAL G
                  WHERE G.CODGENERAL = V_REC.CODGENERAL AND  CODCOMPENS = G.CODDOC;
                EXCEPTION WHEN OTHERS THEN
                  aPREFIXDOC   := NULL;
                  aDATADOC     := NULL;
                  aNRDOC       := NULL;
                  aSUBUNITATEA := NULL;
                  aAGENT       := NULL;
                END;
              END IF;
            END IF;
          END IF;
        END IF;
      END IF;
    END IF;

    UPDATE TMP_OBLIGPART_LA_DATA OB
    SET
    PREFIXDOC   = aPREFIXDOC,
    DATADOC     = aDATADOC,
    NRDOC       = aNRDOC,
    SUBUNITATEA = aSUBUNITATEA,
    CONT        = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, OB.SEMNIFICATIE, OB.ICONT, (SELECT WME_RESULT FROM PKG_NOMPART_GET_PART_COD_CARACT_LUNA(NULL, OB.CODPART, TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU')),'999999999999999999'), TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU')),'999999999999999999'))))),
    CODAGENT    = aAGENT
    WHERE
     CODGENERAL = V_REC.CODGENERAL;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_setct_monitor</obj_name>
  <obj_hashval>3f0195aeea04351241c770aa7f0ce4d4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMPERS.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_gettnccantitate</obj_name>
  <obj_hashval>583e5a61a4052158549d8044945bcdd4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_gettnccantitate(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.tncCantitate', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 3;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_setkartdiscprimter</obj_name>
  <obj_hashval>d475fe5ee16246605b09fd8cdba35a63</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_setkartdiscprimter(akartdiscprimter numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOTECREDIT.KArtDiscPrimTer',aKArtDiscPrimTer::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_tnctermen</obj_name>
  <obj_hashval>dd207c094bbcf4d286379dcf0b4bcc17</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_tnctermen(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.tncTermen', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 1;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_npartretail_sp_insertrecord</obj_name>
  <obj_hashval>15aa32937ab7d4829f6d41ae8a86ca15</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_npartretail_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NPARTRETAIL(CODPARTRETAIL) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_npartretail_sp_postrecords</obj_name>
  <obj_hashval>e865c2f766aef1cc1edb78231600d0ab</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_npartretail_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Florin 18.11.2022 - sinc. Oracle
  --Florin 14.11.2022 - sinc. Oracle
  --Florin 08.11.2022 - sinc. Oracle
  --Bogdan 29.01.2021
  IF Operation = 0 THEN
    SELECT CODPARTRETAIL INTO RecID FROM TMP_NPARTRETAIL;

    UPDATE NPARTRETAIL
    SET
      (
        CODPART, DENUMIRE, REGCOM, OBS,
        CODEXTERN, CODINTERN, TIPPART, COLDISCOUNT,
        CODCLASA, FIDELIZARE, DATANASTERE, BLOCAT,
        INFOBLOCAT, CODCATEGPRET
      )
      = (SELECT CODPART, DENUMIRE, REGCOM, OBS,
          CODEXTERN, CODINTERN, TIPPART, COLDISCOUNT,
          CODCLASA, FIDELIZARE, DATANASTERE, BLOCAT,
          INFOBLOCAT, CODCATEGPRET
         FROM TMP_NPARTRETAIL)
    WHERE
      CODPARTRETAIL = RECID;

    DELETE FROM NSEDIIPARTRETAIL WHERE CODPARTRETAIL = RECID AND CODSEDIU NOT IN (SELECT CODSEDIU FROM TMP_NSEDIIPARTRETAIL);

    FOR V_REC IN (SELECT * FROM TMP_NSEDIIPARTRETAIL) LOOP
      IF V_REC.CODSEDIU &lt; 0 THEN
        INSERT INTO NSEDIIPARTRETAIL (CODSEDIU, CODPARTRETAIL, DENUMIRE, CODLOCALIT, DENLOCALIT, CODJUDET, CODTARA, TELEFON, FAX, EMAIL, STRADA, NR1, NR2, BLOC, SCARA, ETAJ, APART, SECTOR, CODPOSTAL, SEDIUSOCIAL)
        VALUES (NEXTVAL ('SEQ_NSEDIIPARTRETAIL_CODSEDIU') , RECID, V_REC.DENUMIRE, V_REC.CODLOCALIT, V_REC.DENLOCALIT, V_REC.CODJUDET, V_REC.CODTARA, V_REC.TELEFON,
                V_REC.FAX, V_REC.EMAIL, V_REC.STRADA, V_REC.NR1, V_REC.NR2, V_REC.BLOC, V_REC.SCARA, V_REC.ETAJ, V_REC.APART, V_REC.SECTOR, V_REC.CODPOSTAL, V_REC.SEDIUSOCIAL);
      ELSE
        UPDATE NSEDIIPARTRETAIL
        SET
          (
            DENUMIRE, CODLOCALIT, DENLOCALIT, CODJUDET,
            CODTARA, TELEFON, FAX, EMAIL,
            STRADA, NR1, NR2, BLOC,
            SCARA, ETAJ, APART, SECTOR,
            CODPOSTAL, SEDIUSOCIAL
          )
          = (SELECT V_REC.DENUMIRE, V_REC.CODLOCALIT, V_REC.DENLOCALIT, V_REC.CODJUDET,
              V_REC.CODTARA, V_REC.TELEFON, V_REC.FAX, V_REC.EMAIL,
              V_REC.STRADA, V_REC.NR1, V_REC.NR2, V_REC.BLOC,
              V_REC.SCARA, V_REC.ETAJ, V_REC.APART, V_REC.SECTOR,
              V_REC. CODPOSTAL, V_REC.SEDIUSOCIAL)
        WHERE
          CODSEDIU = V_REC.CODSEDIU;
      END IF;
    END LOOP;

    DELETE FROM NCODFISCRETAIL WHERE CODPARTRETAIL = RECID AND COD NOT IN (SELECT COD FROM TMP_NCODFISCRETAIL);

    FOR V_REC IN (SELECT * FROM TMP_NCODFISCRETAIL) LOOP
      IF V_REC.COD &lt; 0 THEN
        INSERT INTO NCODFISCRETAIL (COD, CODPARTRETAIL, CODFISCAL, PRINCIPAL)
        VALUES (NEXTVAL ('SEQ_NCODFISCRETAIL_COD') , RECID, V_REC.CODFISCAL, V_REC.PRINCIPAL);
      ELSE
        UPDATE NCODFISCRETAIL
        SET
          (CODFISCAL, PRINCIPAL) = (SELECT V_REC.CODFISCAL, V_REC.PRINCIPAL)
        WHERE
          COD = V_REC.COD;
      END IF;
    END LOOP;

    DELETE FROM NPARTDISCRETAIL WHERE CODPARTRETAIL = RECID AND COD NOT IN (SELECT COD FROM TMP_NPARTDISCRETAIL);

    FOR V_REC IN (SELECT * FROM TMP_NPARTDISCRETAIL) LOOP
      IF V_REC.COD &lt; 0 THEN
        INSERT INTO NPARTDISCRETAIL (COD, CODPARTRETAIL, CODCATEGDISC, INDEXLOCAL)
        VALUES (NEXTVAL ('SEQ_NPARTDISC_CODPARTDISC') , RECID, V_REC.CODCATEGDISC, V_REC.INDEXLOCAL);
      ELSE
        UPDATE NPARTDISCRETAIL
        SET
          (CODCATEGDISC, INDEXLOCAL) = (SELECT V_REC.CODCATEGDISC, V_REC.INDEXLOCAL)
        WHERE
          COD = V_REC.COD;
      END IF;
    END LOOP;

    DELETE FROM NDELEGATRETAIL WHERE CODPARTRETAIL = RECID AND COD NOT IN (SELECT COD FROM TMP_NDELEGATRETAIL);

    FOR V_REC IN (SELECT * FROM TMP_NDELEGATRETAIL) LOOP
      IF V_REC.COD &lt; 0 THEN
        INSERT INTO NDELEGATRETAIL (COD, CODPARTRETAIL, DELEGAT, CNP, DOC, SERIEDOC, NRDOC, ELIBERAT, MIJLTRANSP, NRTRANSP, ACTIV, DATADOC, IMPLICIT, OBS)
          VALUES (NEXTVAL ('SEQ_NDELEGATRETAIL_COD') , RECID, V_REC.DELEGAT, V_REC.CNP, V_REC.DOC, V_REC.SERIEDOC, V_REC.NRDOC, V_REC.ELIBERAT,
                  V_REC.MIJLTRANSP, V_REC.NRTRANSP, V_REC.ACTIV, V_REC.DATADOC, V_REC.IMPLICIT, V_REC.OBS);
      ELSE
        UPDATE NDELEGATRETAIL
        SET
          (
            DELEGAT, CNP, DOC, SERIEDOC,
            NRDOC, ELIBERAT, MIJLTRANSP, NRTRANSP,
            ACTIV, DATADOC, IMPLICIT, OBS
          )
          = (SELECT V_REC.DELEGAT, V_REC.CNP, V_REC.DOC, V_REC.SERIEDOC,
              V_REC.NRDOC, V_REC.ELIBERAT, V_REC.MIJLTRANSP, V_REC.NRTRANSP,
              V_REC.ACTIV, V_REC.DATADOC, V_REC.IMPLICIT, V_REC.OBS)
        WHERE
          COD = V_REC.COD;
      END IF;
    END LOOP;

    DELETE FROM NBANCIRETAIL WHERE CODPARTRETAIL = RECID AND COD NOT IN (SELECT COD FROM TMP_NBANCIRETAIL);

    FOR V_REC IN (SELECT * FROM TMP_NBANCIRETAIL) LOOP
      IF V_REC.COD &lt; 0 THEN
        INSERT INTO NBANCIRETAIL (COD, CODPARTRETAIL, CODBANK, IMPLICIT, CODLOCALIT, CONTBANCA, SUCURSALA, CODMONEDA, DENBANCA, DENLOCALIT, CODJUDET, CODTARA)
          VALUES (NEXTVAL ('SEQ_NBANCIRETAIL_COD') , RECID, V_REC.CODBANK, V_REC.IMPLICIT, V_REC.CODLOCALIT, V_REC.CONTBANCA, V_REC.SUCURSALA, V_REC.CODMONEDA,
                  V_REC.DENBANCA, V_REC.DENLOCALIT, V_REC.CODJUDET, V_REC.CODTARA);
      ELSE
        UPDATE NBANCIRETAIL
        SET
          (
            CODBANK, IMPLICIT, CODLOCALIT, CONTBANCA,
            SUCURSALA, CODMONEDA, DENBANCA, DENLOCALIT,
            CODJUDET, CODTARA
          )
          = (SELECT V_REC.CODBANK, V_REC.IMPLICIT, V_REC.CODLOCALIT, V_REC.CONTBANCA,
              V_REC.SUCURSALA, V_REC.CODMONEDA, V_REC.DENBANCA, V_REC.DENLOCALIT,
              V_REC.CODJUDET, V_REC.CODTARA)
        WHERE
          COD = V_REC.COD;
      END IF;
    END LOOP;
  ELSE
    SELECT NEXTVAL ('SEQ_NPARTRETAIL_CODPARTRETAIL') INTO RECID;

    INSERT INTO NPARTRETAIL (CODPARTRETAIL, CODPART, DENUMIRE, REGCOM, OBS, CODEXTERN, CODINTERN, TIPPART, COLDISCOUNT, CODCLASA, FIDELIZARE, DATANASTERE, BLOCAT, INFOBLOCAT, CODCATEGPRET, DATACREARE, USERID)
    SELECT RECID, CODPART, DENUMIRE, REGCOM, OBS, CODEXTERN, CODINTERN, TIPPART, COLDISCOUNT, CODCLASA, FIDELIZARE, DATANASTERE, BLOCAT, INFOBLOCAT, CODCATEGPRET, CURRENT_TIMESTAMP, current_setting ('PKG_GLOBALS.USERID', true) ::numeric
    FROM TMP_NPARTRETAIL;

    INSERT INTO NSEDIIPARTRETAIL (CODSEDIU, CODPARTRETAIL, DENUMIRE, CODLOCALIT, DENLOCALIT, CODJUDET, CODTARA, TELEFON, FAX, EMAIL, STRADA, NR1, NR2, BLOC, SCARA, ETAJ, APART, SECTOR, CODPOSTAL, SEDIUSOCIAL)
    SELECT NEXTVAL ('SEQ_NSEDIIPARTRETAIL_CODSEDIU') , RECID, DENUMIRE, CODLOCALIT, DENLOCALIT, CODJUDET, CODTARA, TELEFON, FAX, EMAIL, STRADA, NR1, NR2, BLOC, SCARA, ETAJ, APART, SECTOR, CODPOSTAL, SEDIUSOCIAL
    FROM TMP_NSEDIIPARTRETAIL;

    INSERT INTO NCODFISCRETAIL (COD, CODPARTRETAIL, CODFISCAL, PRINCIPAL)
    SELECT NEXTVAL ('SEQ_NCODFISCRETAIL_COD') , RECID, CODFISCAL, PRINCIPAL
    FROM TMP_NCODFISCRETAIL;

    INSERT INTO NPARTDISCRETAIL (COD, CODPARTRETAIL, CODCATEGDISC, INDEXLOCAL)
    SELECT NEXTVAL ('SEQ_NPARTDISC_CODPARTDISC') , RECID, CODCATEGDISC, INDEXLOCAL
    FROM TMP_NPARTDISCRETAIL;

    INSERT INTO NDELEGATRETAIL (COD, CODPARTRETAIL, DELEGAT, CNP, DOC, SERIEDOC, NRDOC, ELIBERAT, MIJLTRANSP, NRTRANSP, ACTIV, DATADOC, IMPLICIT, OBS)
    SELECT NEXTVAL ('SEQ_NDELEGATRETAIL_COD') , RECID, DELEGAT, CNP, DOC, SERIEDOC, NRDOC, ELIBERAT, MIJLTRANSP, NRTRANSP, ACTIV, DATADOC, IMPLICIT, OBS
    FROM TMP_NDELEGATRETAIL;

    INSERT INTO NBANCIRETAIL (COD, CODPARTRETAIL, CODBANK, IMPLICIT, CODLOCALIT, CONTBANCA, SUCURSALA, CODMONEDA, DENBANCA, DENLOCALIT, CODJUDET, CODTARA)
    SELECT NEXTVAL ('SEQ_NBANCIRETAIL_COD') , RECID, CODBANK, IMPLICIT, CODLOCALIT, CONTBANCA, SUCURSALA, CODMONEDA, DENBANCA, DENLOCALIT, CODJUDET, CODTARA
    FROM TMP_NBANCIRETAIL;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oferta_roundpret</obj_name>
  <obj_hashval>40da25856699cd54dc13f5795a0f658b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oferta_roundpret(pret numeric, rot numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  pretRotunjit Numeric(20,7);
  intPrec integer;
begin
  --Bogdan 29.09.2022 - 55428 : Oferte furnizori - data/termen
  case Rot
    when 1 then  intPrec := 6;
    when 2 then  intPrec := 5;
    when 3 then  intPrec := 4;
    when 4 then  intPrec := 3;
    when 5 then  intPrec := 2;
    when 6 then  intPrec := 1;
    when 7 then  intPrec := 0;
    when 8 then  intPrec := 7;
  else
     intPrec := 2;
  end case;
  pretRotunjit := ROUND (Pret, intPrec);
  return pretRotunjit;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oferta_sp_postrecords</obj_name>
  <obj_hashval>eb65be76266f3c57bd68e9fa6fcc27c6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oferta_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  V_REC       RECORD;
  vRecNo      numeric := 0;
  vCod        numeric;
  vCodPart    numeric;
  vCodClaseP  numeric;
  vtest       numeric;
  vDenumire   varchar;
  vCodExtern  varchar;
  vUmSec      numeric;
  aCarnetDoc  numeric;
  aNrDoc      numeric;
  aCodSubunit numeric;
  aDataDoc    date;
  aDoc        varchar;
  aTIPOFERTA  numeric;
  vUpdArtCli  numeric;
  BEGIN
  --Florin 19.08.2025 - fixat 66378
  --Florin 07.08.2025 - sinc. Oracle
  --Florin 24.07.2024 - sinc. Oracle
  --Florin 07.06.2024 - sinc. Oracle
  --Florin 06.06.2023 - fixat 58475
  --Florin 01.06.2023 - monitor
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  --Florin 08.04.2021 -  fixat 46967
  perform pkg_oferta_setct_monitor('MON_28');
  SELECT
    CodOferta,
    coalesce( Partener, 0),
    coalesce( CodClaseP, 0),
    CarnetDoc,
    NrDoc,
    Subunitatea,
    DataStart,
    coalesce(case when TipDoc = 50 then 'OC' when TipDoc = 51 then 'OF' end , '') || coalesce(NrDoc::varchar , '') || '/' || coalesce(to_char(DataStart, 'dd.mm.yyyy'), '') || '-' || coalesce(to_char(DataEnd, 'dd.mm.yyyy'), ''),
    TIPDOC
  INTO
    RecId,
    vCodPart,
    vCodClaseP,
    aCarnetDoc,
    aNrDoc,
    aCodSubunit,
    aDataDoc,
    aDoc,
    aTIPOFERTA
  FROM TMP_Oferta;

   perform PKG_CFGTABLES_EXT_POSTRECORDS_INIT(aTIPOFERTA);

  if Operation = 0 then  -- UPDATE
    if (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT
        FROM   PKG_USERFIRME_ValidPostLog(null, current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_OFERTA.CT_MONITOR', true)))
    then
      perform pkg_userfirme_postlogcucommit( 'OFERTA',
                                             current_setting('PKG_GLOBALS.USERNAME', true),
                                             'M',
                                             RECID,
                                             current_setting('PKG_GLOBALS.FIRMANAME', true),
                                             aCodSubunit,
                                             aDataDoc,
                                             aDoc,
                                             null,
                                             (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(null, null)));
    end if;

    -- Master OFERTA
    UPDATE OFERTA
    SET
      (TipDoc,
      Anulat,
      Blocat,
      Operat,
      NrDoc,
      DataStart,
      DataEnd,
      DATACERERE,
      DATAOFERTA,
      ToateSubunit,
      OFERTAT,
      TipBeneficiar,
      CodClaseP,
      Partener,
      Obs,
      Moneda,
      CodLocatie,
      Subunitatea,
      CodFiscal,
      UserId,
      --DataCreare,
      CarnetDoc,
      SeriaDoc,
      CodPersC,
      TIPLIVRARE,
      Agent,
      NRMAXAPROBARI,
      NRI,
      CodNParcAut,
      CodPartComis,
      ProcDisc,
      CodAnaliza) = (
      SELECT
        TipDoc,
        Anulat,
        Blocat,
        Operat,
        NrDoc,
        DataStart,
        DataEnd,
        DATACERERE,
        DATAOFERTA,
        ToateSubunit,
        OFERTAT,
        TipBeneficiar,
        CodClaseP,
        Partener,
        Obs,
        Moneda,
        CodLocatie,
        Subunitatea,
        CodFiscal,
        UserId,
        --DataCreare,
        CarnetDoc,
        SeriaDoc,
        CodPersC,
        TIPLIVRARE,
        Agent,
        NRMAXAPROBARI,
        NRI,
        CodNParcAut,
        CodPartComis,
        ProcDisc,
        CodAnaliza
      FROM TMP_OFERTA )
    WHERE CodOferta = RecId ;

    DELETE FROM OFERTA1 WHERE CodOferta = RecID and CodOferta1 not in (SELECT CodOferta1 FROM TMP_OFERTA1 );

    for v_rec in (
                  SELECT
                    CodOferta1,
                    CodOferta,
                    CodObiect,
                    CodArticol,
                    UmSec,
                    CantMin * Paritate CANTMIN,
                    Pret / Paritate PRET,
                    PretRef / Paritate PRETREF,
                    Obs,
                    ZileL,
                    ZileC,
                    ProcAdaos,
                    ProcDiscount,
                    CodExtOfe,
                    CantMinUM1,
                    D1,
                    D2,
                    D3,
                    CantOptim,
                    CANTOPTIMUM1,
                    CantMax * Paritate CANTMAX,
                    CodCatPret,
                    PRETUM1,
                    CodProiect,
                    IndexLocal,
                    DataCertifI,
                    DataCertifF,
                    CODCENTRU,
                    PretAchiz / Paritate PRETACHIZ,
                    CodAnalizaNod,
                    GestAct,
                    CodLinieDocImp
                  FROM TMP_OFERTA1
                  order BY IndexLocal )
    loop
      if coalesce( v_rec.CodOferta1, 0) &gt; 0 then
        insert into x (view_name, test) values ('vCod333', vCod);

        UPDATE OFERTA1
        SET
          CodObiect     = v_rec.CodObiect,
          CodArticol    = v_rec.CodArticol,
          UMSec         = v_rec.UMSec,
          CantMin       = v_rec.CantMin,
          Pret          = v_rec.Pret,
          PretRef       = v_rec.PretRef,
          Obs           = v_rec.Obs,
          ZileL         = v_rec.ZileL,
          ZileC         = v_rec.ZileC,
          ProcAdaos     = v_rec.ProcAdaos,
          ProcDiscount  = v_rec.ProcDiscount,
          CodExtOfe     = v_rec.CodExtOfe,
          CantMinUM1    = v_rec.CantMinUM1,
          D1            = v_rec.D1,
          D2            = v_rec.D2,
          D3            = v_rec.D3,
          CantOptim     = v_rec.CantOptim,
          CANTOPTIMUM1  = V_REC.CANTOPTIMUM1,
          CantMax       = v_rec.CantMax,
          CodCatPret    = v_rec.CodCatPret,
          PRETUM1       = v_rec.PRETUM1,
          CodProiect    = v_rec.CodProiect,
          IndexLocal    = v_rec.IndexLocal,
          DataCertifI   = v_rec.DataCertifI,
          DataCertifF   = v_rec.DataCertifF,
          codcentru     = v_rec.codcentru,
          PretAchiz     = v_rec.Pretachiz,
          CodAnalizaNod = v_Rec.CodAnalizaNod,
          GestAct       = v_Rec.GestAct,
          CodLinieDocImp = v_rec.codliniedocimp
        WHERE
          CodOferta1 = v_rec.CodOferta1 ;
      else
        SELECT nextval('SEQ_OFERTA1_CODOFERTA1') INTO vCod;

        perform PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('OFERTA1', vCod, V_REC.CODOFERTA1);
        insert into x (view_name, test) values ('vCod', vCod);

--        if (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'TMP_OFERTA1EXT')) = 1 then
--          execute ' UPDATE TMP_OFERTA1EXT SET CODOFERTA1 = ' || coalesce(VCOD::varchar , '') || ' WHERE CODOFERTA1 = ' || coalesce(V_REC.CODOFERTA1::varchar , '');
--        end if;

        INSERT INTO OFERTA1 (
          CodOferta1,
          CodOferta,
          CodObiect,
          CodArticol,
          UMSec,
          CantMin,
          Pret,
          PretRef,
          Obs,
          ZileL,
          ZileC,
          ProcAdaos,
          ProcDiscount,
          CodExtOfe,
          CantMinUM1,
          D1,
          D2,
          D3,
          CantOptim,
          CANTOPTIMUM1,
          CantMax,
          CodCatPret,
          PRETUM1,
          CodProiect,
          IndexLocal,
          DataCertifI,
          DataCertifF,
          CodCentru,
          PretAchiz,
          CodAnalizaNod,
          GestAct,
          Codliniedocimp)
        values (
        vCod,
        RecId,
        v_rec.CodObiect,
        v_rec.CodArticol,
        v_rec.UMSec,
        v_rec.CantMin,
        v_rec.Pret,
        v_rec.PretRef,
        v_rec.Obs,
        v_rec.ZileL,
        v_rec.ZileC,
        v_rec.ProcAdaos,
        v_rec.ProcDiscount,
        v_rec.CodExtOfe,
        v_rec.CantMinUM1,
        v_rec.D1,
        v_rec.D2,
        v_rec.D3,
        v_rec.CantOptim,
        V_REC.CANTOPTIMUM1,
        v_rec.CantMax,
        v_rec.CodCatPret,
        V_REC.PRETUM1,
        v_rec.CodProiect,
        v_rec.IndexLocal,
        v_rec.DataCertifI,
        v_rec.DataCertifF,
        v_rec.codcentru,
        v_rec.PretAchiz,
        v_rec.CodAnalizaNod,
        v_rec.GestAct,
        v_rec.codliniedocimp);
      end if;
    end loop;

    DELETE FROM CMDAPROBARI A WHERE CODDOC = RECID and TIPDOC = aTIPOFERTA and not exists (SELECT COD FROM TMP_CMDAPROBARI WHERE COD = A.COD );

    for V_REC in (SELECT * FROM TMP_CMDAPROBARI ) loop
      if V_REC.COD &lt; 0 then
        INSERT INTO CMDAPROBARI (
          COD,
          CODDOC,
          TIPDOC,
          NIVEL,
          STARE,
          OBS,
          USERID )
        values (
        nextval('SEQ_CMDAPROBARI_COD'),
        RECID,
        aTIPOFERTA,
        V_REC.NIVEL,
        V_REC.STARE,
        V_REC.OBS,
        V_REC.USERID );
      else
        UPDATE CMDAPROBARI
        set
          NIVEL  = V_REC.NIVEL,
          STARE  = V_REC.STARE,
          USERID = V_REC.USERID,
          OBS    = V_REC.OBS
        where
          COD = V_REC.COD ;
      end if;
    end loop;
  ELSE  -- INSERT
    if (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT
        FROM   PKG_USERFIRME_ValidPostLog(null, current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_OFERTA.CT_MONITOR', true)))
    then
      perform pkg_userfirme_postlogcucommit( 'OFERTA',
                                             current_setting('PKG_GLOBALS.USERNAME', true),
                                             'A',
                                             RECID,
                                             current_setting('PKG_GLOBALS.FIRMANAME', true),
                                             aCodSubunit,
                                             aDataDoc,
                                             aDoc,
                                             null,
                                             (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(null, null)));
    end if;

    SELECT nextval('SEQ_OFERTA_CODOFERTA') INTO RecId;
    PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('OFERTA', RecId);
    insert into x (view_name, test) values ('RecId', RecId);
    INSERT INTO OFERTA (
      CodOferta,
      TipDoc,
      Anulat,
      Blocat,
      Operat,
      NrDoc,
      DataStart,
      DataEnd,
      DATACERERE,
      DATAOFERTA,
      ToateSubunit,
      OFERTAT,
      TipBeneficiar,
      CodClaseP,
      Partener,
      An,
      Luna,
      Obs,
      Moneda,
      CodLocatie,
      Subunitatea,
      CodFiscal,
      UserId,
      DataCreare,
      CarnetDoc,
      SeriaDoc,
      CodPersC,
      TIPLIVRARE,
      Agent,
      NRMAXAPROBARI,
      NRI,
      CodNParcAut,
      CodPartComis,
      ProcDisc,
      CodAnaliza )
    select
      RecId,
      TipDoc,
      Anulat,
      Blocat,
      Operat,
      NrDoc,
      DataStart,
      DataEnd,
      DATACERERE,
      DATAOFERTA,
      ToateSubunit,
      OFERTAT,
      TipBeneficiar,
      CodClaseP,
      Partener,
      An,
      Luna,
      Obs,
      Moneda,
      CodLocatie,
      Subunitatea,
      CodFiscal,
      current_setting('PKG_GLOBALS.USERID', true)::numeric,
      current_timestamp,
      CarnetDoc,
      SeriaDoc,
      CodPersC,
      TIPLIVRARE,
      Agent,
      NRMAXAPROBARI,
      NRI,
      CodNParcAut,
      CodPartComis,
      ProcDisc,
      CodAnaliza
    FROM TMP_OFERTA;

    -- Detail Oferta1
    SELECT count(1) INTO vRecNo FROM TMP_Oferta1;

    for v_rec in (
                  select
                    CodOferta1,
                    CodObiect,
                    CodArticol,
                    UmSec,
                    CantMin * Paritate CANTMIN,
                    Pret / Paritate PRET,
                    PretRef / Paritate PRETREF,
                    Obs,
                    ZileL,
                    ZileC,
                    ProcAdaos,
                    ProcDiscount,
                    CodExtOfe,
                    CantMinUM1,
                    D1,
                    D2,
                    D3,
                    CantOptim,
                    CantOptimUM1,
                    CantMax * Paritate CANTMAX,
                    CodCatPret,
                    PretUM1,
                    CodProiect,
                    IndexLocal,
                    DataCertifI,
                    DataCertifF,
                    CodCentru,
                    PretAchiz / Paritate PRETACHIZ,
                    CodAnalizaNod,
                    GestAct,
                    Codliniedocimp
                  FROM tmp_oferta1 )
    loop
      SELECT nextval('SEQ_OFERTA1_CODOFERTA1') INTO vCod;
      perform PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('OFERTA1', vCod, v_rec.CodOferta1);

--      if (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'TMP_OFERTA1EXT')) = 1 then
--        execute ' UPDATE TMP_OFERTA1EXT SET CODOFERTA1 = ' || coalesce(vCod::varchar , '') || ' WHERE CODOFERTA1 = ' || coalesce(v_rec.CodOferta1::varchar , '');
--      end if;

      INSERT INTO OFERTA1 (
        CodOferta1,
        CodOferta,
        CodObiect,
        CodArticol,
        UMSec,
        CantMin,
        Pret,
        PretRef,
        Obs,
        ZileL,
        ZileC,
        ProcAdaos,
        ProcDiscount,
        CodExtOfe,
        CantMinUM1,
        D1,
        D2,
        D3,
        CantOptim,
        CantOptimUM1,
        CantMax,
        CodCatPret,
        PretUM1,
        CodProiect,
        IndexLocal,
        Datacertifi,
        Datacertiff,
        CodCentru,
        PretAchiz,
        CodAnalizaNod,
        GestAct,
        Codliniedocimp)
      values (
      vCod,
      RecId,
      v_rec.CodObiect,
      v_rec.CodArticol,
      v_rec.UMSec,
      v_rec.CantMin,
      v_rec.Pret,
      v_rec.PretRef,
      v_rec.Obs,
      v_rec.ZileL,
      v_rec.ZileC,
      v_rec.ProcAdaos,
      v_rec.ProcDiscount,
      v_rec.CodExtOfe,
      v_rec.CantMinUM1,
      v_rec.D1,
      v_rec.D2,
      v_rec.D3,
      v_rec.CantOptim,
      v_rec.CantOptimUM1,
      v_rec.CantMax,
      v_rec.CodCatPret,
      v_rec.PretUM1,
      v_rec.CodProiect,
      v_rec.IndexLocal,
      v_rec.datacertifI,
      v_rec.datacertiff,
      v_rec.CodCentru,
      v_rec.PretAchiz,
      v_rec.CodAnalizaNod,
      v_rec.GestAct,
      v_rec.CodLinieDocimp);
    end loop;

    INSERT INTO CMDAPROBARI (
      COD,
      CODDOC,
      TIPDOC,
      NIVEL,
      STARE,
      OBS,
      USERID )
    select
      nextval('SEQ_CMDAPROBARI_COD'),
      RECID,
      aTIPOFERTA,
      NIVEL,
      STARE,
      OBS,
      USERID
    FROM TMP_CMDAPROBARI;
  end if;

  -- Actualizare nartcli
  if vCodPart &lt;&gt; 0 or vCodClaseP &lt;&gt; 0 then
    vUpdArtCli := coalesce( (select PKG_CATEGCONST_GetValConstanta.WME_RESULT from PKG_CATEGCONST_GetValConstanta(null, 'DetArtPartFromDoc', current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric, current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric))::numeric, 1);
    if vUpdArtCli = 1 then
  --vUpdArtCli := 1;

      for v_rec in (
                  SELECT
                    CodObiect,
                    coalesce( max(CodClaseP),
                    vCodClaseP, 0) CODCLASEP,
                    max(DenArtCli) DENARTCLI,
                    max(CodExtCli) CODEXTCLI,
                    max(CodLaClient) CODLACLIENT,
                    max(UMSec) UMSEC
                  FROM TMP_Oferta1
                   WHERE coalesce(DENARTCLI,'@') &lt;&gt; coalesce(DENARTCLI_INI,'@') OR coalesce(CodExtCli,'@') &lt;&gt; coalesce(CodExtCli_INI,'@') OR coalesce(CodLaClient,'@') &lt;&gt; coalesce(CodLaClient_INI,'@')
                  group BY CodObiect )
      loop
        perform PKG_NOM_ARTICOL_ACTUALIZEAZA_NARTCLI( v_rec.CodObiect,
          vCodPart,
          v_rec.CodClaseP,
          v_rec.DenArtCli,
          v_rec.CodExtCli,
          v_rec.CodLaClient,
          v_rec.UMSec,
          7,
          vUpdArtCli);
      end loop;
    END IF;
  end if;

  perform PKG_CARNETEDOC_SOLVENUMARDOC( aCarnetDoc, (aNrDoc)::character varying);

  perform NotifyModif( OPERATION, RECID, 'OFERTA');

--  if (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'OFERTA1EXT')) = 1
--     and
--     (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'TMP_OFERTA1EXT')) = 1
--  then
--    execute 'DELETE FROM OFERTA1EXT WHERE CODOFERTA1 IN (SELECT CODOFERTA1 FROM TMP_OFERTA1_INITIAL)  ';
--    execute 'UPDATE TMP_OFERTA1EXT SET CODOFERTA1EXT = nextval(''SEQ_OFERTA1EXT_CODOFERTA1EXT'') WHERE CODOFERTA1EXT &lt; 0';
--    execute 'INSERT INTO OFERTA1EXT SELECT * FROM TMP_OFERTA1EXT ';
--  end if;
--
--
--  if (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'OFERTAEXT')) = 1
--     and
--     (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'TMP_OFERTAEXT')) = 1
--  then
--    execute 'DELETE FROM OFERTAEXT WHERE CODOFERTA = ' || RecID::varchar;
--    execute 'UPDATE TMP_OFERTAEXT SET CODOFERTAEXT = nextval(''SEQ_OFERTAEXT_CODOFERTAEXT'') WHERE CODOFERTAEXT &lt; 0';
--        execute 'UPDATE TMP_OFERTAEXT SET CODOFERTA = ' || RECID::varchar;
--    execute 'INSERT INTO OFERTAEXT SELECT * FROM TMP_OFERTAEXT ';
--  end if;
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS (aTIPOFERTA);

end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_onorarecomenzi_get_tmp_livrstoc</obj_name>
  <obj_hashval>947cd1dac3d613efd31fc99ed366b7cd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_onorarecomenzi_get_tmp_livrstoc(acodobiect numeric, atiparticol numeric, acodcomanda numeric, adatestart character varying, acodobiectechiv numeric, acodcomanda1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  lTipArtRel    numeric;
  lOraDateStart date;
  lCodObj       numeric;
  filtruGest    numeric;
  filtruIOArt   numeric;
  aNeconf       NUMERIC(1);
BEGIN
  --Florin 13.02.2024 - sinc. Oracle
  --Florin 09.11.2022
  BEGIN
    SELECT TO_NUMBER(fnc_getvalconstantalucru('IesLivrNeconf')) INTO STRICT aNeconf;
    EXCEPTION WHEN OTHERS THEN aNeconf  := 1;
  END;
  lTipArtRel := 0;
  IF COALESCE (aTipArticol, 0) IN (2, 3) THEN lTipArtRel := 1; END IF;

  lOraDateStart := to_date (aDateStart, 'DD.MM.YYYY');
  lCodObj       := aCodObiect;  -- caut in stoc obiectul de pe comanda

  IF aCodObiectEchiv &gt; 0 THEN
    lCodObj := aCodObiectEchiv;  -- caut in stoc obiectul echivalent selectat
  END IF;

  SELECT Count (1) INTO filtruGest  FROM TMP_MANEVRA_LISTE WHERE UPPER (Filtru) = 'CODGEST';
  SELECT Count (1) INTO filtruIOArt FROM TMP_MANEVRA_LISTE WHERE UPPER (Filtru) = 'CODIOART';

  DELETE FROM TMP_OnorCom_LivrStoc;

  INSERT INTO TMP_OnorCom_LivrStoc (CodArticol, CodGest, CodLocatie, Producator,
      CodTipCont, DataIntrStoc, Expira, CodSerie,
      SerieObiect, CodUM, D1, D2,
      D3, Stoc, STOCINITIAL, Preluat,
      Cantar, RezervatCom1Curenta, RezervatCom1Altele, RezervatComCurenta,
      RezervatComAltele, CodObiect, DenObiect, CodNIRSTOC,
      CodNIRSER, PrefixDoc, SeriaDoc, NrDoc)
  SELECT NA.CodArticol, N.Gest, NSTOC.CodLocatie,
    CASE WHEN NSTOC.TipDocAchiz = 7 THEN (SELECT Den_Gest FROM NGest WHERE CodGest = NSTOC.CodGestProd)
         ELSE (SELECT Den_Part FROM NPart WHERE CodPart = NSToc.Furn)
    END PRODUCATOR,
    NSTOC.CodIOArt, N.DataNIR, NSTOC.TG, NSER.CodSerie,
    CASE WHEN NSTOC.TipSerie = 0 THEN NULL ELSE (SELECT Serie FROM NSerii WHERE CodSerie = NSER.CodSerie) END SERIEOBIECT,
    NA.UM,
    CASE WHEN lTipArtRel = 1 THEN COALESCE (NSTOC.D1, 0) ELSE 0 END D1,
    CASE WHEN lTipArtRel = 1 THEN COALESCE (NSTOC.D2, 0) ELSE 0 END D2,
    CASE WHEN lTipArtRel = 1 THEN COALESCE (NSTOC.D3, 0) ELSE 0 END D3,
    CASE WHEN NSTOC.TIPSERIE &gt; 0
         THEN NSER.REST  - COALESCE ( (SELECT SUM (CANT) FROM STOCLOCK WHERE CODNIRSER  = NSER.CODNIRSER)   , 0)
         ELSE NSTOC.REST - COALESCE ( (SELECT SUM (CANT) FROM STOCLOCK WHERE CODNIRSTOC = NSTOC.CODNIRSTOC) , 0)
    END STOC,
    CASE WHEN NSTOC.TIPSERIE &gt; 0
         THEN NSER.REST  - COALESCE ( (SELECT SUM (CANT) FROM STOCLOCK WHERE CODNIRSER  = NSER.CODNIRSER)   , 0)
         ELSE NSTOC.REST - COALESCE ( (SELECT SUM (CANT) FROM STOCLOCK WHERE CODNIRSTOC = NSTOC.CODNIRSTOC) , 0)
    END STOCINITIAL,
    0 PRELUAT,
    (SELECT COALESCE (Sum (Net_KG) , 0) FROM Cantar WHERE TipDoc IN (18, 43, 44) AND CodDoc1 = aCodComanda1 AND COALESCE (Net_KG, 0) &lt;&gt; 0) CANTAR, -- doar comenzi clienti, comenzi de la gestiuni, comenzi de la subunitati
    (SELECT COALESCE (Sum (RS.Rest), 0)
     FROM RezervatS RS
     WHERE  COALESCE (RS.CodNIRStoc, 0) = COALESCE (NSTOC.CodNIRStoc, 0)
        AND COALESCE (RS.CodNIRSer , 0) = COALESCE (NSER.CodNIRSer  , 0)
        AND RS.CodComanda1 = aCodComanda1
        AND COALESCE (RS.Rest, 0) &lt;&gt; 0
    ) REZERVATCOM1CURENTA,
    (SELECT COALESCE (Sum (RS.Rest) , 0)
     FROM RezervatS RS
     WHERE  COALESCE (RS.CodNIRStoc, 0) = COALESCE (NSTOC.CodNIRStoc, 0)
        AND COALESCE (RS.CodNIRSer , 0) = COALESCE (NSER.CodNIRSer  , 0)
        AND RS.CodComanda1 &lt;&gt; aCodComanda1
        AND COALESCE (RS.Rest, 0) &lt;&gt; 0
    ) REZERVATCOM1ALTELE,
    (SELECT COALESCE (Sum (RS.Rest) , 0)
     FROM RezervatS RS LEFT JOIN Comanda1 C1 ON C1.CodComanda1 = RS.CodComanda1
     WHERE  COALESCE (RS.CodNIRStoc, 0) = COALESCE (NSTOC.CodNIRStoc, 0)
        AND COALESCE (RS.CodNIRSer , 0) = COALESCE (NSER.CodNIRSer  , 0)
        AND C1.CodComanda = aCodComanda
        AND COALESCE (RS.Rest, 0) &lt;&gt; 0
    ) REZERVATCOMCURENTA,
    (SELECT COALESCE (Sum (RS.Rest) , 0)
     FROM RezervatS RS LEFT JOIN Comanda1 C1 ON C1.CodComanda1 = RS.CodComanda1
     WHERE  COALESCE (RS.CodNIRStoc, 0) = COALESCE (NSTOC.CodNIRStoc, 0)
        AND COALESCE (RS.CodNIRSer , 0) = COALESCE (NSER.CodNIRSer  , 0)
        AND C1.CodComanda &lt;&gt; aCodComanda
        AND COALESCE (RS.Rest, 0) &lt;&gt; 0
    ) REZERVATCOMALTELE,
    NSTOC.CodObiect, NAO.Denumire, NSTOC.CodNIRSTOC,
    COALESCE (NSER.CodNIRSER, 0) CODNIRSER, COALESCE (intr.PrefixDoc, tr.PrefixDoc, ies.PrefixDoc) PREFIXDOC,
    COALESCE (intr.SeriaDoc, tr.SeriaDoc, ies.SeriaDoc) SERIADOC, COALESCE (intr.NrDoc, tr.NrDoc, ies.NrDoc) NRDOC
  FROM NIRStoc                NSTOC
    INNER JOIN NIR            N     ON N.CodNIR        = NSTOC.CodNIR
    INNER JOIN NGEST          G     ON G.CodGest       = N.Gest
    LEFT  JOIN TMP_IOArt_Luna TIOAL ON TIOAL.CodIOArt  = NSTOC.CodIOArt
    LEFT  JOIN NArtObj        NAO   ON NAO.CodObiect   = NSTOC.CodObiect
    LEFT  JOIN NArt           NA    ON NA.CodArticol   = NAO.CodArticol
    LEFT  JOIN NIRSer         NSER  ON NSER.CodNIRStoc = NSTOC.CodNIRStoc
    LEFT  JOIN intrari        intr  ON intr.codintr    = n.codintr
    LEFT  JOIN transf         tr    ON tr.codtransf    = n.codtransf
    LEFT  JOIN iesiri         ies   ON ies.codies      = n.codies
  WHERE NSTOC.CodObiect = lCodObj
    AND TIOAL.MG &lt;&gt; 5   -- Metoda de Gestiune: 5 = 'articole/stocuri valorice'
    AND Coalesce (NSER.Rest, NSTOC.Rest) &lt;&gt; 0
    AND (filtruGest  = 0 OR COALESCE (N.Gest, 0)         IN (SELECT Valoare ::NUMERIC FROM TMP_MANEVRA_LISTE WHERE UPPER (Filtru) = 'CODGEST'))
    AND (filtruIOArt = 0 OR COALESCE (NSTOC.CodIOArt, 0) IN (SELECT Valoare :: NUMERIC FROM TMP_MANEVRA_LISTE WHERE UPPER (Filtru) = 'CODIOART'))
    AND G.CodSubunit = (SELECT Pkg_Globals_GETSUBUNITATE_DOC.WME_RESULT FROM Pkg_Globals_GETSUBUNITATE_DOC (NULL,NULL))
    AND (aNeconf = 1 or (aNeconf = 2 and g.tip &lt;&gt; 4));

  DELETE FROM TMP_OnorCom_LivrStoc where stoc &lt;= 0;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_onorarecomenzi_get_tmp_operlivr_articole</obj_name>
  <obj_hashval>83daed26af0f566498cf074536afa64b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_onorarecomenzi_get_tmp_operlivr_articole(arez numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 30.04.2025 - sinc. Oracle
  --Florin 07.03.2023 - fixat 57515
  --Florin 01.03.2023 - sinc. racle
  --Florin 26.08.2022 - sinc. Oracle (25.08.2022)
  --Stef 29.06.2022 - fnc_getprocenttvaart
  --Adina 18.05.2021 - sinc.Oracle din 17.05.2021 - doar martor la zi
  --Bogdan 11.02.2021
  DELETE FROM TMP_OnorCom_PrelStoc;
  DELETE FROM TMP_OnorCom_Articole;

  INSERT INTO TMP_Onorcom_Articole (CODCOMANDA1, CODCOMANDA, INDEXLOCAL, CODOBIECT,
      DENOBIECT, CODEXTERN, CODARTICOL, TERMENLIVR,
      CODUM, UMSEC, CANTCOMANDAT, CANTACCEPTAT,
      RESTLIVR, LIVRSTOC, LIVRECHIV, CODEKIV,
      DENEKIV, PARITATEEKIV, CODUMEKIV, CODUMSPEC,
      CANTSPEC, D1, D2, D3,
      RELATIEUMSPEC, RELATIEUMALT, Cantaribil, CANT,
      PRET, PRETORIG, VALOARE, ADDIM,
      PROCDISC, OBS, SCADENTA, TERMENPLATA,
      NET, BRUT, A1, A2,
      A3, A4, A5, A6,
      KGA1, KGA2, KGA3, KGA4,
      KGA5, KGA6, FlagInchidere, PROCTVA,
      RestNeglijCmd, CoefDiscMaj, Codgest, Codioart,
      TipLinie, ContServ, GestAct, den_um1)
  SELECT C1.CodComanda1, C.CodComanda, c1.IndexLocal, C1.CodObiect,
    NAO.Denumire, NAO.CodExtern, NA.CODARTICOL, C1.Termen,
    NA.UM, C1.UMSec, C1.CantComandat, C1.CantAcceptat,
    C1.RestAcceptat, 0, 0, 0,
    ' ', 1, 0, NA.UM1,
    C1.CantUM1, C1.D1, C1.D2, C1.D3,
    NA.RelatieUM1, NA.RelatieUM2,
    CASE WHEN U.TipUM = 1 AND COALESCE (U.Coef, 0) &lt;&gt; 0 THEN 1 ELSE 0 END ,
    0,
    case when c.pretcuamanunt = 1 then C1.PU / (1 + (SELECT wme_result FROM PKG_SELECTARTICOLE_GETPROCENTTVA(NULL, NAO.CodArticol, GETANLUCRU(),GETLUNALUCRU())) / 100) else c1.pu end,
    case when c.pretcuamanunt = 1 then C1.PRETORIG / (1 + (SELECT wme_result FROM PKG_SELECTARTICOLE_GETPROCENTTVA(NULL, NAO.CodArticol, GETANLUCRU(), GETLUNALUCRU())) / 100) else C1.PRETORIG end,
    0, C1.AdDim, C1.ProcDisc, C1.Obs, C1.Scadenta, NAO.TermenPlata,
    0, 0,
    0, 0, 0, 0,
    0, 0, 0, 0,
    0, 0, 0, 0,
    0,
    fnc_getprocenttvaart(NAO.CodArticol, current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric, current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric) ,
    COALESCE (NA.RestNeglijCmd, 0.01) , CoefDiscMaj, IMP.GESTIMPLICITA,
    IMP.CONTIMPLICIT,
    CASE WHEN NA.TIPARTICOL = '0' THEN '=' ELSE 'S' END TIPLINIE,
    CASE WHEN NA.TIPARTICOL = '1' THEN NA.ContServiciu ELSE NULL END CONTSERV,
    CASE WHEN NA.TIPARTICOL = '1' THEN Coalesce (NullIF (C1.GestAct, 0) , IMP.GESTIMPLICITA) ELSE NULL END GESTACT,
    num1.den_um1
  FROM Comanda                 C
      INNER JOIN Comanda1      C1  ON C1.CodComanda  = C.CodComanda
      INNER JOIN NArtObj       NAO ON NAO.CodObiect  = C1.CodObiect
      INNER JOIN NArt          NA  ON NA.CodArticol  = NAO.CodArticol
      INNER JOIN NUM           U   ON U.CodUM        = NA.UM
      LEFT  JOIN NARTIMPLICITE IMP ON IMP.CODARTICOL = NA.CODARTICOL AND IMP.CODSUBUNIT = C.SUBUNITATEA
      LEFT  JOIN NUM1              ON NUM1.CODUM1    = C1.UMSEC
  WHERE
    C.TipDoc IN (18, 43, 44)  -- doar comenzi clienti, comenzi de la gestiuni, comenzi de la subunitati
    AND C.UserIDBlocaj = current_setting ('PKG_GLOBALS.UserID', true)::NUMERIC
    AND C1.RESTACCEPTAT &lt;&gt; 0 and C1.RESTACCEPTAT * c1.cantacceptat &gt; 0
    AND (current_setting ('PKG_ONORARECOMENZI.pFlagTermLivr', true)::numeric = 0
         OR
         COALESCE (C1.Termen, (to_date(current_setting ('PKG_ONORARECOMENZI.pDataSys', true),'dd.mm.yyyy'))) BETWEEN to_date( current_setting ('PKG_ONORARECOMENZI.pDataTermLivrDeLa', true),'dd.mm.yyyy') AND to_date( current_setting ('PKG_ONORARECOMENZI.pDataTermLivrPanaLa', true),'dd.mm.yyyy')
        )
    AND (current_setting ('PKG_ONORARECOMENZI.pFlagClaseArt', true)::numeric = 1
         OR
         COALESCE (NA.Clasa, 0) IN (SELECT Valoare::NUMERIC FROM TMP_MANEVRA_LISTE WHERE UPPER (Filtru) = 'CODCLASEA')
    AND COALESCE(C1.MODINCHIDERE,0) = 0
    AND (aRez = 0 or exists (select r.codrezervats from rezervats r where r.codcomanda1 = c1.codcomanda1 and r.rest &gt; 0)));
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_get_job_datafin</obj_name>
  <obj_hashval>3df77cd13cd0661825973d6d2ab14d4a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_get_job_datafin(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  --Stef 06.09.2022
  WME_Result := To_Date(current_setting('PKG_ORA_LISTS.JOB_DATAFin', true),'dd.mm.yyyy');
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_setjob_codjob1</obj_name>
  <obj_hashval>3d4d86d45e7afe265632e0ca9c1d1f56</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_setjob_codjob1(ajob_codjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_ORA_LISTS.JOB_CodJob1',to_char(aJOB_CodJob1,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_orar_sp_lockrecord</obj_name>
  <obj_hashval>3895c0da27965142f035290a481d52d8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_orar_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CODORAR INTO Tmp FROM ORAR WHERE CodORAR = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pachete_setnrdoc_i</obj_name>
  <obj_hashval>2c1395ca5edae6c0033fe81aaf28aeab</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pachete_setnrdoc_i(anrdoc numeric, acarnet numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PACHETE.CARNETDOC_I',to_char(ACARNET,'999999999999999999'),false);
perform set_config('PKG_PACHETE.NRDOC_I',to_char(ANRDOC,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pachete_sp_insertrecord</obj_name>
  <obj_hashval>41b500d8f2bbaaa6e0fafd6a4e59be7d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pachete_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 12.04.2023 - sinc. Oracle (10.04.2023)
  INSERT INTO TMP_PACHETE(codpachete, listat) VALUES(0, 0);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(77);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_contechivalat</obj_name>
  <obj_hashval>2a932820839ddfd1c9f38462650e58a1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_contechivalat(INOUT wme_result numeric, INOUT acodcont numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  Res numeric := 0;
begin
  --Bogdan 09.02.2021
  SELECT COALESCE (MIN (CONTNOU) , 0)
  INTO RES
  FROM NCONTECHIV
  WHERE CONTVECHI = aCODCONT AND AN = current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric;

  WME_Result := RES;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_setcodcontrep</obj_name>
  <obj_hashval>0e2710fcaa41446a02594737c50c40fa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_setcodcontrep(acodcont numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANCONTURI.CODCONTREP',to_char(aCODCONT,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_sp_postrecords</obj_name>
  <obj_hashval>d3ba096fe933d7d91516c4111dac0650</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC          RECORD;
  V_RECPARINTE   RECORD;
  V_RECANALITICE RECORD;
  V_REC_SOLDSUB  RECORD;
    V_REC_SOLD     RECORD;

  aCODPARINTE            NUMERIC := 0;
  NrCopii                NUMERIC := 0;
  NR                     NUMERIC := 0;
  aAnLuna                NUMERIC := 0;
  ANINCEPUTREPARTIZARI   NUMERIC := 0;
  LUNAINCEPUTREPARTIZARI NUMERIC := 0;
  CONTUL_EXISTA_IN_LUNA  NUMERIC := 0;
  aCOD                   NUMERIC := 0;
  VCOD                   NUMERIC := 0;
  ANI                    NUMERIC;
  LUNAI                  NUMERIC;
  aCODCONTREPSOLD        NUMERIC;
  aCODCONTREPSOLDSUB     NUMERIC;
  aCODCONTREPRUL         NUMERIC;
  aCODCONTREPRULSUB      NUMERIC;
  aInitializari          numeric;
    aCODCONTSOLD         numeric;
BEGIN
  --Florin 20.04.2023 - sinc. Oracle
  --Florin 14.02.2022 - sinc. Oracle (13.02.2022)
  --Florin 08.01.2022 - sinc. Oracle (29.12.2021)
  --Laura 17.11.2021 - sinc Oracle (17.11.2021)
  --Laura 10.11.2021 - sinc Oracle (10.11.2021)
  --Laura 22.09.2021 - sinc Oracle (21.09.2021)
  --Adina 15.03.2021 - prc_al_refresh
  aInitializari := TO_NUMBER(CURRENT_SETTING('PKG_PLANCONTURI.INITIALIZARI', TRUE), '999999999999999999');
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT (521);

  SELECT COALESCE(CODPARINTE, 0) INTO aCODPARINTE FROM TMP_NCONT;

  IF aCodParinte &gt; 0 THEN
    BEGIN
      SELECT COUNT(CodCont) INTO NrCopii FROM NCONT WHERE CodParinte = aCodParinte;
    EXCEPTION WHEN OTHERS THEN
      NrCopii := 0;
    END;

    BEGIN
      SELECT AnStart * 12 + LunaStart INTO aAnLuna FROM TMP_NCONT1 LIMIT 1;
    EXCEPTION WHEN OTHERS THEN
      aAnLuna := 0;
    END;
  END IF;

  IF Operation = 0 THEN
    SELECT CodCont INTO RecId FROM TMP_NCONT;

    UPDATE NCONT
    SET
     ( Simbol,Clasa,Den_cont,Name,TipCont,VizibilBalanta,BalantaSintetica,Nivel,CodParinte, SimbolSitFin, ANINACTIV, LUNAINACTIV, CODSAFT, TAXCODE, IMPOZIT, taxtype )
      =
     ( SELECT Simbol,Clasa,Den_cont,Name,TipCont,VizibilBalanta,BalantaSintetica,Nivel,CodParinte, SimbolSitFin, ANINACTIV, LUNAINACTIV, CODSAFT, TAXCODE, IMPOZIT, taxtype
      FROM TMP_NCONT)
    WHERE CodCont = RecId;

    FOR V_REC IN (SELECT * FROM NCONT1 WHERE CodCont = RecId AND CodCont1 NOT IN (SELECT CodCont1 FROM TMP_NCONT1))
    LOOP
      DELETE FROM NCONT1SUB WHERE CODCONT1 = V_REC.CODCONT1;
      DELETE FROM NCONT1    WHERE CODCONT1 = V_REC.CODCONT1;
    END LOOP;


    FOR V_REC IN (SELECT CODCONT1, NrAnalitice, ContTransfD, ContTransfC, ContTransfCDim,
                         CONTSECUNDARG, CONTSECUNDARGO, CODCENTRU, CODCENTRUS, CODCENTRUSG,
                         CODCENTRUSGO, TipInchidere, ContInkidSold, Participatiune, Sincronizare,
                         ContSecundar, ContTertiar, anstart, lunastart, codanalizanod
                  FROM TMP_NCONT1
                  WHERE CodCont1 &lt; 0
                 )
    LOOP
      SELECT NEXTVAL('SEQ_NCONT1_CODCONT1') INTO VCOD;

      UPDATE TMP_NCONT1SUB SET CODCONT1 = VCOD WHERE CODCONT1 = V_REC.CODCONT1;

      INSERT INTO NCONT1 (CodCont1, CodCont, NrAnalitice, ContTransfD, ContTransfC, ContTransfCDim, CONTSECUNDARG, CONTSECUNDARGO, CODCENTRU, CODCENTRUS, CODCENTRUSG,
                  CODCENTRUSGO, TipInchidere, ContInkidSold, Participatiune, Sincronizare, ContSecundar, ContTertiar, anstart, lunastart, codanalizanod)
      VALUES (VCOD, RecId, V_REC.NrAnalitice, V_REC.ContTransfD, V_REC.ContTransfC, V_REC.ContTransfCDim, V_REC.CONTSECUNDARG, V_REC.CONTSECUNDARGO, V_REC.CODCENTRU, V_REC.CODCENTRUS,
           V_REC.CODCENTRUSG, V_REC.CODCENTRUSGO, V_REC.TipInchidere, V_REC.ContInkidSold, V_REC.Participatiune, V_REC.Sincronizare, V_REC.ContSecundar, V_REC.ContTertiar, V_REC.anstart,
           V_REC.lunastart, V_REC.codanalizanod);
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_NCONT1 WHERE COALESCE(CodCont1, -1) &gt; 0 ORDER BY CodCont1) LOOP
      UPDATE NCONT1
      SET NRANALITICE    = v_rec.NrAnalitice,
          ContTransfD    = v_rec.ContTransfD,
          ContTransfC    = v_rec.ContTransfC,
          ContTransfCDim = v_rec.ContTransfCDim,
          TipInchidere   = v_rec.TipInchidere,
          CONTSECUNDARG  = v_rec.CONTSECUNDARG,
          CONTSECUNDARGO = v_rec.CONTSECUNDARGO,
          CODCENTRU      = v_rec.CODCENTRU,
          CODCENTRUS     = v_rec.CODCENTRUS,
          CODCENTRUSG    = v_rec.CODCENTRUSG,
          CODCENTRUSGO   = v_rec.CODCENTRUSGO,
          ContInkidSold  = v_rec.ContInkidSold,
          Participatiune = v_rec.Participatiune,
          Sincronizare   = v_rec.Sincronizare,
          ContSecundar   = v_rec.ContSecundar,
          ContTertiar    = v_rec.ContTertiar,
          codanalizanod  = V_REC.codanalizanod
      WHERE CodCont1     = v_rec.CodCont1;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_NCONT1SUB) LOOP
      IF V_REC.COD &lt; 0 THEN
        INSERT INTO NCONT1SUB (COD, CODCONT1, SUBUNITATEA, TIPINCHIDERE)
        VALUES (NEXTVAL('SEQ_NCONT1SUB_COD'), V_REC.CODCONT1, V_REC.SUBUNITATEA, V_REC.TIPINCHIDERE);
      ELSE
        UPDATE NCONT1SUB
        SET SUBUNITATEA  = V_REC.SUBUNITATEA,
            TIPINCHIDERE = V_REC.TIPINCHIDERE
        WHERE COD = V_REC.COD;
      END IF;
    END LOOP;

    SELECT ANINITIAL, LUNAINITIALA INTO ANI, LUNAI FROM FIRMALUNI;

    IF (aInitializari = 1) OR (ANI * 12 + LUNAI = GetAnLunaLucru()) THEN
      FOR V_REC IN (SELECT * FROM TMP_NCONTSOLD) LOOP
        IF V_REC.CODCONTSOLD &lt; 0 THEN
          SELECT NEXTVAL('SEQ_NCONTSOLD_CODCONTSOLD') INTO aCOD;

          INSERT INTO NCONTSOLD (CodContSold, SoldID, SoldIC, SoldVID, SoldVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP, CodCont, An, Luna)
          VALUES (aCOD, V_REC.SoldID, V_REC.SoldIC, V_REC.SoldVID, V_REC.SoldVIC, V_REC.SOLDI_IFRS, V_REC.SOLDVI_IFRS, V_REC.SOLDI_GRUP, V_REC.SOLDVI_GRUP, RecId, V_REC.An, V_REC.Luna);

          UPDATE TMP_NCONTSOLDSUB SET CODCONTSOLD = aCOD WHERE CODCONTSOLD = V_REC.CODCONTSOLD;
        ELSE
          UPDATE NCONTSOLD
          SET SoldID        = V_REC.SOLDID,
              SoldIC        = V_REC.SOLDIC,
              SoldVID       = V_REC.SOLDVID,
              SoldVIC       = V_REC.SOLDVIC,
              SOLDI_IFRS    = V_REC.SOLDI_IFRS,
              SOLDVI_IFRS   = V_REC.SOLDVI_IFRS,
              SOLDI_GRUP    = V_REC.SOLDI_GRUP,
              SOLDVI_GRUP   = V_REC.SOLDVI_GRUP
          WHERE CODCONTSOLD = V_REC.CODCONTSOLD;
        END IF;
      END LOOP;

      FOR V_REC IN (SELECT * FROM TMP_NCONTRUL) LOOP
        IF V_REC.CODCONTRUL &lt; 0 THEN
          SELECT NEXTVAL('SEQ_NCONTRUL_CODCONTRUL') INTO aCOD;

          INSERT INTO NCONTRUL (CodContRul, RulajPD, RulajPC, CodCont, RulajCD, RulajCC, RulajVPD, RulajVPC, RulajVCD, RulajVCC, RULAJP_IFRS, RULAJVP_IFRS, RULAJC_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJVP_GRUP, RULAJC_GRUP, RULAJVC_GRUP, An, Luna)
          VALUES (aCOD, V_REC.RulajPD, V_REC.RulajPC, RecId, V_REC.RulajCD, V_REC.RulajCC, V_REC.RulajVPD, V_REC.RulajVPC, V_REC.RulajVCD, V_REC.RulajVCC, V_REC.RULAJP_IFRS, V_REC.RULAJVP_IFRS, V_REC.RULAJC_IFRS, V_REC.RULAJVC_IFRS, V_REC.RULAJP_GRUP, V_REC.RULAJVP_GRUP, V_REC.RULAJC_GRUP, V_REC.RULAJVC_GRUP, V_REC.An, V_REC.Luna);

          UPDATE TMP_NCONTRULSUB SET CODCONTRUL = aCOD WHERE CODCONTRUL = V_REC.CODCONTRUL;
        ELSE
          UPDATE NCONTRUL
          SET RulajPD      = V_REC.RULAJPD,
              RulajPC      = V_REC.RULAJPC,
              RulajVPD     = V_REC.RULAJVPD,
              RulajVPC     = V_REC.RULAJVPC,
              RULAJP_IFRS  = V_REC.RULAJP_IFRS,
              RULAJVP_IFRS = V_REC.RULAJVP_IFRS,
              RULAJC_IFRS  = V_REC.RULAJC_IFRS,
              RULAJVC_IFRS = V_REC.RULAJVC_IFRS,
              RULAJP_GRUP  = V_REC.RULAJP_GRUP,
              RULAJVP_GRUP = V_REC.RULAJVP_GRUP,
              RULAJC_GRUP  = V_REC.RULAJC_GRUP,
              RULAJVC_GRUP = V_REC.RULAJVC_GRUP
          WHERE CODCONTRUL = V_REC.CODCONTRUL;
        END IF;
      END LOOP;

      FOR V_REC IN (SELECT * FROM TMP_NCONTSOLDSUB) LOOP
        IF V_REC.CODCONTSOLDSUB &lt; 0 THEN
          INSERT INTO NCONTSOLDSUB (CODCONTSOLDSUB, CODCONTSOLD, SUBUNITATEA, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP)
          VALUES (NEXTVAL('SEQ_NCONTSOLDSUB_CODSOLDSUB'), V_REC.CODCONTSOLD, V_REC.SUBUNITATEA, V_REC.SOLDID, V_REC.SOLDIC, V_REC.SOLDVID, V_REC.SOLDVIC, V_REC.SOLDI_IFRS, V_REC.SOLDVI_IFRS, V_REC.SOLDI_GRUP, V_REC.SOLDVI_GRUP);
        ELSE
          UPDATE NCONTSOLDSUB
          SET SOLDID           = V_REC.SOLDID,
              SOLDIC           = V_REC.SOLDIC,
              SOLDVID          = V_REC.SOLDVID,
              SOLDVIC          = V_REC.SOLDVIC,
              SOLDI_IFRS       = V_REC.SOLDI_IFRS,
              SOLDVI_IFRS      = V_REC.SOLDVI_IFRS,
              SOLDI_GRUP       = V_REC.SOLDI_GRUP,
              SOLDVI_GRUP      = V_REC.SOLDVI_GRUP
          WHERE CODCONTSOLDSUB = V_REC.CODCONTSOLDSUB;
        END IF;
      END LOOP;

      FOR V_REC IN (SELECT RS.*, R.CODCONT FROM TMP_NCONTRULSUB RS, NCONTRUL R  WHERE RS.CODCONTRUL = R.CODCONTRUL)
      LOOP
        IF V_REC.CODCONTRULSUB &lt; 0 THEN
          INSERT INTO NCONTRULSUB (CODCONTRULSUB, CODCONTRUL, SUBUNITATEA, RULAJPD, RULAJPC, RULAJVPD, RULAJVPC, RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP)
          VALUES (NEXTVAL('SEQ_NCONTRULSUB_CODRULSUB'), V_REC.CODCONTRUL, V_REC.SUBUNITATEA, V_REC.RULAJPD, V_REC.RULAJPC, V_REC.RULAJVPD, V_REC.RULAJVPC, V_REC.RULAJP_IFRS, V_REC.RULAJC_IFRS, V_REC.RULAJVP_IFRS, V_REC.RULAJVC_IFRS, V_REC.RULAJP_GRUP, V_REC.RULAJC_GRUP, V_REC.RULAJVP_GRUP, V_REC.RULAJVC_GRUP);
        ELSE
          UPDATE NCONTRULSUB
          SET RULAJPD         = V_REC.RULAJPD,
              RULAJPC         = V_REC.RULAJPC,
              RULAJVPD        = V_REC.RULAJVPD,
              RULAJVPC        = V_REC.RULAJVPC,
              RULAJP_IFRS     = V_REC.RULAJP_IFRS,
              RULAJC_IFRS     = V_REC.RULAJC_IFRS,
              RULAJVP_IFRS    = V_REC.RULAJVP_IFRS,
              RULAJVC_IFRS    = V_REC.RULAJVC_IFRS,
              RULAJP_GRUP     = V_REC.RULAJP_GRUP,
              RULAJC_GRUP     = V_REC.RULAJC_GRUP,
              RULAJVP_GRUP    = V_REC.RULAJVP_GRUP,
              RULAJVC_GRUP    = V_REC.RULAJVC_GRUP
          WHERE CODCONTRULSUB = V_REC.CODCONTRULSUB;
        END IF;
      END LOOP;
    END IF;
  ELSE
    SELECT NEXTVAL('SEQ_NCONT_CODCONT') INTO RecId;
    PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('NCONT', RecId);

    INSERT INTO  NCONT ( CodCont,Simbol,Clasa,Den_cont,Name,TipCont,VizibilBalanta,BalantaSintetica,Nivel,CodParinte, SimbolSitFin, ANINACTIV, LUNAINACTIV,CODSAFT, TAXCODE, IMPOZIT,taxtype )
    ( SELECT RecId, Simbol, Clasa, Den_cont, Name, TipCont, VizibilBalanta, BalantaSintetica, Nivel, CodParinte, SimbolSitFin, ANINACTIV, LUNAINACTIV,CODSAFT, TAXCODE, IMPOZIT,taxtype
    FROM TMP_NCONT);

    FOR V_REC IN (SELECT CODCONT1, NrAnalitice, ContTransfD, ContTransfC, ContTransfCDim,
                         CONTSECUNDARG, CONTSECUNDARGO, CODCENTRU, CODCENTRUS, CODCENTRUSG,
                         CODCENTRUSGO, TipInchidere, ContInkidSold, Participatiune, Sincronizare,
                         ContSecundar, ContTertiar, anstart, lunastart, codanalizanod
                  FROM TMP_NCONT1 WHERE CodCont1 &lt; 0
                 )
    LOOP
      SELECT NEXTVAL('SEQ_NCONT1_CODCONT1') INTO VCOD;

      UPDATE TMP_NCONT1SUB SET CODCONT1 = VCOD WHERE CODCONT1 = V_REC.CODCONT1;

      INSERT INTO NCONT1 (CodCont1, CodCont, NrAnalitice, ContTransfD, ContTransfC, ContTransfCDim, CONTSECUNDARG, CONTSECUNDARGO, CODCENTRU, CODCENTRUS, CODCENTRUSG, CODCENTRUSGO,
                  TipInchidere, ContInkidSold, Participatiune, Sincronizare, ContSecundar, ContTertiar, anstart, lunastart, codanalizanod)
      VALUES (VCOD, RecId, V_REC.NrAnalitice, V_REC.ContTransfD, V_REC.ContTransfC, V_REC.ContTransfCDim, V_REC.CONTSECUNDARG, V_REC.CONTSECUNDARGO, V_REC.CODCENTRU, V_REC.CODCENTRUS,
             V_REC.CODCENTRUSG, V_REC.CODCENTRUSGO, V_REC.TipInchidere, V_REC.ContInkidSold, V_REC.Participatiune, V_REC.Sincronizare, V_REC.ContSecundar, V_REC.ContTertiar,
             V_REC.anstart, V_REC.lunastart, V_REC.codanalizanod);
    END LOOP;

    INSERT INTO NCONT1SUB (COD, CODCONT1, SUBUNITATEA, TIPINCHIDERE)
    SELECT NEXTVAL('SEQ_NCONT1SUB_COD'), CODCONT1, SUBUNITATEA, TIPINCHIDERE
    FROM TMP_NCONT1SUB;

    IF (aCodParinte &gt; 0) AND (NrCopii = 0) THEN
      BEGIN
        UPDATE NCONT1 NC1
        SET ContSecundar = NULL
              where NC1.codcont = aCodparinte and aAnLuna BETWEEN nc1.alstart AND nc1.alstop;
      EXCEPTION WHEN OTHERS THEN
        NULL;
      END;
    END IF;

    SELECT ANINITIAL, LUNAINITIALA INTO ANI, LUNAI FROM FIRMALUNI;

    IF (aInitializari = 1) OR (ANI * 12 + LUNAI = GetAnLunaLucru()) THEN
      FOR V_REC IN (SELECT * FROM TMP_NCONTSOLD) LOOP
        SELECT NEXTVAL('SEQ_NCONTSOLD_CODCONTSOLD') INTO aCOD;

        INSERT INTO NCONTSOLD (CodContSold, SoldID, SoldIC, SoldVID, SoldVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP, CodCont, An, Luna)
        VALUES (aCOD, V_REC.SoldID, V_REC.SoldIC, V_REC.SoldVID, V_REC.SoldVIC, V_REC.SOLDI_IFRS, V_REC.SOLDVI_IFRS, V_REC.SOLDI_GRUP, V_REC.SOLDVI_GRUP, RecId, V_REC.An, V_REC.Luna);

        UPDATE TMP_NCONTSOLDSUB SET CODCONTSOLD = aCOD WHERE CODCONTSOLD = V_REC.CODCONTSOLD;
      END LOOP;

      FOR V_REC IN (SELECT * FROM TMP_NCONTRUL) LOOP
        SELECT NEXTVAL('SEQ_NCONTRUL_CODCONTRUL') INTO aCOD;

        INSERT INTO NCONTRUL (CodContRul, RulajPD, RulajPC, CodCont, RulajCD, RulajCC, RulajVPD, RulajVPC, RulajVCD, RulajVCC, RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP, An, Luna)
        VALUES (aCOD, V_REC.RulajPD, V_REC.RulajPC, RecId, V_REC.RulajCD, V_REC.RulajCC, V_REC.RulajVPD, V_REC.RulajVPC, V_REC.RulajVCD, V_REC.RulajVCC, V_REC.RULAJP_IFRS, V_REC.RULAJC_IFRS, V_REC.RULAJVP_IFRS, V_REC.RULAJVC_IFRS, V_REC.RULAJP_GRUP, V_REC.RULAJC_GRUP, V_REC.RULAJVP_GRUP, V_REC.RULAJVC_GRUP, V_REC.An, V_REC.Luna);

        UPDATE TMP_NCONTRULSUB SET CODCONTRUL = aCOD WHERE CODCONTRUL = V_REC.CODCONTRUL;
      END LOOP;

      INSERT INTO NCONTSOLDSUB (CODCONTSOLDSUB, CODCONTSOLD, SUBUNITATEA, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP)
      SELECT NEXTVAL('SEQ_NCONTSOLDSUB_CODSOLDSUB'), CODCONTSOLD, SUBUNITATEA, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP
      FROM TMP_NCONTSOLDSUB;

      INSERT INTO NCONTRULSUB (CODCONTRULSUB, CODCONTRUL, SUBUNITATEA, RULAJPD, RULAJPC, RULAJVPD, RULAJVPC, RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP)
      SELECT NEXTVAL('SEQ_NCONTRULSUB_CODRULSUB'), CODCONTRUL, SUBUNITATEA, RULAJPD, RULAJPC, RULAJVPD, RULAJVPC, RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP
      FROM TMP_NCONTRULSUB;
    END IF;
  END IF;

  IF aInitializari = 1 AND ACODPARINTE &gt; 0 THEN
    PERFORM PKG_PLANCONTURI_UPDATE_SOLD_PARINTE(aCODPARINTE);
    PERFORM PKG_PLANCONTURI_UPDATE_SOLD_SUB_PARINTE(aCODPARINTE);
    PERFORM PKG_PLANCONTURI_UPDATE_RULAJP_PARINTE(aCODPARINTE);
    PERFORM PKG_PLANCONTURI_UPDATE_RULAJP_SUB_PARINTE(aCODPARINTE);
  END IF;

  CALL PRC_AL_REFRESH('ncont1',  RecId);
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS(521);
  PERFORM   NotifyModif(Operation, RecId, 'NCONT');

  SELECT ANINITIAL, LUNAINITIALA INTO ANI, LUNAI FROM FIRMALUNI;

  IF aCODPARINTE &gt; 0 AND GetAnLunaLucru() &gt; ANI * 12 + LUNAI THEN
    DELETE FROM TMP_NCONT_LUNA_1;

    PERFORM PKG_INCHIDERI_MAKE_NCONT_LUNA('TMP_NCONT_LUNA_1', GetAnLucru(), GetLunaLucru());

    SELECT DISTINCT ANSTART, LUNASTART INTO ANINCEPUTREPARTIZARI, LUNAINCEPUTREPARTIZARI
    FROM NCONT1
    WHERE CODCONT IN (SELECT CODCONT FROM NCONT WHERE CODPARINTE = aCODPARINTE)
      AND ANSTART * 12 + LUNASTART = (SELECT MIN(ANSTART * 12 + LUNASTART)
                                      FROM NCONT1
                                      WHERE CODCONT IN (SELECT CODCONT FROM NCONT WHERE CODPARINTE = aCODPARINTE)
                                     );

    IF ANINCEPUTREPARTIZARI = GetAnLucru() AND LUNAINCEPUTREPARTIZARI = GetLunaLucru() THEN
      FOR V_RECPARINTE IN (SELECT * FROM TMP_NCONT_LUNA_1 WHERE CODCONT = aCODPARINTE) LOOP
        IF V_RECPARINTE.NRANALITICE = 0 THEN
          UPDATE NCONTREP
          SET AN   = COALESCE(ANINCEPUTREPARTIZARI, 0),
              LUNA = COALESCE(LUNAINCEPUTREPARTIZARI, 0)
          WHERE CODCONT = aCODPARINTE;

          FOR V_RECANALITICE IN (SELECT * FROM NCONT WHERE CODPARINTE = aCODPARINTE) LOOP
            DELETE FROM NCONTSOLD
            WHERE CODCONT = V_RECANALITICE.CODCONT
              AND AN = (SELECT PKG_PLANCONTURI_GET_AN_SOLDINI.WME_RESULT FROM PKG_PLANCONTURI_GET_AN_SOLDINI(NULL, NULL))
              AND LUNA = 1;

            DELETE FROM NCONTRUL WHERE CODCONT = V_RECANALITICE.CODCONT AND AN = GetAnLucru() AND LUNA = GetLunaLucru();
          END LOOP;
        ELSE
          FOR V_RECANALITICE IN (SELECT * FROM NCONT WHERE CODPARINTE = aCODPARINTE) LOOP
            SELECT COUNT(*) INTO CONTUL_EXISTA_IN_LUNA FROM TMP_NCONT_LUNA_1 WHERE CODCONT = V_RECANALITICE.CODCONT;

            IF (V_RECPARINTE.NRANALITICE &gt;= 1)
               AND
               ((COALESCE(V_RECPARINTE.SOLDID  , 0) &lt;&gt; 0 OR
                 COALESCE(V_RECPARINTE.SOLDIC  , 0) &lt;&gt; 0 OR
                 COALESCE(V_RECPARINTE.SOLDVID , 0) &lt;&gt; 0 OR
                 COALESCE(V_RECPARINTE.SOLDVIC , 0) &lt;&gt; 0 OR
                 COALESCE(V_RECPARINTE.RULAJPD , 0) &lt;&gt; 0 OR
                 COALESCE(V_RECPARINTE.RULAJPC , 0) &lt;&gt; 0 OR
                 COALESCE(V_RECPARINTE.RULAJVPD, 0) &lt;&gt; 0 OR
                 COALESCE(V_RECPARINTE.RULAJVPC, 0) &lt;&gt; 0
                )
               )
            THEN
              IF CONTUL_EXISTA_IN_LUNA = 1 THEN
                SELECT COUNT(*) INTO NR FROM NCONTREP WHERE CODCONT = aCODPARINTE;

                IF NR = 0 THEN
                  INSERT INTO NCONTREP (CODCONTREP, CODCONT, AN, LUNA)
                  VALUES (NEXTVAL('SEQ_NCONTREP_CODCONTREP'), aCODPARINTE, ANINCEPUTREPARTIZARI, LUNAINCEPUTREPARTIZARI);
                ELSE
                  UPDATE NCONTREP
                  SET AN   = ANINCEPUTREPARTIZARI,
                      LUNA = LUNAINCEPUTREPARTIZARI
                  WHERE CODCONT = aCODPARINTE;
                END IF;

                SELECT COUNT(*) INTO NR FROM NCONTSOLD
                WHERE CODCONT = V_RECANALITICE.CODCONT
                  AND AN   = (SELECT PKG_PLANCONTURI_GET_AN_SOLDINI.WME_RESULT FROM PKG_PLANCONTURI_GET_AN_SOLDINI(NULL, NULL))
                  AND LUNA = 1;

                IF NR = 0 THEN
                  INSERT INTO NCONTSOLD (CODCONTSOLD, CODCONT, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP, AN, LUNA)
                  VALUES (NEXTVAL('SEQ_NCONTSOLD_CODCONTSOLD'), V_RECANALITICE.CODCONT, CASE WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.SOLDID ELSE 0 END, CASE WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.SOLDIC ELSE 0 END, CASE WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.SOLDVID ELSE 0 END, CASE WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.SOLDVIC ELSE 0 END, CASE WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.SOLDI_IFRS ELSE 0 END, CASE WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.SOLDVI_IFRS ELSE 0 END, CASE WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.SOLDI_GRUP ELSE 0 END, CASE WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.SOLDVI_GRUP ELSE 0 END, (SELECT PKG_PLANCONTURI_GET_AN_SOLDINI.WME_RESULT FROM PKG_PLANCONTURI_GET_AN_SOLDINI(NULL, NULL)), 1);
                ELSE
                  UPDATE NCONTSOLD
                  SET SOLDID      = V_RECPARINTE.SOLDID,
                      SOLDIC      = V_RECPARINTE.SOLDIC,
                      SOLDVID     = V_RECPARINTE.SOLDVID,
                      SOLDVIC     = V_RECPARINTE.SOLDVIC,
                      SOLDI_IFRS  = V_RECPARINTE.SOLDI_IFRS,
                      SOLDVI_IFRS = V_RECPARINTE.SOLDVI_IFRS,
                      SOLDI_GRUP  = V_RECPARINTE.SOLDI_GRUP,
                      SOLDVI_GRUP = V_RECPARINTE.SOLDVI_GRUP
                  WHERE V_RECPARINTE.NRANALITICE = 1
                    AND CODCONT = V_RECANALITICE.CODCONT
                    AND AN   = (SELECT PKG_PLANCONTURI_GET_AN_SOLDINI.WME_RESULT FROM PKG_PLANCONTURI_GET_AN_SOLDINI(NULL, NULL))
                    AND LUNA = 1;
                END IF;

if V_RECPARINTE.NRANALITICE = 1 then for V_REC_SOLD in ( --preiau solduri pe subunitati de la parinte
select
  SS.*
from
  NCONTSOLD S,
  NCONTSOLDSUB SS
where
  CODCONT = V_RECPARINTE.CODCONT
  and AN = (
  select
    PKG_PLANCONTURI_GET_AN_SOLDINI.WME_RESULT
  from
    PKG_PLANCONTURI_GET_AN_SOLDINI(null, null))
  and LUNA = 1
  and SS.CODCONTSOLD = S.CODCONTSOLD ) loop begin
select
  CODCONTSOLD
into
  aCODCONTSOLD
from
  NCONTSOLD
where
  CODCONT = V_RECANALITICE.CODCONT
  and AN = (
  select
    PKG_PLANCONTURI_GET_AN_SOLDINI.WME_RESULT
  from
    PKG_PLANCONTURI_GET_AN_SOLDINI(null,
    null))
  and LUNA = 1;

exception
when others then aCODCONTSOLD := 0;
end;

if coalesce(aCODCONTSOLD, 0) &lt;&gt; 0 then
update
  NCONTSOLDSUB
set
  SOLDID = V_REC_SOLD.SOLDID,
  SOLDIC = V_REC_SOLD.SOLDIC,
  SOLDVID = V_REC_SOLD.SOLDVID,
  SOLDVIC = V_REC_SOLD.SOLDVIC,
  SOLDI_IFRS = V_REC_SOLD.SOLDI_IFRS,
  SOLDVI_IFRS = V_REC_SOLD.SOLDVI_IFRS,
  SOLDI_GRUP = V_REC_SOLD.SOLDI_GRUP,
  SOLDVI_GRUP = V_REC_SOLD.SOLDVI_GRUP
where
  CODCONTSOLD = aCODCONTSOLD
  and SUBUNITATEA = V_REC_SOLD.SUBUNITATEA ;

if not found then
insert
  into
  NCONTSOLDSUB ( CODCONTSOLDSUB, CODCONTSOLD, SUBUNITATEA, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP )
values ( NEXTVAL('SEQ_NCONTSOLDSUB_CODSOLDSUB'), aCODCONTSOLD, V_REC_SOLD.SUBUNITATEA, V_REC_SOLD.SOLDID, V_REC_SOLD.SOLDIC, V_REC_SOLD.SOLDVID, V_REC_SOLD.SOLDVIC, V_REC_SOLD.SOLDI_IFRS, V_REC_SOLD.SOLDVI_IFRS, V_REC_SOLD.SOLDI_GRUP, V_REC_SOLD.SOLDVI_GRUP );
end if;
end if;
end loop;
end if;





                SELECT COUNT(*) INTO NR FROM NCONTREPSOLD WHERE CODCONT = V_RECANALITICE.CODCONT;

                IF NR = 0 THEN
                  INSERT INTO NCONTREPSOLD (CODCONTREPSOLD, CODCONT, CODPARINTE, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP)
                  VALUES (NEXTVAL('SEQ_NCONTREPSOLD_CODCONTREPS'), V_RECANALITICE.CODCONT, aCODPARINTE, CASE WHEN aInitializari = 1 THEN (SELECT SOLDID FROM NCONTSOLD WHERE CODCONT = V_RECANALITICE.CODCONT AND LUNA = 1 AND AN = (SELECT PKG_PLANCONTURI_GET_AN_SOLDINI.WME_RESULT FROM PKG_PLANCONTURI_GET_AN_SOLDINI(NULL, NULL))) WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.SOLDID ELSE 0 END, CASE WHEN aInitializari = 1 THEN (SELECT SOLDIC FROM NCONTSOLD WHERE CODCONT = V_RECANALITICE.CODCONT AND LUNA = 1 AND AN = (SELECT PKG_PLANCONTURI_GET_AN_SOLDINI.WME_RESULT FROM PKG_PLANCONTURI_GET_AN_SOLDINI(NULL, NULL))) WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.SOLDIC ELSE 0 END, CASE WHEN aInitializari = 1 THEN (SELECT SOLDVID FROM NCONTSOLD WHERE CODCONT = V_RECANALITICE.CODCONT AND LUNA = 1 AND AN = (SELECT PKG_PLANCONTURI_GET_AN_SOLDINI.WME_RESULT FROM PKG_PLANCONTURI_GET_AN_SOLDINI(NULL, NULL))) WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.SOLDVID ELSE 0 END, CASE WHEN aInitializari = 1 THEN (SELECT SOLDVIC FROM NCONTSOLD WHERE CODCONT = V_RECANALITICE.CODCONT AND LUNA = 1 AND AN = (SELECT PKG_PLANCONTURI_GET_AN_SOLDINI.WME_RESULT FROM PKG_PLANCONTURI_GET_AN_SOLDINI(NULL, NULL))) WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.SOLDVIC ELSE 0 END, CASE WHEN aInitializari = 1 THEN (SELECT SOLDI_IFRS FROM NCONTSOLD WHERE CODCONT = V_RECANALITICE.CODCONT AND LUNA = 1 AND AN = (SELECT PKG_PLANCONTURI_GET_AN_SOLDINI.WME_RESULT FROM PKG_PLANCONTURI_GET_AN_SOLDINI(NULL, NULL))) WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.SOLDI_IFRS ELSE 0 END, CASE WHEN aInitializari = 1 THEN (SELECT SOLDVI_IFRS FROM NCONTSOLD WHERE CODCONT = V_RECANALITICE.CODCONT AND LUNA = 1 AND AN = (SELECT PKG_PLANCONTURI_GET_AN_SOLDINI.WME_RESULT FROM PKG_PLANCONTURI_GET_AN_SOLDINI(NULL, NULL))) WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.SOLDVI_IFRS ELSE 0 END, CASE WHEN aInitializari = 1 THEN (SELECT SOLDI_GRUP FROM NCONTSOLD WHERE CODCONT = V_RECANALITICE.CODCONT AND LUNA = 1 AND AN = (SELECT PKG_PLANCONTURI_GET_AN_SOLDINI.WME_RESULT FROM PKG_PLANCONTURI_GET_AN_SOLDINI(NULL, NULL))) WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.SOLDI_GRUP ELSE 0 END, CASE WHEN aInitializari = 1 THEN (SELECT SOLDVI_GRUP FROM NCONTSOLD WHERE CODCONT = V_RECANALITICE.CODCONT AND LUNA = 1 AND AN = (SELECT PKG_PLANCONTURI_GET_AN_SOLDINI.WME_RESULT FROM PKG_PLANCONTURI_GET_AN_SOLDINI(NULL, NULL))) WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.SOLDVI_GRUP ELSE 0 END);
                ELSE
                  UPDATE NCONTREPSOLD
                  SET SOLDID      = V_RECPARINTE.SOLDID,
                      SOLDIC      = V_RECPARINTE.SOLDIC,
                      SOLDVID     = V_RECPARINTE.SOLDVID,
                      SOLDVIC     = V_RECPARINTE.SOLDVIC,
                      SOLDI_IFRS  = V_RECPARINTE.SOLDI_IFRS,
                      SOLDVI_IFRS = V_RECPARINTE.SOLDVI_IFRS,
                      SOLDI_GRUP  = V_RECPARINTE.SOLDI_GRUP,
                      SOLDVI_GRUP = V_RECPARINTE.SOLDVI_GRUP
                  WHERE V_RECPARINTE.NRANALITICE = 1
                    AND CODCONT = V_RECANALITICE.CODCONT;
                END IF;

                IF V_RECPARINTE.NRANALITICE = 1 THEN
                  BEGIN
                    SELECT CODCONTREPSOLD INTO ACODCONTREPSOLD FROM NCONTREPSOLD WHERE CODCONT = V_RECANALITICE.CODCONT;
                  EXCEPTION WHEN OTHERS THEN
                    aCODCONTREPSOLD := 0;
                  END;

                  IF aCODCONTREPSOLD &lt;&gt; 0 THEN
                    FOR V_REC_SOLDSUB IN (SELECT SS.* FROM NCONTSOLD S, NCONTSOLDSUB SS
                                          WHERE AN = GetAnLucru() AND LUNA = 1
                                            AND S.CODCONT = V_RECPARINTE.CODCONT
                                            AND SS.CODCONTSOLD = S.CODCONTSOLD
                                         )
                    LOOP
                      BEGIN
                        SELECT CODREPSOLDSUB INTO aCODCONTREPSOLDSUB FROM NCONTREPSOLDSUB SS WHERE SS.CODCONTREPSOLD = aCODCONTREPSOLD AND SUBUNITATEA = V_REC_SOLDSUB.SUBUNITATEA;
                      EXCEPTION WHEN OTHERS THEN
                        aCODCONTREPSOLDSUB := 0;
                      END;

                      IF aCODCONTREPSOLDSUB = 0 THEN
                        INSERT INTO NCONTREPSOLDSUB (CODREPSOLDSUB, CODCONTREPSOLD, SUBUNITATEA, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP)
                        VALUES (NEXTVAL('SEQ_NCONTREPSOLDSUB_COD'), aCODCONTREPSOLD, V_REC_SOLDSUB.SUBUNITATEA, V_REC_SOLDSUB.SOLDID, V_REC_SOLDSUB.SOLDIC, V_REC_SOLDSUB.SOLDVID, V_REC_SOLDSUB.SOLDVIC, V_REC_SOLDSUB.SOLDI_IFRS, V_REC_SOLDSUB.SOLDVI_IFRS, V_REC_SOLDSUB.SOLDI_GRUP, V_REC_SOLDSUB.SOLDVI_GRUP);
                      ELSE
                        UPDATE NCONTREPSOLDSUB
                        SET SOLDID      = V_REC_SOLDSUB.SOLDID,
                            SOLDIC      = V_REC_SOLDSUB.SOLDIC,
                            SOLDVID     = V_REC_SOLDSUB.SOLDVID,
                            SOLDVIC     = V_REC_SOLDSUB.SOLDVIC,
                            SOLDI_IFRS  = V_REC_SOLDSUB.SOLDI_IFRS,
                            SOLDVI_IFRS = V_REC_SOLDSUB.SOLDVI_IFRS,
                            SOLDI_GRUP  = V_REC_SOLDSUB.SOLDI_GRUP,
                            SOLDVI_GRUP = V_REC_SOLDSUB.SOLDVI_GRUP
                        WHERE CODREPSOLDSUB = aCODCONTREPSOLDSUB;
                      END IF;
                    END LOOP;
                  END IF;
                END IF;

                SELECT COUNT(*) INTO NR FROM NCONTRUL WHERE CODCONT = V_RECANALITICE.CODCONT AND AN = GetAnLucru() AND LUNA = GetLunaLucru();

                IF NR = 0 THEN
                  INSERT INTO NCONTRUL (CodContRul, CodCont, RulajPD, RulajPC, RulajVPD, RulajVPC, RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP, An, Luna)
                  VALUES (NEXTVAL('SEQ_NCONTRUL_CODCONTRUL'), V_RECANALITICE.CODCONT, CASE WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.RulajPD ELSE 0 END, CASE WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.RulajPC ELSE 0 END, CASE WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.RulajVPD ELSE 0 END, CASE WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.RulajVPC ELSE 0 END, CASE WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.RULAJP_IFRS ELSE 0 END, CASE WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.RULAJC_IFRS ELSE 0 END, CASE WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.RULAJVP_IFRS ELSE 0 END, CASE WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.RULAJVC_IFRS ELSE 0 END, CASE WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.RULAJP_GRUP ELSE 0 END, CASE WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.RULAJC_GRUP ELSE 0 END, CASE WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.RULAJVP_GRUP ELSE 0 END, CASE WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.RULAJVC_GRUP ELSE 0 END, GetAnLucru(), GetLunaLucru());
                ELSE
                  UPDATE NCONTRUL
                  SET RULAJPD      = V_RECPARINTE.RULAJPD,
                      RULAJPC      = V_RECPARINTE.RULAJPC,
                      RULAJVPD     = V_RECPARINTE.RULAJVPD,
                      RULAJVPC     = V_RECPARINTE.RULAJVPC,
                      RULAJP_IFRS  = V_RECPARINTE.RULAJP_IFRS,
                      RULAJC_IFRS  = V_RECPARINTE.RULAJC_IFRS,
                      RULAJVP_IFRS = V_RECPARINTE.RULAJVP_IFRS,
                      RULAJVC_IFRS = V_RECPARINTE.RULAJVC_IFRS,
                      RULAJP_GRUP  = V_RECPARINTE.RULAJP_GRUP,
                      RULAJC_GRUP  = V_RECPARINTE.RULAJC_GRUP,
                      RULAJVP_GRUP = V_RECPARINTE.RULAJVP_GRUP,
                      RULAJVC_GRUP = V_RECPARINTE.RULAJVC_GRUP
                  WHERE V_RECPARINTE.NRANALITICE = 1
                    AND CODCONT = V_RECANALITICE.CODCONT
                    AND AN = GetAnLucru()
                    AND LUNA = GetLunaLucru();
                END IF;

                SELECT COUNT(*) INTO NR FROM NCONTREPRUL WHERE CODCONT = V_RECANALITICE.CODCONT;

                IF NR = 0 THEN
                  INSERT INTO NCONTREPRUL (CODCONTREPRUL, CODCONT, CODPARINTE, RULAJPD, RULAJPC, RULAJVPD, RULAJVPC, RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP)
                  VALUES (NEXTVAL('SEQ_NCONTREPRUL_CODCONTREPRUL'), V_RECANALITICE.CODCONT, aCODPARINTE, CASE WHEN aInitializari = 1 THEN (SELECT RULAJPD FROM NCONTRUL WHERE CODCONT = V_RECANALITICE.CODCONT AND LUNA = GetLunaLucru() AND AN = GetAnLucru()) WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.RULAJPD ELSE 0 END, CASE WHEN aInitializari = 1 THEN (SELECT RULAJPC FROM NCONTRUL WHERE CODCONT = V_RECANALITICE.CODCONT AND LUNA = GetLunaLucru() AND AN = GetAnLucru()) WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.RULAJPC ELSE 0 END, CASE WHEN aInitializari = 1 THEN (SELECT RULAJVPD FROM NCONTRUL WHERE CODCONT = V_RECANALITICE.CODCONT AND LUNA = GetLunaLucru() AND AN = GetAnLucru()) WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.RULAJVPD ELSE 0 END, CASE WHEN aInitializari = 1 THEN (SELECT RULAJVPC FROM NCONTRUL WHERE CODCONT = V_RECANALITICE.CODCONT AND LUNA = GetLunaLucru() AND AN = GetAnLucru()) WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.RULAJVPC ELSE 0 END, CASE WHEN aInitializari = 1 THEN (SELECT RULAJP_IFRS FROM NCONTRUL WHERE CODCONT = V_RECANALITICE.CODCONT AND LUNA = GetLunaLucru() AND AN = GetAnLucru()) WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.RULAJP_IFRS ELSE 0 END, CASE WHEN aInitializari = 1 THEN (SELECT RULAJC_IFRS FROM NCONTRUL WHERE CODCONT = V_RECANALITICE.CODCONT AND LUNA = GetLunaLucru() AND AN = GetAnLucru()) WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.RULAJC_IFRS ELSE 0 END, CASE WHEN aInitializari = 1 THEN (SELECT RULAJVP_IFRS FROM NCONTRUL WHERE CODCONT = V_RECANALITICE.CODCONT AND LUNA = GetLunaLucru() AND AN = GetAnLucru()) WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.RULAJVP_IFRS ELSE 0 END, CASE WHEN aInitializari = 1 THEN (SELECT RULAJVC_IFRS FROM NCONTRUL WHERE CODCONT = V_RECANALITICE.CODCONT AND LUNA = GetLunaLucru() AND AN = GetAnLucru()) WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.RULAJVC_IFRS ELSE 0 END, CASE WHEN aInitializari = 1 THEN (SELECT RULAJP_GRUP FROM NCONTRUL WHERE CODCONT = V_RECANALITICE.CODCONT AND LUNA = GetLunaLucru() AND AN = GetAnLucru()) WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.RULAJP_GRUP ELSE 0 END, CASE WHEN aInitializari = 1 THEN (SELECT RULAJC_GRUP FROM NCONTRUL WHERE CODCONT = V_RECANALITICE.CODCONT AND LUNA = GetLunaLucru() AND AN = GetAnLucru()) WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.RULAJC_GRUP ELSE 0 END, CASE WHEN aInitializari = 1 THEN (SELECT RULAJVP_GRUP FROM NCONTRUL WHERE CODCONT = V_RECANALITICE.CODCONT AND LUNA = GetLunaLucru() AND AN = GetAnLucru()) WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.RULAJVP_GRUP ELSE 0 END, CASE WHEN aInitializari = 1 THEN (SELECT RULAJVC_GRUP FROM NCONTRUL WHERE CODCONT = V_RECANALITICE.CODCONT AND LUNA = GetLunaLucru() AND AN = GetAnLucru()) WHEN V_RECPARINTE.NRANALITICE = 1 THEN V_RECPARINTE.RULAJVC_GRUP ELSE 0 END);
                ELSE
                  UPDATE NCONTREPRUL
                  SET RULAJPD      = V_RECPARINTE.RULAJPD,
                      RULAJPC      = V_RECPARINTE.RULAJPC,
                      RULAJVPD     = V_RECPARINTE.RULAJVPD,
                      RULAJVPC     = V_RECPARINTE.RULAJVPC,
                      RULAJP_IFRS  = V_RECPARINTE.RULAJP_IFRS,
                      RULAJC_IFRS  = V_RECPARINTE.RULAJC_IFRS,
                      RULAJVP_IFRS = V_RECPARINTE.RULAJVP_IFRS,
                      RULAJVC_IFRS = V_RECPARINTE.RULAJVC_IFRS,
                      RULAJP_GRUP  = V_RECPARINTE.RULAJP_GRUP,
                      RULAJC_GRUP  = V_RECPARINTE.RULAJC_GRUP,
                      RULAJVP_GRUP = V_RECPARINTE.RULAJVP_GRUP,
                      RULAJVC_GRUP = V_RECPARINTE.RULAJVC_GRUP
                  WHERE V_RECPARINTE.NRANALITICE = 1
                    AND CODCONT = V_RECANALITICE.CODCONT;
                END IF;

                IF V_RECPARINTE.NRANALITICE = 1 THEN
                  BEGIN
                    SELECT CODCONTREPRUL INTO ACODCONTREPRUL FROM NCONTREPRUL WHERE CODCONT = V_RECANALITICE.CODCONT;
                  EXCEPTION WHEN OTHERS THEN
                    aCODCONTREPRUL := 0;
                  END;

                  IF aCODCONTREPRUL &lt;&gt; 0 THEN
                    FOR V_REC_SOLDSUB IN (SELECT RS.* FROM NCONTRUL R, NCONTRULSUB RS
                                          WHERE AN = GetAnLucru() AND LUNA = GetLunaLucru()
                                          AND R.CODCONT = V_RECPARINTE.CODCONT AND RS.CODCONTRUL = R.CODCONTRUL)
                    LOOP
                      BEGIN
                        SELECT CODREPRULSUB INTO aCODCONTREPRULSUB FROM NCONTREPRULSUB RS WHERE RS.CODCONTREPRUL = aCODCONTREPRUL AND SUBUNITATEA = V_REC_SOLDSUB.SUBUNITATEA;
                      EXCEPTION WHEN OTHERS THEN
                        aCODCONTREPRULSUB := 0;
                      END;

                      IF aCODCONTREPRULSUB = 0 THEN
                        INSERT INTO NCONTREPRULSUB (CODREPRULSUB, CODCONTREPRUL, SUBUNITATEA, RULAJPD, RULAJPC, RULAJVPD, RULAJVPC, RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP)
                        VALUES (NEXTVAL('SEQ_NCONTREPRULSUB_COD'), aCODCONTREPRUL, V_REC_SOLDSUB.SUBUNITATEA, V_REC_SOLDSUB.RULAJPD, V_REC_SOLDSUB.RULAJPC, V_REC_SOLDSUB.RULAJVPD, V_REC_SOLDSUB.RULAJVPC, V_REC_SOLDSUB.RULAJP_IFRS, V_REC_SOLDSUB.RULAJC_IFRS, V_REC_SOLDSUB.RULAJVP_IFRS, V_REC_SOLDSUB.RULAJVC_IFRS, V_REC_SOLDSUB.RULAJP_GRUP, V_REC_SOLDSUB.RULAJC_GRUP, V_REC_SOLDSUB.RULAJVP_GRUP, V_REC_SOLDSUB.RULAJVC_GRUP);
                      ELSE
                        UPDATE NCONTREPRULSUB
                        SET RULAJPD      = V_REC_SOLDSUB.RULAJPD,
                            RULAJPC      = V_REC_SOLDSUB.RULAJPC,
                            RULAJVPD     = V_REC_SOLDSUB.RULAJVPD,
                            RULAJVPC     = V_REC_SOLDSUB.RULAJVPC,
                            RULAJP_IFRS  = V_REC_SOLDSUB.RULAJP_IFRS,
                            RULAJC_IFRS  = V_REC_SOLDSUB.RULAJC_IFRS,
                            RULAJVP_IFRS = V_REC_SOLDSUB.RULAJVP_IFRS,
                            RULAJVC_IFRS = V_REC_SOLDSUB.RULAJVC_IFRS,
                            RULAJP_GRUP  = V_REC_SOLDSUB.RULAJP_GRUP,
                            RULAJC_GRUP  = V_REC_SOLDSUB.RULAJC_GRUP,
                            RULAJVP_GRUP = V_REC_SOLDSUB.RULAJVP_GRUP,
                            RULAJVC_GRUP = V_REC_SOLDSUB.RULAJVC_GRUP
                        WHERE CODREPRULSUB = aCODCONTREPRULSUB;
                      END IF;
                    END LOOP;
                  END IF;
                END IF;
              ELSE
                DELETE FROM NCONTSOLD
                WHERE CODCONT = V_RECANALITICE.CODCONT
                  AND AN = (SELECT PKG_PLANCONTURI_GET_AN_SOLDINI.WME_RESULT FROM PKG_PLANCONTURI_GET_AN_SOLDINI(NULL, NULL))
                  AND LUNA = 1;

                DELETE FROM NCONTRUL WHERE CODCONT = V_RECANALITICE.CODCONT AND AN = GetAnLucru() AND LUNA = GetLunaLucru();

                UPDATE NCONTREPRUL
                SET RULAJPD      = 0,
                    RULAJPC      = 0,
                    RULAJVPD     = 0,
                    RULAJVPC     = 0,
                    RULAJP_IFRS  = 0,
                    RULAJC_IFRS  = 0,
                    RULAJVP_IFRS = 0,
                    RULAJVC_IFRS = 0,
                    RULAJP_GRUP  = 0,
                    RULAJC_GRUP  = 0,
                    RULAJVP_GRUP = 0,
                    RULAJVC_GRUP = 0
                WHERE CODCONT = V_RECANALITICE.CODCONT;

                UPDATE NCONTREPSOLD
                SET SOLDID      = 0,
                    SOLDIC      = 0,
                    SOLDVID     = 0,
                    SOLDVIC     = 0,
                    SOLDI_IFRS  = 0,
                    SOLDVI_IFRS = 0,
                    SOLDI_GRUP  = 0,
                    SOLDVI_GRUP = 0
                WHERE CODCONT = V_RECANALITICE.CODCONT;
              END IF;
            END IF;
          END LOOP;
        END IF;
      END LOOP;
    END IF;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_getcursorstare1</obj_name>
  <obj_hashval>598da0128d6dd819c15829630b0cfdce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_getcursorstare1(INOUT wme_result refcursor, INOUT asetg numeric, INOUT aang numeric, INOUT aset numeric, INOUT aan numeric, INOUT acodstare1 numeric, INOUT curefreshrestse2 boolean)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  TmpCursor   REFCURSOR;
  adatacreare timestamp;
  aCodStare2  numeric;
  aUserID     numeric;
  asubunitatea numeric;
  aCodObiect  numeric;
BEGIN
  --Florin 08.08.2022 - sinc. Oracle
  --Florin 30.05.2022 - sinc. Oracle (27.05.2022)
  --Florin 31.01.2022 - sinc. Oracle (7-21.01)
  FOR v_rec IN (SELECT count( *), codstare1, codcomanda1 FROM planiflink GROUP BY codstare1, codcomanda1) LOOP
    DELETE FROM planiflink WHERE codstare1 = v_rec.codstare1 and  codcomanda1 = v_rec.codcomanda1;

    INSERT INTO planiflink(codcomanda1, codstare1)
    VALUES(v_rec.codcomanda1, v_rec.codstare1);
  END LOOP;

  FOR v_rec IN (SELECT count( *), se2.codcomanda1, se2.codstare
                FROM stareestimari2 se2
                     INNER JOIN stareestimari se ON  se.codstare = se2.codstare
                WHERE se.an = aAn and  se.saptamana = aSet
                GROUP BY se2.codcomanda1, se2.codstare
               )
  LOOP
    BEGIN
      SELECT max( codstare2) INTO aCodStare2 FROM stareestimari2 WHERE codcomanda1 = v_rec.codcomanda1 and  codstare = v_rec.codstare;
    EXCEPTION WHEN others THEN
      aCodStare2 := 0;
    END;

    IF  aCodStare2 &gt; 0 THEN
      DELETE FROM stareestimari2
      WHERE codcomanda1 = v_rec.codcomanda1 and  codstare = v_rec.codstare and  codstare2 &lt;&gt; aCodStare2;
    END IF;
  END LOOP;

  IF CuRefreshRestSE2 THEN
    UPDATE stareestimari2 se2
    SET
    restacceptat = (SELECT c1.restacceptat FROM comanda1 c1 WHERE c1.codcomanda1 = se2.codcomanda1)
    WHERE
     se2.codstare1 = aCodStare1;
  END IF;

  BEGIN
    select se.datacreare, se.subunitatea, se1.codobiect into adatacreare, asubunitatea, aCodObiect
    FROM stareestimari se
    INNER JOIN stareestimari1 se1 ON  se1.codstare = se.codstare
    WHERE
       se1.codstare1 = acodstare1;
  EXCEPTION WHEN others THEN
    aDataCreare := CURRENT_TIMESTAMP;
  END;

  DELETE from tmp_cmd;
  insert into tmp_cmd(codobiect,resta,tip)
  SELECT CODLINIECOMANDA, SUM(L.CANT) CANT, 'STORNO'
        FROM CMDLIVRLINK L
            INNER JOIN COMANDA1 S1 ON  L.CODCOMANDA1 = S1.CODCOMANDA1
            INNER JOIN COMANDA  S  ON  S1.CODCOMANDA = S.CODCOMANDA
        WHERE S.OPERAT = 1 AND coalesce(S.ANULAT,0) = 0 AND S.TIPDOC = 66 and s1.codobiect = acodobiect
        GROUP BY CODLINIECOMANDA;

  insert into tmp_cmd(codobiect,resta,tip)
  select se1.codobiect, sum(coalesce(se1.estimat,0)) cant, 'ESTINTP'
  from stareestimari1 se1
       inner join stareestimari se on se1.codstare = se.codstare
  where se.an = aAn and se.saptamana = aSet and se.AnG * 100 + se.saptamanag &lt; aAnG * 100 + aSetG
        and se.subunitatea = aSubunitatea and se1.codobiect = acodobiect
  group by se1.codobiect;

  insert into tmp_cmd(codobiect,resta,tip)
  select c1.codobiect, sum(c1.cantacceptat - COALESCE (Storno.RESTA,0)) cant, 'CMDFP'
  from STAREESTIMARI1 SE1
       INNER JOIN STAREESTIMARI SE ON SE1.CODSTARE = SE.CODSTARE
       inner join planiflink l on l.codstare1 = se1.codstare1
       inner join comanda1 c1 on c1.codcomanda1 = l.codcomanda1
       inner join comanda c on c1.codcomanda = c.codcomanda
       LEFT  JOIN TMP_CMD STORNO ON STORNO.CODOBIECT = C1.CodComanda1 AND STORNO.TIP = 'STORNO'
  where se.an = aAn and se.saptamana = aSet and se.ang = aAnG and se.saptamanag = aSetG
        and se.subunitatea = aSubunitatea and c1.codobiect = acodobiect
        and c.tipdoc = 8 and c.operat = 1 and c.anulat = 0
        and c1.termen between (SELECT wme_result FROM iso_week_to_date(NULL, aAnG, aSetG)) and add_days((SELECT wme_result FROM iso_week_to_date(NULL, aAnG, aSetG)), 6::integer)
  group by c1.codobiect;

  insert into tmp_cmd(codobiect,resta,tip)
  select se1.codobiect, sum(se2.restacceptat) cant, 'CMDFFIX'
  from STAREESTIMARI1 SE1
       INNER JOIN STAREESTIMARI SE ON SE1.CODSTARE = SE.CODSTARE
       inner join stareestimari2 se2 on se2.codstare = se.codstare and se2.codstare1 = se1.codstare1
  where se.an = aAn and se.saptamana = aSet and se.ang = aAnG and se.saptamanag = aSetG
        and se.subunitatea = aSubunitatea and se1.codobiect = acodobiect
  group by se1.codobiect;

  insert into tmp_cmd(codobiect,resta,tip)
  SELECT SE1.CODSTARE1, SUM(PC1.REST) CANT, 'RESTC'
  FROM STAREESTIMARI1 SE1
       INNER JOIN STAREESTIMARI SE ON SE1.CODSTARE = SE.CODSTARE
       INNER JOIN PRECOMANDA1 PC1 ON PC1.CODSTARE1 = SE1.CODSTARE1
       INNER JOIN PRECOMANDA PC ON PC.CODPRECOMANDA = PC1.CODPRECOMANDA
  WHERE se.an = PC.ANC and se.saptamana = PC.SAPTAMANAC
        AND SE.ANG = PC.ANG AND SE.SAPTAMANAG = PC.SAPTAMANAG
        AND PC.USERID = GETUSERID() and se1.codstare1 = acodstare1
  GROUP BY SE1.CODSTARE1;

  insert into tmp_cmd(codobiect,resta,tip)
  SELECT SE1.CODSTARE1, SUM(PC1.REST) CANT, 'RESTCA'
  FROM STAREESTIMARI1 SE1
       INNER JOIN STAREESTIMARI SE ON SE1.CODSTARE = SE.CODSTARE
       INNER JOIN PRECOMANDA1 PC1 ON PC1.CODSTARE1 = SE1.CODSTARE1
       INNER JOIN PRECOMANDA PC ON PC.CODPRECOMANDA = PC1.CODPRECOMANDA
  WHERE se.an = PC.ANC and se.saptamana = PC.SAPTAMANAC
        AND SE.ANG = PC.ANG AND SE.SAPTAMANAG = PC.SAPTAMANAG
        AND PC.USERID &lt;&gt; GETUSERID() and se1.codstare1 = acodstare1
  GROUP BY SE1.CODSTARE1;

  BEGIN
  if aAnG * 100 + aSetG = aAn * 100 + aSet then
    insert into tmp_cmd(codobiect,resta,tip)
    select c1.codobiect, sum(c1.cantacceptat - coalesce(Storno.RESTA,0)) cant, 'CMDFL'
    from comanda1 c1
         INNER JOIN comanda c on c.codcomanda = c1.codcomanda
         LEFT  JOIN TMP_CMD STORNO ON STORNO.CODOBIECT = C1.CodComanda1 AND STORNO.TIP = 'STORNO'
    where c.tipdoc = 8 and c.operat = 1 and c.anulat = 0
          and c.subunitatea = aSubunitatea
          and c1.termen &lt;= add_days((SELECT wme_result FROM iso_week_to_date(NULL, aAnG, aSetG)), 6)
          and c.datacreare &gt; adatacreare and c1.codobiect = acodobiect
          and not exists (select se2.codcomanda1 from stareestimari2 se2 where se2.codcomanda1 = c1.codcomanda1)
          and not exists (select l.codcomanda1 from planiflink l where l.codcomanda1 = c1.codcomanda1)
    group by c1.codobiect;

   OPEN TmpCursor FOR
        SELECT x.codstare, x.codstare1, x.codobiect, x.stocmin, x.stocini, x.StocPrec, x.Estimari,
               x.CmdF, -x.Necesar NECESAR, -x.Necesar * X.Pret VALNECESAR, x.StocFinal, x.Pret,
               x.StocVal, rownum, x.denumire, x.cmdfp, x.restprecmd, x.restprecmda, x.dirty, x.dirtycmdf, x.part1nec,
               x.UMSec, x.UM1, x.D1, x.D2, x.D3,
               -round( CASE
                         WHEN x.RELATIEUM1 IN (1, 7) AND  COALESCE( x.D1, 0) &lt;&gt; 0 THEN x.NECESAR / x.D1
                         WHEN x.RELATIEUM1 IN (2, 8) AND  COALESCE( x.D1, 0) * COALESCE( x.D2, 0) &lt;&gt; 0 THEN x.NECESAR / (  COALESCE( x.D1, 0) * COALESCE( x.D2, 0))
                         WHEN x.RELATIEUM1 IN (3, 9) AND  COALESCE( x.D1, 0) * COALESCE( x.D2, 0) * COALESCE( x.D3, 0) &lt;&gt; 0 THEN x.NECESAR / (  COALESCE( x.D1, 0) * COALESCE( x.D2, 0) * COALESCE( x.D3, 0))
                         WHEN x.RELATIEUM1 IN (4, 10) THEN x.NECESAR * COALESCE( x.D1, 0)
                         WHEN x.RELATIEUM1 IN (5, 11) THEN x.NECESAR * COALESCE( x.D1, 0) * COALESCE( x.D2, 0)
                         WHEN x.RELATIEUM1 IN (6, 12) THEN x.NECESAR * COALESCE( x.D1, 0) * COALESCE( x.D2, 0) * COALESCE( x.D3, 0)
                       END , 7) NECESARUM1,
               x.RelatieUM1, x.Den_UMSec, x.Den_UM1,
               CASE WHEN  -x.Necesar - x.restprecmd - x.restprecmda &lt; 0 THEN 0
                    ELSE -x.Necesar - x.restprecmd - x.restprecmda
               END  RESTNECESAR,
               x.consum
        FROM (SELECT se.codstare, se1.codstare1, se1.codobiect,
                     COALESCE( se1.stocmin, 0) STOCMIN, COALESCE( se1.stocini, 0) STOCINI,
                     CASE WHEN  aSetG = aSet and  aAnG = aAn THEN se1.StocIni
                     else coalesce(se1.stocini,0) + coalesce(CmdFP.resta,0) + coalesce(CmdFFix.resta,0) + coalesce(CmdFL.resta,0) - coalesce(EstIntP.resta,0)
                     END  STOCPREC,
                     COALESCE( se1.estimat, 0) ESTIMARI,
                     coalesce(CmdFP.resta,0) + coalesce(CmdFFix.resta,0) + coalesce(CmdFL.resta,0) CmdF,
                     CASE
                       when aSetG = aSet and aAnG = aAn then coalesce(se1.stocini,0) + coalesce(CmdFP.resta,0) + coalesce(CmdFFix.resta,0) + coalesce(CmdFL.resta,0) - coalesce(se1.estimat,0)
                       else coalesce(se1.stocini,0) + coalesce(CmdFP.resta,0) + coalesce(CmdFFix.resta,0) + coalesce(CmdFL.resta,0) - coalesce(EstIntP.resta,0) - coalesce(se1.estimat,0)
                       END  - COALESCE( se1.stocmin, 0) NECESAR,
                     CASE
                       when aSetG = aSet and aAnG = aAn then coalesce(se1.stocini,0) + coalesce(CmdFP.resta,0) + coalesce(CmdFFix.resta,0) + coalesce(CmdFL.resta,0) - coalesce(se1.estimat,0)
                       else coalesce(se1.stocini,0) + coalesce(CmdFP.resta,0) + coalesce(CmdFFix.resta,0) + coalesce(CmdFL.resta,0) - coalesce(EstIntP.resta,0) - coalesce(se1.estimat,0)
                       END  STOCFINAL,
                     COALESCE( se1.pret, 0) PRET,
                     coalesce(se1.pret,0) * (
                     CASE
                       when aSetG = aSet and aAnG = aAn then coalesce(se1.stocini,0) + coalesce(CmdFP.resta,0) + coalesce(CmdFFix.resta,0) + coalesce(CmdFL.resta,0) - coalesce(se1.estimat,0)
                       else coalesce(se1.stocini,0) + coalesce(CmdFP.resta,0) + coalesce(CmdFFix.resta,0) + coalesce(CmdFL.resta,0) - coalesce(EstIntP.resta,0) - coalesce(se1.estimat,0)
                       END )  STOCVAL,
                     obj.denumire, cmdfp.cant CMDFP, COALESCE( RESTC.CANT, 0) RESTPRECMD,
                     COALESCE( RESTCA.CANT, 0) RESTPRECMDA, se1.dirty, se1.dirtycmdf, se1.part1nec, um.codum1 UMSEC,
                     um1.codum UM1, art.d1, art.d2, art.d3, art.relatieum1, um.Den_UM1 DEN_UMSEC,
                     um1.Den_Um DEN_UM1, se1.consum
              FROM stareestimari se
                  INNER JOIN stareestimari1 se1 ON  se1.codstare = se.codstare
                  INNER JOIN nartobj        obj ON  se1.codobiect = obj.codobiect
                  INNER JOIN nart           art ON  art.codarticol = obj.codarticol
                  LEFT  JOIN num1           um  ON  um.codum = art.um and  COALESCE( um.secundara, 0) = 0
                  LEFT  JOIN num            um1 ON  um1.codum = art.um1
                  left join tmp_cmd EstIntP on EstIntP.codobiect = se1.codobiect and EstIntP.Tip = 'ESTINTP'
                  left join tmp_cmd cmdfp on cmdfp.codobiect = se1.codobiect and cmdfp.tip = 'CMDFP'
                  left join tmp_cmd cmdffix on cmdffix.codobiect = se1.codobiect and cmdffix.tip = 'CMDFFIX'
                  left join tmp_cmd cmdfl on cmdfl.codobiect = se1.codobiect and cmdfl.tip = 'CMDFL'
                  LEFT JOIN TMP_CMD RESTC ON RESTC.CODOBIECT = SE1.CODSTARE1 AND RESTC.TIP = 'RESTC'
                  LEFT JOIN TMP_CMD RESTCA ON RESTCA.CODOBIECT = SE1.CODSTARE1 AND RESTCA.TIP = 'RESTCA'
                  where se.an = aAn and se.saptamana = aSet and se.ang = aAnG and se.saptamanag = aSetG
                  and se.subunitatea = aSubunitatea and se1.codstare1 = acodstare1
                  order by obj.denumire) x;
                else
                  insert into tmp_cmd(codobiect,resta,tip)
                  select c1.codobiect, sum(c1.cantacceptat - coalesce(Storno.RESTA,0)) cant, 'CMDFL'
                  from comanda1 c1
                       INNER JOIN comanda c on c.codcomanda = c1.codcomanda
                       LEFT  JOIN TMP_CMD STORNO ON STORNO.CODOBIECT = C1.CodComanda1 AND STORNO.TIP = 'STORNO'
                  where c.tipdoc = 8 and c.operat = 1 and c.anulat = 0
                        and c.subunitatea = aSubunitatea
                        and c1.termen between (SELECT wme_result from iso_week_to_date(NULL, aAnG, aSetG)) and add_days((SELECT wme_result FROM iso_week_to_date(NULL, aAnG, aSetG)), 6::integer)
                        and c.datacreare &gt; adatacreare
                        and not exists (select se2.codcomanda1 from stareestimari2 se2 where se2.codcomanda1 = c1.codcomanda1)
                        and not exists (select l.codcomanda1 from planiflink l where l.codcomanda1 = c1.codcomanda1)
                        and c1.codobiect = acodobiect
                  group by c1.codobiect;
                  insert into tmp_cmd(codobiect,resta,tip)
                  select c1.codobiect, sum(c1.cantacceptat - coalesce(Storno.RESTA,0)) cant, 'CMDFP_PREC'
                              FROM STAREESTIMARI1 SE1
                                   INNER JOIN STAREESTIMARI  SE  ON  SE1.CODSTARE = SE.CODSTARE
                                   INNER JOIN STAREESTIMARI SES ON SES.AN = SE.AN AND SES.SAPTAMANA = SE.SAPTAMANA AND SES.ANG * 100 + SES.SAPTAMANAG &lt; SE.ANG * 100 + SE.SAPTAMANAG
                                   INNER JOIN STAREESTIMARI1 SES1 ON SES.CODSTARE = SES1.CODSTARE AND SES1.CODOBIECT = SE1.CODOBIECT
                                   inner join stareestimari2 se2 on se2.codstare = ses.codstare and se2.codstare1 = ses1.codstare1
                              WHERE se.an = aAn and  se.saptamana = aSet and  se.ang = aAnG and  se.saptamanag = aSetG and  se.subunitatea = (SELECT pkg_globals_GETSUBUNITATE.WME_RESULT FROM pkg_globals_GETSUBUNITATE(NULL,NULL))
                              GROUP BY se1.codobiect;

      insert into tmp_cmd(codobiect,resta,tip)
      select c1.codobiect, sum(c1.cantacceptat - coalesce(Storno.RESTA,0)) cant, 'CMDFL_PREC'
      from comanda1 c1
      INNER JOIN comanda c on c.codcomanda = c1.codcomanda
      LEFT  JOIN TMP_CMD STORNO ON STORNO.CODOBIECT = C1.CodComanda1 AND STORNO.TIP = 'STORNO'
      where c.tipdoc = 8 and c.operat = 1 and c.anulat = 0
        and c.subunitatea = aSubunitatea
        and c1.termen &lt; (SELECT wme_result FROM iso_week_to_date(NULL, aAnG, aSetG))
        and c.datacreare &gt; adatacreare and c1.codobiect = acodobiect
        and not exists (select se2.codcomanda1 from stareestimari2 se2 where se2.codcomanda1 = c1.codcomanda1)
        and not exists (select l.codcomanda1 from planiflink l where l.codcomanda1 = c1.codcomanda1)
        group by c1.codobiect;

      OPEN TmpCursor FOR
        SELECT x.codstare, x.codstare1, x.codobiect, x.stocmin, x.stocini, x.StocPrec, x.Estimari,
               x.CmdF, -x.Necesar NECESAR, -x.Necesar * X.Pret VALNECESAR, x.StocFinal, x.Pret,
               x.StocVal, rownum, x.denumire, x.cmdfp, x.restprecmd, x.restprecmda, x.dirty, x.dirtycmdf, x.part1nec,
               x.UMSec, x.UM1, x.D1, x.D2, x.D3,
               -round( CASE
                         WHEN x.RELATIEUM1 IN (1, 7) AND  COALESCE( x.D1, 0) &lt;&gt; 0 THEN x.NECESAR / x.D1
                         WHEN x.RELATIEUM1 IN (2, 8) AND  COALESCE( x.D1, 0) * COALESCE( x.D2, 0) &lt;&gt; 0 THEN x.NECESAR / (  COALESCE( x.D1, 0) * COALESCE( x.D2, 0))
                         WHEN x.RELATIEUM1 IN (3, 9) AND  COALESCE( x.D1, 0) * COALESCE( x.D2, 0) * COALESCE( x.D3, 0) &lt;&gt; 0 THEN x.NECESAR / (  COALESCE( x.D1, 0) * COALESCE( x.D2, 0) * COALESCE( x.D3, 0))
                         WHEN x.RELATIEUM1 IN (4, 10) THEN x.NECESAR * COALESCE( x.D1, 0)
                         WHEN x.RELATIEUM1 IN (5, 11) THEN x.NECESAR * COALESCE( x.D1, 0) * COALESCE( x.D2, 0)
                         WHEN x.RELATIEUM1 IN (6, 12) THEN x.NECESAR * COALESCE( x.D1, 0) * COALESCE( x.D2, 0) * COALESCE( x.D3, 0)
                       END , 7) NECESARUM1,
                x.RelatieUM1, x.Den_UMSec, x.Den_UM1,
                CASE
                 WHEN  -x.Necesar - x.restprecmd - x.restprecmda &lt; 0 THEN 0
                 ELSE -x.Necesar - x.restprecmd - x.restprecmda
               END  RESTNECESAR,
               x.consum
        FROM (SELECT se.codstare, se1.codstare1, se1.codobiect, COALESCE( se1.stocmin, 0) STOCMIN,
                     COALESCE( se1.stocini, 0) STOCINI,
                     CASE
                       WHEN  aSetG = aSet and  aAnG = aAn THEN se1.StocIni
                          else coalesce(se1.stocini,0) + coalesce(CmdFP_prec.resta,0) + coalesce(CmdFFix_prec.resta,0) + coalesce(CmdFL_prec.resta,0) - coalesce(EstIntP.resta,0)
                       END  STOCPREC,
                      COALESCE( se1.estimat, 0) ESTIMARI,
                      coalesce(CmdFP.resta,0) + coalesce(CmdFFix.resta,0) + coalesce(CmdFL.resta,0) CmdF,
                      CASE
                     when aSetG = aSet and aAnG = aAn then coalesce(se1.stocini,0) + coalesce(CmdFP_prec.resta,0) + coalesce(CmdFFix_prec.resta,0) + coalesce(CmdFL_prec.resta,0) + coalesce(CmdFP.resta,0) + coalesce(CmdFFix.resta,0) + coalesce(CmdFL.resta,0) - coalesce(se1.estimat,0)
                     else coalesce(se1.stocini,0) + coalesce(CmdFP_prec.resta,0) + coalesce(CmdFFix_prec.resta,0) + coalesce(CmdFL_prec.resta,0) + coalesce(CmdFP.resta,0) + coalesce(CmdFFix.resta,0) + coalesce(CmdFL.resta,0) - coalesce(EstIntP.resta,0) - coalesce(se1.estimat,0)
                     END  - COALESCE( se1.stocmin, 0) NECESAR,
                     CASE
                     when aSetG = aSet and aAnG = aAn then coalesce(se1.stocini,0) + coalesce(CmdFP_prec.resta,0) + coalesce(CmdFFix_prec.resta,0) + coalesce(CmdFL_prec.resta,0) + coalesce(CmdFP.resta,0) + coalesce(CmdFFix.resta,0) + coalesce(CmdFL.resta,0) - coalesce(se1.estimat,0)
                     else coalesce(se1.stocini,0) + coalesce(CmdFP.resta,0) + coalesce(CmdFP_prec.resta,0) + coalesce(CmdFFix_prec.resta,0) + coalesce(CmdFL_prec.resta,0) + coalesce(CmdFFix.resta,0) + coalesce(CmdFL.resta,0) - coalesce(EstIntP.resta,0) - coalesce(se1.estimat,0)
                     END  STOCFINAL,
                     COALESCE( se1.pret, 0) PRET,
                     COALESCE( se1.pret, 0) *
                     (CASE
                      when aSetG = aSet and aAnG = aAn then coalesce(se1.stocini,0) + coalesce(CmdFP_prec.resta,0) + coalesce(CmdFFix_prec.resta,0) + coalesce(CmdFL_prec.resta,0) + coalesce(CmdFP.resta,0) + coalesce(CmdFFix.resta,0) + coalesce(CmdFL.resta,0) - coalesce(se1.estimat,0)
                      else coalesce(se1.stocini,0) + coalesce(CmdFP_prec.resta,0) + coalesce(CmdFFix_prec.resta,0) + coalesce(CmdFL_prec.resta,0) + coalesce(CmdFP.resta,0) + coalesce(CmdFFix.resta,0) + coalesce(CmdFL.resta,0) - coalesce(EstIntP.resta,0) - coalesce(se1.estimat,0)
                      END )  STOCVAL,
                     obj.denumire, cmdfp.resta CMDFP, coalesce(RESTC.RESTA,0) RESTPRECMD,
                     coalesce(RESTCA.RESTA,0) RESTPRECMDA, se1.dirty, se1.dirtycmdf,se1.part1nec, um.codum1 UMSEC,
                     um1.codum UM1, art.d1, art.d2, art.d3, art.relatieum1, um.Den_UM1 DEN_UMSEC,
                     um1.Den_Um DEN_UM1, se1.consum
              FROM stareestimari se
                  INNER JOIN stareestimari1 se1 ON  se1.codstare   = se.codstare
                  INNER JOIN nartobj        obj ON  se1.codobiect  = obj.codobiect
                  INNER JOIN nart           art ON  art.codarticol = obj.codarticol
                  LEFT  JOIN num1           um  ON  um.codum  = art.um and  COALESCE( um.secundara, 0) = 0
                  LEFT  JOIN num            um1 ON  um1.codum = art.um1
                  left join tmp_cmd EstIntP on EstIntP.codobiect = se1.codobiect and EstIntP.Tip = 'ESTINTP'
                   left join tmp_cmd cmdfp on cmdfp.codobiect = se1.codobiect and cmdfp.tip = 'CMDFP'
                   left join tmp_cmd cmdffix on cmdffix.codobiect = se1.codobiect and cmdffix.tip = 'CMDFFIX'
                   left join tmp_cmd cmdfl on cmdfl.codobiect = se1.codobiect and cmdfl.tip = 'CMDFL'
                   left join tmp_cmd cmdfp_prec on cmdfp_prec.codobiect = se1.codobiect and cmdfp_prec.tip = 'CMDFP_PREC'
                   left join tmp_cmd cmdffix_prec on cmdffix_prec.codobiect = se1.codobiect and cmdffix_prec.tip = 'CMDFFIX_PREC'
                   left join tmp_cmd cmdfl_prec on cmdfl_prec.codobiect = se1.codobiect and cmdfl_prec.tip = 'CMDFL_PREC'
                   LEFT JOIN TMP_CMD RESTC ON RESTC.CODOBIECT = SE1.CODSTARE1 AND RESTC.TIP = 'RESTC'
                   LEFT JOIN TMP_CMD RESTCA ON RESTCA.CODOBIECT = SE1.CODSTARE1 AND RESTCA.TIP = 'RESTCA'
    where se.an = aAn and se.saptamana = aSet and se.ang = aAnG and se.saptamanag = aSetG
    and se.subunitatea = aSubunitatea and se1.codobiect &gt; 0 and se1.codstare1 = acodstare1
    order by obj.denumire) x;
  end if;
  EXCEPTION WHEN OTHERS THEN
    WME_Result :=  NULL;
    RETURN;
  END;
  DELETE FROM tmp_cmd;
  WME_Result :=  TmpCursor;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprod_setcarnetdoc_i</obj_name>
  <obj_hashval>d983264034088b273d4c0b3d766e52bd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprod_setcarnetdoc_i(acarnetdoc_i numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANIFPROD.CARNETDOC_I',to_char(aCARNETDOC_I,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plati_nrdoc_i</obj_name>
  <obj_hashval>33c5b2b23a6911f94ebb67035c5eae3a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plati_nrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PLATI.NRDOC_I', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plati_setnrdoc_i</obj_name>
  <obj_hashval>d70f71db650e8b7bfc8dad432c223aca</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plati_setnrdoc_i(anrdoc numeric, acarnet numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLATI.CARNETDOC_I',(ACARNET)::varchar,false);
perform set_config('PKG_PLATI.NRDOC_I',(ANRDOC)::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_calc_pmp</obj_name>
  <obj_hashval>324965b90f9a613d6dfbaa655b168a05</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_calc_pmp(tip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sCodSubunit TEXT;
  tSQL        TEXT;

  iAn         NUMERIC(4) := getAnLucru();
  iLuna       NUMERIC(2) := getLunaLucru();
  iAnPrec     NUMERIC(4);
  iLunaPrec   NUMERIC(2);
BEGIN
  --Stef 12.10.2025 - de pus si in Oracle optimizarile din PG
  --Stef 29.09.2025
  --PERFORM PKG_GLOBALS_setdebugmode(true);
  CALL create_wm_temps_flag('PMP_CALC');

  DELETE FROM TMP_PMP;
  DELETE FROM TMP_PMP_CALC_P;
  DELETE FROM TMP_PMP_CALC_I;

  SELECT newan, newluna INTO iAnPrec, iLunaPrec FROM PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA( iAn, iLuna, iAnPrec, iLunaPrec);
  PERFORM PKG_GLOBALS_SetLunaTemp(iAn, iLuna);
  PERFORM PKG_CATEGCONST_CONST_TO_TMP_CONSTANTE('TRANSFPMP');

  IF Tip = 2
  THEN sCodSubunit := 'CodSubunit';
  ELSE sCodSubunit := '1';
  END IF;

  tSQL := 'INSERT INTO TMP_PMP_CALC_P
  SELECT
    CodObiect, '||sCodSubunit||' AS CodSubunit,
    SUM(CANTINTR),  SUM(VALINTR), SUM(VALVALUTA)
  FROM PMPLUNA
  WHERE an = '||To_Char(iAnPrec)||' AND luna = '||to_char(iLunaPrec)||'
  GROUP BY CodObiect '||CASE WHEN sCodSubunit = '1' THEN '' ELSE ','||sCodSubunit END;
  PERFORM LIST_EXECUTE_IMMEDIATE(tSQL, 0, 0);

  tSQL := 'INSERT INTO TMP_PMP_CALC_I
  SELECT
    CodObiect, '||sCodSubunit||' AS CodSubunit,
    Sum(CANTINTR), Sum(VALINTR), Sum(VALVALUTA)
  FROM ('||V_PMP_LUNA(0, 0)||') aa
  GROUP BY CodObiect '||CASE WHEN sCodSubunit = '1' THEN '' ELSE ','||sCodSubunit END;
  PERFORM LIST_EXECUTE_IMMEDIATE(tSQL, 0, 0);

  tSQL := '
  INSERT INTO tmp_pmp(
    CodObiect, Codsubunit,
    PMP,
    PMPValuta
  )
  SELECT
    pal.CodObiect, pal.CodSubunit,
    CASE WHEN Coalesce(P.CANTINTR,0)+Coalesce(I.CANTINTR,0) = 0 THEN 0 ELSE Round( (Coalesce(P.VALINTR,  0)+Coalesce(I.VALINTR,  0)) / (Coalesce(P.CANTINTR,0)+Coalesce(I.CANTINTR,0)) , 7) END AS PMPL,
    CASE WHEN Coalesce(P.CANTINTR,0)+Coalesce(I.CANTINTR,0) = 0 THEN 0 ELSE Round( (Coalesce(P.VALVALUTA,0)+Coalesce(I.VALVALUTA,0)) / (Coalesce(P.CANTINTR,0)+Coalesce(I.CANTINTR,0)) , 7) END AS PMPV
  FROM ( SELECT DISTINCT CodObiect, 1 AS CodSubunit FROM tmp_pmp_act_luna ) pal
    LEFT JOIN TMP_PMP_CALC_P P ON P.CodObiect = PAL.CodObiect AND P.CodSubunit = PAL.CodSubunit
    LEFT JOIN TMP_PMP_CALC_I I ON I.CodObiect = PAL.CodObiect AND I.CodSubunit = PAL.CodSubunit';
  PERFORM LIST_EXECUTE_IMMEDIATE(tSQL, 0, 0);

END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_getg_pmp_lei</obj_name>
  <obj_hashval>a5aa1ce0ba1f39f6204efb87839fabad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_getg_pmp_lei(INOUT wme_result double precision, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PMP.G_PMP_LEI', true)),'99999999999.9999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_getg_pmp_prec</obj_name>
  <obj_hashval>8c22b92152428352481c0711b1d4aa40</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_getg_pmp_prec(INOUT wme_result double precision, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PMP.G_PMP_PREC', true)),'99999999999.9999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_postretail_sp_gotorecord</obj_name>
  <obj_hashval>b7840e3d538a6b8478279cf575a162b3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_postretail_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Florin 27.11.2025 - sinc. Oracle
  INSERT INTO TMP_POSTRETAIL
  SELECT * FROM POSTRETAIL WHERE COD = RECID;
  INSERT INTO TMP_INACTIVRETAIL(CODINACTIVRETAIL, CODOBIECT, CODPOSTRETAIL, DENUMIRE)
  SELECT  CODINACTIVRETAIL, I.CODOBIECT, CODPOSTRETAIL, DENUMIRE
  FROM
    INACTIVRETAIL I
    INNER JOIN NARTOBJ O ON O.CODOBIECT = I.CODOBIECT
  WHERE
    CODPOSTRETAIL = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_precomanda_sp_lockrecord</obj_name>
  <obj_hashval>7d5116025a983e8e93bdad8162e34e6f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_precomanda_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodPreComanda INTO Tmp FROM PRECOMANDA WHERE CodPreComanda = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_preturi_getpret_ies</obj_name>
  <obj_hashval>32db5b35eb8f1443d0bfc17474b8c6ed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_preturi_getpret_ies(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT apart numeric, INOUT alocatie numeric, INOUT asubunit numeric, INOUT adataref character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 07.01.2021 - fixat #42050
WME_Result :=  (SELECT PKG_PRETURI_GETPRET.WME_RESULT FROM PKG_PRETURI_GETPRET(NULL, 1, aCodObiect, aPart, aLocatie, aSubunit, To_Date( aDataRef, 'DD.MM.YYYY')));
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_get_mat_echivalat</obj_name>
  <obj_hashval>6bb9d4627ee47ab4d913c01f6d9ae80c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_get_mat_echivalat(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  current_setting('PKG_PRODCOMP.vCodMat', true)::numeric;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_calcul_detalii</obj_name>
  <obj_hashval>8d4bfdd11773cfae032e76454a65fec3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_calcul_detalii(xt character varying, yt character varying, vtip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vDATASTART  date;
  vDATASTOP   date;
  vZILEN      numeric;
  aCount      numeric;
  vAllGest    numeric;
  vAllTipCont numeric;
begin
  --Florin 11.11.2025 - sinc. Oracle
  --Florin 04.01.2022 - sinc. Oracle (29.12.2021)
  --Laura 09.11.2021 - sinc Oracle (09.11.2021)
  --Florin 28.10.2021 - fixat 51814
  --Adina 16.08.2021 - sinc.Oracle din 14.08.2021
  --Adina 12.07.2021 - sinc.Oracle din 10.07.2021
  --Adina 10.07.2021 - sinc.Oracle din 09.07.2021
  --Adina 09.07.2021 - sinc.Oracle din 09.07.2021
  SELECT VDELA      INTO vDATASTART  FROM TMP_PROGRAMF_MANEVRA;
  SELECT VPANALA    INTO vDATASTOP   FROM TMP_PROGRAMF_MANEVRA;
  SELECT AllGest    INTO vAllGest    FROM tmp_programf_manevra;
  SELECT AllTipCont INTO vAllTipCont FROM tmp_programf_manevra;

  SELECT count (zn1.data) INTO vZILEN
  FROM zineluc1 zn1
  WHERE zn1.data BETWEEN (SELECT VDELA FROM tmp_programf_manevra limit 1) AND (SELECT VpanaLA FROM tmp_programf_manevra limit 1);

    --DELETE FROM tmp_programf1c;
  DELETE FROM TMP_PF_MAT;
  DELETE FROM TMP_PF_SDV;
  DELETE FROM TMP_PF_LOCM;
  DELETE FROM TMP_PF_MAN;

  IF fnc_GetValConstantaLucru ('RAPORDMAN') = '1' THEN
    IF NOT current_setting ('PKG_PROGRAMF.vDinGoTo', true)::BOOL THEN
      DELETE FROM tmp_programf1;

      INSERT INTO tmp_programf1 (codprogramf1, codprogramf, codcomanda1, codgest,
          termen, cantprogramat, codformatie, schimb,
          den_gest, nrcmd, den_obiect, codextern,
          um, termenexec, den_client, termenlivr,
          codobiect, codcomanda, durata, duratam,
          den_formatie, d1, d2, d3,
          lansat, cantreteta, duratareteta, termencmdint,
          nrcmdcli, obscmdint, obscmdcli,prioritate,datastart)
      SELECT -1, tmp.codprogramf, c1.codcomanda1, c.codgest,
        c1.termen, sum (CASE WHEN maxop.ultim = man.nrop THEN tmp.cant * COALESCE (man.bps, 0) ELSE 0 END) CANTPROGRAMAT,
        c.codformatie, c.schimb, g.den_gest,
        ROUND((C.NRDOC + c1.indexlocal / 1000)::numeric, 3) NRCMD, obj.denumire DEN_OBIECT, obj.codextern, num1.den_um1 UM,
        c1.termen TERMENEXEC,
        case when cs.codcomanda &gt; 0 then ss.den_subunit else p.den_part end DEN_CLIENT, cc1.termen TERMENLIVR, obj.codobiect,
            c.codcomanda, sum (tmp.cant * (man.tu + man.tpi)) / 60 DURATA, sum (tmp.cant * (man.tu + man.tpi)) DURATAM, f.den_formatie,
             c1.d1, c1.d2, c1.d3, c1.cantacceptat LANSAT,
            pc.cant CANTRETETA, pc.durata DURATARETETA, c1.termen TERMENCMDINT,
            case when cs.codcomanda &gt; 0 then ROUND((CS.NRDOC + CS1.indexlocal / 1000)::numeric, 3) ELSE ROUND((CC.NRDOC + CC1.indexlocal / 1000)::numeric, 3) END,
            c1.obs, case when cs.codcomanda &gt; 0 then CS1.OBS ELSE cc1.obs end, gt.prioritate,gt.dstart
      FROM tmp_programfman_manevra tmp
        INNER JOIN cmdprodman    man ON man.codcmdprodman = tmp.codcmdprodman
        INNER JOIN comanda1      c1  ON c1.codcomanda1    = man.codcomanda1
        INNER JOIN comanda       c   ON c1.codcomanda     = c.codcomanda
        INNER JOIN ngest         g   ON g.codgest         = c.codgest
        INNER JOIN nartobj       obj ON c1.codobiect      = obj.codobiect
        INNER JOIN num1              ON num1.codum1       = c1.umsec
        INNER JOIN prodcomp      pc  ON pc.codprodcomp    = c1.codreteta
        INNER JOIN (SELECT ret.codprodcomp, max (pm.nrop) ULTIM
                    FROM cmdprodman                      m
                      INNER JOIN tmp_programfman_manevra mv  ON m.codcmdprodman = mv.codcmdprodman
                      INNER JOIN prodman                 pm  ON m.codman        = pm.codman
                      INNER JOIN prodcomp                ret ON ret.codprodcomp = pm.codprodcomp
                    GROUP BY ret.codprodcomp
                   )      maxop ON maxop.codprodcomp = pc.codprodcomp
        LEFT  JOIN (Select CodComanda1, CODCMDPRODMAN from CMDPRODMAN x where NROP = 1) PM ON PM.CODCOMANDA1 = C1.CODCOMANDA1
        LEFT  JOIN GANTT    GT  ON GT.CODCMDPRODMAN  = PM.CODCMDPRODMAN
        LEFT  JOIN formatii f   ON f.codformatie     = c.codformatie
        left  join cmdlink ls on ls.codcomanda1    = c1.codcomanda1
            left  join comanda1 cs1 on cs1.codcomanda1    = ls.codliniecomanda
            left  join comanda cs on cs.codcomanda      = cs1.codcomanda
            left  join nsubunit ss on ss.codsubunit    = cs.subunitsursa
        LEFT  JOIN comanda1 cc1 ON cc1.codcomanda1   = (SELECT pkg_comanda_DinCmdCli.WME_RESULT FROM pkg_comanda_DinCmdCli (NULL,c1.codcomanda1))
        LEFT  JOIN comanda  cc  ON cc1.codcomanda    = cc.codcomanda
        LEFT  JOIN npart    p   ON p.codpart         = cc.partener
        WHERE vTip = 0 or GT.Codgantt is not null
        GROUP BY
            tmp.codprogramf,
        c1.codcomanda1,
        c.codgest,
        c1.termen,
        c.codformatie,
        c.schimb,
        g.den_gest,
        C.NRDOC,
        c1.indexlocal,
        obj.denumire,
        obj.codextern,
        num1.den_um1,
        cs.codcomanda,
        ss.den_subunit,
        p.den_part,
        cc1.termen,
        obj.codobiect,
        c.codcomanda,
        f.den_formatie,
        c1.d1,
        c1.d2,
        c1.d3,
        c1.cantacceptat,
        pc.cant,
        pc.durata,
        CS.NRDOC,
        CS1.indexlocal,
        CC.NRDOC,
        CC1.indexlocal,
        c1.obs,
        CS1.OBS,
        cc1.obs,
        gt.prioritate,
        gt.dstart;
    END IF;

--    INSERT INTO TMP_PROGRAMF1C (CODCOMANDA, NRCMD, CODPROGRAMF, CANTPROGRAMAT, DEN_OBIECT, CODEXTERN, UM, CODOBIECT, DURATA, DURATAM, PRIORITATE, LANSARE,
--                                TERMENEXEC, CODINTERN, DEN_CLASEA)
--    SELECT C.CODCOMANDA, C.NRDOC, TMP.CODPROGRAMF, SUM (TMP.CANTPROGRAMAT) , OBJ.DENUMIRE, OBJ.CODEXTERN, NUM1.DEN_UM1, C1.CODOBIECT,
--           SUM (TMP.DURATA) , SUM (TMP.DURATAM) , 0 PRIORITATE,
--           CASE WHEN L.CODLANSARE &gt; 0 THEN coalesce (L.NRDOC::varchar,'') || '/' || coalesce (TO_CHAR (L.DATADOC, 'DD.MM.YYYY')  ,'')
--                ELSE NULL
--           END ,
--           TMP.TERMENEXEC, OBJ.CODINTERN, CLS.DEN_CLASEA
--    FROM TMP_PROGRAMF1    TMP
--      INNER JOIN COMANDA1 C1  ON C1.CODCOMANDA1 = TMP.CODCOMANDA1
--      INNER JOIN COMANDA  C   ON C1.CODCOMANDA  = C.CODCOMANDA
--      INNER JOIN NUM1         ON NUM1.CODUM1    = C1.UMSEC
--      INNER JOIN NARTOBJ  OBJ ON C1.CODOBIECT   = OBJ.CODOBIECT
--      INNER JOIN NART     A   ON OBJ.CODARTICOL = A.CODARTICOL
--      INNER JOIN PRODCOMP PC  ON C1.CODRETETA   = PC.CODPRODCOMP
--      LEFT JOIN NCLASEA   CLS ON A.CLASA        = CLS.CODCLASEA
--      LEFT JOIN LANSARE1  L1  ON C1.CODCOMANDA1 = L1.CODCMD1
--      LEFT JOIN LANSARE   L   ON L.CODLANSARE   = L1.CODLANSARE
--    GROUP BY
--      C.CODCOMANDA, C.NRDOC, TMP.CODPROGRAMF, OBJ.DENUMIRE,
--      OBJ.CODEXTERN, NUM1.DEN_UM1, C1.CODOBIECT, L.CODLANSARE,
--      L.NRDOC, L.DATADOC, TMP.TERMENEXEC, OBJ.CODINTERN,
--      CLS.DEN_CLASEA;

    INSERT INTO TMP_PF_MAT (CODOBIECT, DENUMIRE, CODEXTERN, DEN_UM1, NECESAR, CONSUMAT, DIFERENTE, REZERVAT, STOCFURN, RESTASIGURAT)
    SELECT NOBJ.CODOBIECT, NOBJ.DENUMIRE, NOBJ.CODEXTERN, NUM.DEN_UM,
      ROUND ( (SUM (  MAT.CANT * TMP.CANT / MAN.CANT)) ::numeric, 2) NECESAR,
      ROUND ( (SUM ( (MAT.CANT * TMP.CANT / MAN.CANT) - (MAT.REST * TMP.CANT / MAN.CANT))) ::numeric, 2) CONSUMAT,
      ROUND ( (SUM (  MAT.REST * TMP.CANT / MAN.CANT)) ::numeric, 2) DIFERENTE,
      ROUND ( (SUM (COALESCE (REZ.REST, 0))) ::numeric, 2) REZERVAT,
      ROUND ( (COALESCE (CMDFURN.STOCFURN, 0)) ::numeric, 2) STOCFURN,
      ROUND ( (SUM (CASE WHEN MAT.CANT * TMP.CANT / MAN.CANT - COALESCE (REZ.REST, 0) &lt; 0 THEN 0
                         ELSE MAT.CANT * TMP.CANT / MAN.CANT - COALESCE (REZ.REST, 0)
                    END) ) ::numeric, 2)
    FROM TMP_PROGRAMFMAN_MANEVRA TMP
      INNER JOIN CMDPRODMAN    MAN  ON TMP.CODCMDPRODMAN = MAN.CODCMDPRODMAN
      INNER JOIN CMDPRODMAT    MAT  ON MAT.CODCMDPRODMAN = MAN.CODCMDPRODMAN
      INNER JOIN COMANDA1      C1   ON MAN.CODCOMANDA1   = C1.CODCOMANDA1
      INNER JOIN NARTOBJ       NOBJ ON NOBJ.CODOBIECT    = MAT.CODOBIECT
      INNER JOIN NART          N    ON N.CODARTICOL      = NOBJ.CODARTICOL
      INNER JOIN NUM                ON NUM.CODUM         = N.UM
      LEFT  JOIN REZERVATS     REZ  ON REZ.CODCMDPRODMAT = MAT.CODCMDPRODMAT
      LEFT  JOIN (SELECT CFURN1.CODOBIECT, SUM (CFURN1.RESTACCEPTAT) STOCFURN
                  FROM COMANDA                         CFURN
                    INNER JOIN COMANDA1                CFURN1 ON CFURN.CODCOMANDA  = CFURN1.CODCOMANDA
                    INNER JOIN CMDPRODMAT              MAT    ON MAT.CODOBIECT     = CFURN1.CODOBIECT
                    INNER JOIN CMDPRODMAN              MAN    ON MAN.CODCMDPRODMAN = MAT.CODCMDPRODMAN
                    INNER JOIN TMP_PROGRAMFMAN_MANEVRA TMP    ON TMP.CODCMDPRODMAN = MAN.CODCMDPRODMAN
                  WHERE CFURN.TIPDOC = 8
                  GROUP BY CFURN1.CODOBIECT
                 ) CMDFURN ON CMDFURN.CODOBIECT = MAT.CODOBIECT
    WHERE
      (C1.CONSUM = 1 AND MAT.TIP = 1) OR (C1.CONSUM = 2 AND MAT.TIP IN (0, 1))
    GROUP BY
      NOBJ.CODOBIECT, NOBJ.DENUMIRE, NOBJ.CODEXTERN, NUM.DEN_UM, COALESCE (CMDFURN.STOCFURN, 0);

    UPDATE TMP_PF_MAT SET restasigurat = 0 WHERE restasigurat &lt; 0;

    INSERT INTO TMP_PF_SDV (DENUMIRE, DEN_UM, CODEXTERN, REST, STOCFURN, CANTACT, CANTDOC, CODOBIECT)
    SELECT NOBJ.DENUMIRE, NUM.DEN_UM, NOBJ.CODEXTERN, ROUND ( (COALESCE (STOC.REST, 0)) ::numeric, 2) REST,
           ROUND ( (COALESCE (CMDFURN.STOCFURN, 0)) ::numeric, 2) STOCFURN,
           ROUND ( (COALESCE (SUM (PSDV.CANT) , 0)) ::numeric, 2) CANTACT,
           ROUND ( (SUM (SDV.CANT * TMP.CANT)) ::numeric, 2) CANTDOC, NOBJ.CODOBIECT
    FROM TMP_PROGRAMFMAN_MANEVRA TMP
      INNER JOIN CMDPRODMAN      MAN  ON TMP.CODCMDPRODMAN = MAN.CODCMDPRODMAN
      INNER JOIN COMANDA1        C1   ON MAN.CODCOMANDA1   = C1.CODCOMANDA1
      INNER JOIN PRODMAN         PMAN ON PMAN.CODMAN       = MAN.CODMAN
      INNER JOIN (SELECT S.CODPRODMAN, S.CODSDV, SUM (S.CANT / PC.CANT) CANT
                  FROM PRODSDV S INNER JOIN PRODCOMP PC ON PC.Codprodcomp = S.CODPRODCOMP
                  GROUP BY CODPRODMAN, CODSDV
                 ) SDV  ON SDV.CODPRODMAN = PMAN.CODMAN
      LEFT  JOIN NARTOBJ               NOBJ ON NOBJ.CODOBIECT = SDV.CODSDV
      LEFT  JOIN NART                  N    ON N.CODARTICOL   = NOBJ.CODARTICOL
      LEFT  JOIN NUM                        ON NUM.CODUM      = N.UM
      LEFT  JOIN (SELECT NS.CODOBIECT, SUM (NS.REST) REST FROM NIRSTOC NS GROUP BY NS.CODOBIECT) STOC ON SDV.CODSDV = STOC.CODOBIECT
      LEFT  JOIN (SELECT CFURN1.CODOBIECT, SUM (CFURN1.RESTACCEPTAT) STOCFURN
                  FROM COMANDA CFURN INNER JOIN COMANDA1 CFURN1 ON CFURN.CODCOMANDA = CFURN1.CODCOMANDA
                  WHERE CFURN.TIPDOC = 8
                  GROUP BY CFURN1.CODOBIECT
                 ) CMDFURN ON CMDFURN.CODOBIECT = SDV.CODSDV
      LEFT  JOIN (SELECT CODPROGRAMF, SUM (CANT) CANT FROM PROGRAMFSDV GROUP BY CODPROGRAMF) PSDV ON PSDV.CODPROGRAMF = TMP.CODPROGRAMF
    GROUP BY
      NOBJ.DENUMIRE, NUM.DEN_UM, NOBJ.CODEXTERN, NOBJ.CODOBIECT, COALESCE (STOC.REST, 0) , COALESCE (CMDFURN.STOCFURN, 0);

    INSERT INTO TMP_PF_LOCM (DENUMIRE, DISPONIBIL, NECESAR, DIFERENTE, CODLOCMUNCA, DISPONIBILM, NECESARM, DIFERENTEM)
    WITH CRS_ZILE AS
      (SELECT T.CodProgramf,
              (T.vPanaLa - T.VDeLa) + 1 - (SELECT count (zn1.data) FROM zineluc1 zn1 WHERE zn1.data BETWEEN vDataStart AND vDataStop) ZILE
       FROM TMP_PROGRAMF_MANEVRA T
      )
      , CRS_NECESAR AS
      (SELECT SUM (CASE WHEN PC.CANT &lt;&gt; 1 THEN PFM.CANT / PMAN.CANT * COALESCE (PMAN.TPI, 0) + PFM.CANT / PMAN.BPS * PMAN.TU
                        ELSE COALESCE (PMAN.TPI, 0) + PFM.CANT / PMAN.BPS * PMAN.TU
                   END) NECESAR,
              COALESCE (PMAN.CODLOC, 0) CODLOC
       FROM TMP_PROGRAMFMAN_MANEVRA PFM
            INNER JOIN CMDPRODMAN    PMAN ON PMAN.CODCMDPRODMAN = PFM.CODCMDPRODMAN
            INNER JOIN PRODMAN       MAN  ON PMAN.CODMAN        = MAN.CODMAN
            INNER JOIN PRODCOMP      PC   ON PC.CODPRODCOMP     = MAN.CODPRODCOMP
       GROUP BY PMAN.CODLOC
      )
      , CRS_LOCURI AS
      (SELECT x.codloc, sum (x.disponibil) DISPONIBIL
       FROM (SELECT DISTINCT LM.CODLOC, LM.DENUMIRE, LM1.ore * zile.zile DISPONIBIL
             FROM (SELECT ZILE FROM CRS_ZILE limit 1) ZILE, LOCMUNCA LM
                LEFT JOIN LOCMUNCA1     LM1 ON LM.CODLOC     = LM1.CODLOC
                LEFT JOIN MIFIX1        MF1 ON MF1.CODMIFIX  = LM1.CODMIFIX
                LEFT JOIN NIRSTOC       NS  ON NS.CODNIRSTOC = MF1.CODNIRSTOC
                LEFT JOIN NIR               ON NIR.CODNIR    = NS.CODNIR
                LEFT JOIN NGEST NG          ON NG.CODGEST    = NIR.GEST
             WHERE LM.TIP = 1 AND NS.Rest &gt; 0
               AND MF1.Anstart * 12 + MF1.lunastart = (SELECT max (anstart * 12 + lunastart) FROM mifix1 WHERE codmifix = LM1.codmifix)
            union ALL
             SELECT  DISTINCT LM.CODLOC, LM.DENUMIRE, LM1.ore * zile.zile DISPONIBIL
             FROM (SELECT ZILE FROM CRS_ZILE limit 1) ZILE, LOCMUNCA LM
                LEFT JOIN LOCMUNCA1 LM1 ON LM.CODLOC = LM1.CODLOC
             WHERE LM.TIP = 2
            union ALL
             SELECT  DISTINCT LM.CODLOC, LM.DENUMIRE, COALESCE (G.ORESCHIMB, 0) * COALESCE (G.NRSCHIMBURI, 0) * zile.zile DISPONIBIL
             FROM (SELECT ZILE FROM CRS_ZILE limit 1) ZILE, TMP_PROGRAMFMAN_MANEVRA MM
                INNER JOIN CMDPRODMAN   MAN ON MM.CODCMDPRODMAN = MAN.CODCMDPRODMAN
                INNER JOIN LOCMUNCA     LM  ON MAN.CODLOC       = LM.CODLOC
                INNER JOIN COMANDA1     C1  ON C1.CODCOMANDA1   = MAN.CODCOMANDA1
                INNER JOIN COMANDA      C   ON C.CODCOMANDA     = C1.CODCOMANDA
                INNER JOIN NGEST        G   ON G.CODGEST        = C.CODGEST
             WHERE LM.TIP = 0
            ) x
        GROUP BY x.codloc
      )
    SELECT  LM.DENUMIRE,
            coalesce(LOCURI.DISPONIBIL,0)  DISPONIBIL,
            coalesce(NECESAR.NECESAR,0)/60 NECESAR,
            coalesce(LOCURI.DISPONIBIL,0) - coalesce(NECESAR.NECESAR,0)/60 DIFERENTE,
            NECESAR.CODLOC,
            COALESCE (LOCURI.DISPONIBIL, 0) * 60 DISPONIBILM,
            COALESCE (NECESAR.NECESAR, 0) NECESARM,
            COALESCE (LOCURI.DISPONIBIL, 0) * 60 - COALESCE (NECESAR.NECESAR, 0) DIFERENTEM
    FROM CRS_NECESAR        NECESAR
      INNER JOIN LOCMUNCA   LM     ON NECESAR.CODLOC = LM.CODLOC
      LEFT  JOIN CRS_LOCURI LOCURI ON LOCURI.CODLOC  = NECESAR.CODLOC;

    INSERT INTO TMP_PF_MAN (CODOP, CODTARIF, DEN_OP, DEN_TARIF, TARIF, ORE, VALOARE, OREM, OPERATII, Den_Locm)
    SELECT OP.CodOp, T1.CODTARIF, OP.DENUMIRE, T.DENUMIRE,
           round ( (T1.TARIF) ::numeric, 2) ,
           round ( (sum(round((PFM.CANT * coalesce(MAN.TPI, 0) + PFM.CANT * coalesce(MAN.TU, 0))::numeric, 2) / 60))::numeric, 2) ,
           round ( (sum (PFM.CANT * COALESCE (MAN.TPI, 0) + PFM.CANT * COALESCE (MAN.TU, 0) * T1.TARIF / 60)) ::numeric, 2) ,
           round ( (sum (PFM.CANT * COALESCE (MAN.TPI, 0) + PFM.CANT * COALESCE (MAN.TU, 0) * T1.TARIF)) ::numeric, 2) ,
           round ( (sum (PFM.CANT)) ::numeric, 2),
           L.DENUMIRE
    FROM TMP_PROGRAMFMAN_MANEVRA PFM
      INNER JOIN CMDPRODMAN    MAN  ON MAN.CODCMDPRODMAN = PFM.CODCMDPRODMAN
      INNER JOIN PRODMAN       PMAN ON PMAN.CODMAN       = MAN.CODMAN
      INNER JOIN COMANDA1      C1   ON MAN.CODCOMANDA1   = C1.CODCOMANDA1
      INNER JOIN PRODCOMP      PC   ON C1.CODRETETA      = PC.CODPRODCOMP
      INNER JOIN NOPER         OP   ON OP.CODOP          = MAN.CODOP
      INNER JOIN TARIFEMAN1    T1   ON T1.CODTARIF       = MAN.CODTARIF
      INNER JOIN TARIFEMAN     T    ON T1.CODTARIF       = T.CODTARIF
      INNER JOIN LOCMUNCA      L    ON L.CODLOC          = MAN.CODLOC
      WHERE GetAnLunaLucru() BETWEEN T1.ALSTART AND T1.ALSTOP
      GROUP by OP.CODOP, T1.CODTARIF, OP.DENUMIRE, T.DENUMIRE, T1.TARIF, L.DENUMIRE;

  ELSE
    IF NOT current_setting ('PKG_PROGRAMF.vDinGoTo', true)::BOOL THEN
      DELETE FROM tmp_programf1;

      INSERT INTO tmp_programf1 (codprogramf1, codprogramf, codcomanda1, codgest,
          termen, cantprogramat, codformatie, schimb,
          den_gest, nrcmd, den_obiect, codextern,
          um, termenexec, den_client, termenlivr,
          codobiect, codcomanda, durata, duratam,
          den_formatie, d1, d2, d3,
          lansat, cantreteta, duratareteta, termencmdint,
          nrcmdcli, obscmdint, obscmdcli, saptamana, prioritate, datastart)
      SELECT -1, tmp.codprogramf, c1.codcomanda1, c.codgest,
            c1.termen, tmp.cantprogramat, c.codformatie, c.schimb,
            g.den_gest, ROUND((C.NRDOC + c1.indexlocal / 1000)::numeric, 3) NRCMD, obj.denumire DEN_OBIECT, obj.codextern,
            num1.den_um1 UM, c1.termen TERMENEXEC, case when cs.codcomanda &gt; 0 then ss.den_subunit else p.den_part end den_client, cc1.termen TERMENLIVR,
                  obj.codobiect, c.codcomanda,
                  tmp.cantprogramat/pc.cant * coalesce(pc.durata,0)/60 DURATA,
                  tmp.cantprogramat / pc.cant * COALESCE (pc.durata, 0) DURATAM, f.den_formatie, c1.d1,
                  c1.d2, c1.d3, c1.cantacceptat LANSAT, pc.cant CANTRETETA,
                  pc.durata DURATARETETA, c1.termen TERMENCMDINT, ROUND((CC.NRDOC + Cc1.indexlocal / 1000)::numeric, 3), c1.obs,
            case when cs.codcomanda &gt; 0 then CS1.OBS ELSE cc1.obs END, TO_CHAR (C1.TERMEN, 'IW') ::numeric, gt.prioritate,gt.dstart
      FROM tmp_programf1_manevra tmp
          INNER JOIN comanda1             c1  ON c1.codcomanda1  = tmp.codcomanda1
          INNER JOIN comanda              c   ON c1.codcomanda   = c.codcomanda
          INNER JOIN ngest                g   ON g.codgest       = c.codgest
          INNER JOIN nartobj              obj ON c1.codobiect    = obj.codobiect
          INNER JOIN num1                     ON num1.codum1     = c1.umsec
          INNER JOIN prodcomp             pc  ON pc.codprodcomp  = c1.codreteta
          LEFT  JOIN (Select CodComanda1, CODCMDPRODMAN from CMDPRODMAN x where NROP = 1) PM ON PM.CODCOMANDA1 = C1.CODCOMANDA1
                left  JOIN GANTT                GT  ON GT.CODCMDPRODMAN = PM.CODCMDPRODMAN
          LEFT  JOIN formatii             f   ON f.codformatie    = c.codformatie
          left  join cmdlink           ls on ls.codcomanda1 = c1.codcomanda1
                left  join comanda1       cs1 on cs1.codcomanda1 = ls.codliniecomanda
                left  join comanda           cs on cs.codcomanda = cs1.codcomanda
                left  join nsubunit          ss on ss.codsubunit = cs.subunitsursa
          LEFT  JOIN comanda1             cc1 ON cc1.codcomanda1  = (SELECT pkg_comanda_DinCmdCli.WME_RESULT FROM pkg_comanda_DinCmdCli (NULL,c1.codcomanda1))
          LEFT  JOIN comanda              cc  ON cc1.codcomanda   = cc.codcomanda
          LEFT  JOIN npart                p   ON p.codpart        = cc.partener
          LEFT  JOIN tmp_programf_manevra mm  ON mm.codprogramf   = tmp.codprogramf
      WHERE vTip = 0 or GT.Codgantt is not null;
    END IF;

--    INSERT INTO TMP_PROGRAMF1C (CODCOMANDA, NRCMD, CODPROGRAMF, CANTPROGRAMAT, DEN_OBIECT, CODEXTERN, UM, CODOBIECT,
--                                DURATA, DURATAM, PRIORITATE, LANSARE, TERMENEXEC, CODINTERN, DEN_CLASEA)
--    SELECT  C.CODCOMANDA, C.NRDOC, TMP.CODPROGRAMF, SUM (TMP.CANTPROGRAMAT) , OBJ.DENUMIRE, OBJ.CODEXTERN, NUM1.DEN_UM1, C1.CODOBIECT,
--            CASE WHEN vTip = 1 THEN sum (TMP.CANTPROGRAMAT / PC.CANT * PC.DURATA / 60)
--                 ELSE sum (TMP.CANTPROGRAMAT / PC.CANT * PC.DURATA)
--            END ,
--            sum (TMP.CANTPROGRAMAT / PC.CANT * PC.DURATA) ,
--            TMP.PRIORITATE,
--            CASE WHEN L.CODLANSARE &gt; 0 THEN coalesce (L.NRDOC::varchar,'') || '/' || coalesce  (TO_CHAR (L.DATADOC, 'DD.MM.YYYY')  ,'')
--                 ELSE NULL
--            END ,
--            MAX (TMP.TERMENEXEC) , OBJ.CODINTERN, CLS.DEN_CLASEA
--    FROM TMP_PROGRAMF1_MANEVRA TMP
--        INNER JOIN COMANDA1    C1  ON C1.CODCOMANDA1 = TMP.CODCOMANDA1
--        INNER JOIN COMANDA     C   ON C1.CODCOMANDA  = C.CODCOMANDA
--        INNER JOIN NUM1            ON NUM1.CODUM1    = C1.UMSEC
--        INNER JOIN NARTOBJ     OBJ ON C1.CODOBIECT   = OBJ.CODOBIECT
--        INNER JOIN NART        A   ON OBJ.CODARTICOL = A.CODARTICOL
--        INNER JOIN PRODCOMP    PC  ON C1.CODRETETA   = PC.CODPRODCOMP
--        LEFT  JOIN NCLASEA     CLS ON A.CLASA        = CLS.CODCLASEA
--        LEFT  JOIN LANSARE1    L1  ON C1.CODCOMANDA1 = L1.CODCMD1
--        LEFT  JOIN LANSARE     L   ON L.CODLANSARE   = L1.CODLANSARE
--    GROUP BY
--      TMP.CODPROGRAMF, OBJ.DENUMIRE, OBJ.CODEXTERN, NUM1.DEN_UM1, C1.CODOBIECT, C.NRDOC, C.CODCOMANDA, TMP.PRIORITATE,
--      L.NRDOC, L.DATADOC, L.CODLANSARE, OBJ.CODINTERN, CLS.DEN_CLASEA;

    INSERT INTO TMP_PF_MAT (CODOBIECT, DENUMIRE, CODEXTERN, DEN_UM1, NECESAR, CONSUMAT, DIFERENTE, REZERVAT, STOCFURN, RESTASIGURAT)
    SELECT NOBJ.CODOBIECT, NOBJ.DENUMIRE, NOBJ.CODEXTERN, NUM.DEN_UM,
           ROUND ( (SUM (PRODM.CANT * PF1.CANTPROGRAMAT / C1.CANTACCEPTAT)) ::numeric, 2) NECESAR,
           ROUND ( (SUM ( (PRODM.CANT * PF1.CANTPROGRAMAT / C1.CANTACCEPTAT) - (PRODM.REST * PF1.CANTPROGRAMAT / C1.CANTACCEPTAT))) ::numeric, 2) CONSUMAT,
           ROUND ( (SUM (PRODM.REST * PF1.CANTPROGRAMAT / C1.CANTACCEPTAT)) ::numeric, 2) DIFERENTE,
           ROUND ( (SUM (COALESCE (REZ.REST, 0))) ::numeric, 2) REZERVAT,
           ROUND ( (COALESCE (CMDFURN.STOCFURN, 0)) ::numeric, 2) STOCFURN,
           ROUND ( (SUM (CASE WHEN PRODM.CANT     * PF1.CANTPROGRAMAT / C1.CANTACCEPTAT - COALESCE (REZ.REST, 0) &lt; 0 THEN 0
                              ELSE PRODM.CANT * PF1.CANTPROGRAMAT / C1.CANTACCEPTAT - COALESCE (REZ.REST, 0)
                         END)
                   ) ::numeric, 2)
    FROM COMANDA1                      C1
      INNER JOIN TMP_PROGRAMF1_MANEVRA PF1   ON PF1.CODCOMANDA1   = C1.CODCOMANDA1
      INNER JOIN CMDPRODMAT            PRODM ON PRODM.CODCOMANDA1 = C1.CODCOMANDA1
      INNER JOIN NARTOBJ               NOBJ  ON NOBJ.CODOBIECT    = PRODM.CODOBIECT
      INNER JOIN NART                  N     ON N.CODARTICOL      = NOBJ.CODARTICOL
      INNER JOIN NUM                         ON NUM.CODUM         = N.UM
      LEFT  JOIN REZERVATS             REZ   ON REZ.CODCMDPRODMAT = PRODM.CODCMDPRODMAT
      LEFT  JOIN (SELECT CFURN1.CODOBIECT, SUM (CFURN1.RESTACCEPTAT) STOCFURN
                  FROM COMANDA CFURN INNER JOIN COMANDA1 CFURN1 ON CFURN.CODCOMANDA = CFURN1.CODCOMANDA
                  WHERE CFURN.TIPDOC = 8
                  GROUP BY CFURN1.CODOBIECT
                 ) CMDFURN ON CMDFURN.CODOBIECT = PRODM.CODOBIECT
    WHERE (C1.CONSUM = 1 AND PRODM.TIP = 1) OR (C1.CONSUM = 2 AND PRODM.TIP IN (0, 1))
    GROUP BY NOBJ.CODOBIECT, NOBJ.DENUMIRE, NOBJ.CODEXTERN, NUM.DEN_UM, COALESCE (CMDFURN.STOCFURN, 0);

    UPDATE TMP_PF_MAT SET restasigurat = 0 WHERE restasigurat &lt; 0;

    INSERT INTO TMP_PF_SDV (DENUMIRE, DEN_UM, CODEXTERN, REST, STOCFURN, CANTACT, CANTDOC, CODOBIECT)
    SELECT NOBJ.DENUMIRE, NUM.DEN_UM, NOBJ.CODEXTERN, ROUND ( (COALESCE (STOC.REST, 0)) ::numeric, 2) REST,
           ROUND ( (COALESCE (CMDFURN.STOCFURN, 0)) ::numeric, 2) STOCFURN,
           ROUND ( (COALESCE (SUM (PSDV.CANT) , 0)) ::numeric, 2) CANTACT,
           ROUND ( (SUM (SDV.CANT * PF1.CANTPROGRAMAT)) ::numeric, 2) CANTDOC, NOBJ.CODOBIECT
    FROM TMP_PROGRAMF1_MANEVRA PF1
      INNER JOIN COMANDA1      C1   ON PF1.CODCOMANDA1 = C1.CODCOMANDA1
      INNER JOIN PRODMAN       PMAN ON C1.CODRETETA    = PMAN.CODPRODCOMP
      INNER JOIN (SELECT S.CODPRODMAN, S.CODSDV, SUM (S.CANT / PC.CANT) CANT
                  FROM PRODSDV S INNER JOIN PRODCOMP PC ON PC.Codprodcomp = S.CODPRODCOMP
                  GROUP BY CODPRODMAN, CODSDV
                 ) SDV  ON SDV.CODPRODMAN = PMAN.CODMAN
      LEFT  JOIN NARTOBJ NOBJ ON NOBJ.CODOBIECT = SDV.CODSDV
      LEFT  JOIN NART    N    ON N.CODARTICOL   = NOBJ.CODARTICOL
      LEFT  JOIN NUM          ON NUM.CODUM      = N.UM
      LEFT  JOIN (SELECT NS.CODOBIECT, SUM (NS.REST) REST FROM NIRSTOC NS GROUP BY NS.CODOBIECT) STOC ON SDV.CODSDV = STOC.CODOBIECT
      LEFT  JOIN (SELECT CFURN1.CODOBIECT, SUM (CFURN1.RESTACCEPTAT) STOCFURN
                  FROM COMANDA CFURN INNER JOIN COMANDA1 CFURN1 ON CFURN.CODCOMANDA = CFURN1.CODCOMANDA
                  WHERE CFURN.TIPDOC = 8
                  GROUP BY CFURN1.CODOBIECT
                 ) CMDFURN ON CMDFURN.CODOBIECT = SDV.CODSDV
      LEFT  JOIN (SELECT CODPROGRAMF, SUM (CANT) CANT FROM PROGRAMFSDV GROUP BY CODPROGRAMF) PSDV ON PSDV.CODPROGRAMF = PF1.CODPROGRAMF
    GROUP BY
      NOBJ.DENUMIRE, NUM.DEN_UM, NOBJ.CODEXTERN, NOBJ.CODOBIECT, COALESCE (STOC.REST, 0) , COALESCE (CMDFURN.STOCFURN, 0);

    INSERT INTO TMP_PF_LOCM (DENUMIRE, DISPONIBIL, NECESAR, DIFERENTE, CODLOCMUNCA, DISPONIBILM, NECESARM, DIFERENTEM)
    WITH CRS_ZILE AS
      (SELECT T.CodProgramf, (T.vPanaLa - T.VDeLa) + 1 - (SELECT count (zn1.data) FROM zineluc1 zn1 WHERE zn1.data BETWEEN vDataStart AND vDataStop) ZILE
       FROM TMP_PROGRAMF_MANEVRA                              T
      )
      , CRS_NECESAR AS
      (SELECT SUM (CASE WHEN PC.CANT &lt;&gt; 1 THEN PF1.CANTPROGRAMAT / PMAN.CANT * COALESCE (PMAN.TPI, 0) + PF1.CANTPROGRAMAT / PMAN.BPS * PMAN.TU
                        ELSE COALESCE (PMAN.TPI, 0) + PF1.CANTPROGRAMAT / PMAN.BPS * PMAN.TU
                   END) NECESAR,
              COALESCE (PMAN.CODLOC, 0) CODLOC
        FROM TMP_PROGRAMF1_MANEVRA PF1
            INNER JOIN COMANDA1    C1   ON C1.CODCOMANDA1   = PF1.CODCOMANDA1
            INNER JOIN PRODCOMP    PC   ON C1.CODRETETA     = PC.CODPRODCOMP
            INNER JOIN CMDPRODMAN  PMAN ON PMAN.CODCOMANDA1 = PF1.CODCOMANDA1
        GROUP BY PMAN.CODLOC
      )
      , CRS_LOCURI AS
      (SELECT x.codloc, sum (x.disponibil) DISPONIBIL
       FROM (SELECT DISTINCT LM.CODLOC, LM.DENUMIRE, LM1.ore * zile.zile DISPONIBIL
             FROM (SELECT ZILE FROM CRS_ZILE limit 1) ZILE, LOCMUNCA LM
                LEFT JOIN LOCMUNCA1     LM1 ON LM.CODLOC     = LM1.CODLOC
                LEFT JOIN MIFIX1        MF1 ON MF1.CODMIFIX  = LM1.CODMIFIX
                LEFT JOIN NIRSTOC       NS  ON NS.CODNIRSTOC = MF1.CODNIRSTOC
                LEFT JOIN NIR               ON NIR.CODNIR    = NS.CODNIR
                LEFT JOIN NGEST NG          ON NG.CODGEST    = NIR.GEST
             WHERE LM.TIP = 1 AND NS.Rest &gt; 0
               AND MF1.Anstart * 12 + MF1.lunastart = (SELECT max (anstart * 12 + lunastart) FROM mifix1 WHERE codmifix = LM1.codmifix)
            union ALL
             SELECT DISTINCT LM.CODLOC, LM.DENUMIRE, LM1.ore * zile.zile DISPONIBIL
             FROM (SELECT ZILE FROM CRS_ZILE limit 1) ZILE, LOCMUNCA LM
                LEFT JOIN LOCMUNCA1     LM1 ON LM.CODLOC = LM1.CODLOC
             WHERE LM.TIP = 2
            union ALL
             SELECT  DISTINCT LM.CODLOC, LM.DENUMIRE, COALESCE (G.ORESCHIMB, 0) * COALESCE (G.NRSCHIMBURI, 0) * zile.zile DISPONIBIL
             FROM (SELECT ZILE FROM CRS_ZILE limit 1) ZILE, TMP_PROGRAMF1_MANEVRA MM
                INNER JOIN CMDPRODMAN   MAN ON MM.CODCOMANDA1 = MAN.CODCOMANDA1
                INNER JOIN LOCMUNCA     LM  ON MAN.CODLOC = LM.CODLOC
                INNER JOIN COMANDA1     C1  ON C1.CODCOMANDA1 = MAN.CODCOMANDA1
                INNER JOIN COMANDA      C   ON C.CODCOMANDA = C1.CODCOMANDA
                INNER JOIN NGEST        G   ON G.CODGEST = C.CODGEST
             WHERE LM.TIP = 0
            ) x
        GROUP BY x.codloc
      )
    SELECT LM.DENUMIRE,
           coalesce(LOCURI.DISPONIBIL,0) DISPONIBIL,
           coalesce(NECESAR.NECESAR,0)/60 NECESAR,
           coalesce(LOCURI.DISPONIBIL,0) - coalesce(NECESAR.NECESAR,0)/60 DIFERENTE,
           NECESAR.CODLOC,
           COALESCE (LOCURI.DISPONIBIL, 0) * 60 DISPONIBILM,
           COALESCE (NECESAR.NECESAR, 0) NECESARM,
           COALESCE (LOCURI.DISPONIBIL, 0) * 60 - COALESCE (NECESAR.NECESAR, 0) DIFERENTEM
    FROM CRS_NECESAR        NECESAR
      INNER JOIN LOCMUNCA   LM     ON NECESAR.CODLOC = LM.CODLOC
      LEFT  JOIN CRS_LOCURI LOCURI ON LOCURI.CODLOC  = NECESAR.CODLOC;

    INSERT INTO TMP_PF_MAN (CODOP, CODTARIF, DEN_OP, DEN_TARIF, TARIF, ORE, VALOARE, OREM, OPERATII, Den_Locm)
    SELECT OP.CodOp, T1.CODTARIF, OP.DENUMIRE, T.DENUMIRE,
           round ( (T1.TARIF) ::numeric, 2) ,
           round( (sum(CASE WHEN PC.CANT &lt;&gt; 1 THEN round((PF1.CANTPROGRAMAT/coalesce(PC.CANT, 1) * coalesce(MAN.TPI, 0) + PF1.CANTPROGRAMAT / coalesce(MAN.BPS, 1) * coalesce(MAN.TU, 0))::numeric, 2)
                            ELSE round((coalesce(MAN.TPI, 0) + PF1.CANTPROGRAMAT * coalesce(MAN.TU, 0))::numeric, 2)
                       END
                      ) / 60
                  )::numeric, 2),
           round ( (sum (CASE WHEN PC.CANT &lt;&gt; 1 THEN round ( (PF1.CANTPROGRAMAT / COALESCE (PC.CANT, 1) * COALESCE (MAN.TPI, 0) + PF1.CANTPROGRAMAT / COALESCE (MAN.BPS, 1) * COALESCE (MAN.TU, 0)) ::numeric, 2)
                              ELSE round ( (COALESCE (MAN.TPI, 0) + PF1.CANTPROGRAMAT * COALESCE (MAN.TU, 0)) ::numeric, 2)
                         END * T1.TARIF)
                    / 60) ::numeric, 2) ,
           round ( (sum (CASE WHEN PC.CANT &lt;&gt; 1 THEN round ( (PF1.CANTPROGRAMAT / COALESCE (PC.CANT, 1) * COALESCE (MAN.TPI, 0) + PF1.CANTPROGRAMAT / COALESCE (MAN.BPS, 1) * COALESCE (MAN.TU, 0)) ::numeric, 2)
                              ELSE round ( (COALESCE (MAN.TPI, 0) + PF1.CANTPROGRAMAT * COALESCE (MAN.TU, 0)) ::numeric, 2)
                         END)
                   ) ::numeric, 2) ,
           round ( (sum (MAN.CANT)) ::numeric, 2),
           L.DENUMIRE
    FROM TMP_PROGRAMF1_MANEVRA PF1
      INNER JOIN COMANDA1    C1  ON PF1.CODCOMANDA1 = C1.CODCOMANDA1
      INNER JOIN PRODCOMP    PC  ON C1.CODRETETA    = PC.CODPRODCOMP
      INNER JOIN CMDPRODMAN  MAN ON MAN.CODCOMANDA1 = PF1.CODCOMANDA1
      INNER JOIN NOPER       OP  ON OP.CODOP        = MAN.CODOP
      INNER JOIN TARIFEMAN1  T1  ON T1.CODTARIF     = MAN.CODTARIF
      INNER JOIN TARIFEMAN   T   ON T1.CODTARIF     = T.CODTARIF
      INNER JOIN LOCMUNCA    L   ON L.CODLOC        = MAN.CODLOC
      WHERE GetAnLunaLucru() BETWEEN T1.ALSTART AND T1.ALSTOP
      GROUP by OP.CODOP, T1.CODTARIF, OP.DENUMIRE, T.DENUMIRE, T1.TARIF, L.DENUMIRE;
    INSERT INTO TMP_PROGRAMFMAN_MANEVRA(CODPFMAN,CODPROGRAMF,CODCMDPRODMAN,CANT)
    SELECT - ROW_NUMBER() OVER(),
           (SELECT CODPROGRAMF FROM TMP_PROGRAMF_MANEVRA) CODPROGRAMF,
           MAN.CODCMDPRODMAN,
           round(MAN.CANT, 2)
    FROM TMP_PROGRAMF1_MANEVRA PF1
         INNER JOIN CMDPRODMAN MAN ON MAN.CODCOMANDA1 = PF1.CODCOMANDA1;
  END IF;

  PERFORM PKG_PROGRAMF_CALCUL_GEST (XT, YT);
  PERFORM PKG_PROGRAMF_CALCUL_CMD (XT, YT);
  PERFORM PKG_PROGRAMF_update_stocuri (vAllGest, vAllTipCont);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_setvdingoto</obj_name>
  <obj_hashval>0c097e2cde4b5c4cb821bdc0ce317185</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_setvdingoto(avdingoto boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PROGRAMF.vDinGoTo',avDinGoTo,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_setct_monitor</obj_name>
  <obj_hashval>7c52a2de6bb4525769094cad992996f9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PROIECT.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_setdocommit</obj_name>
  <obj_hashval>caf2e705cfde2ff99cd97de260a51371</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_setdocommit(adocommit boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PROIECT.DoCommit',aDoCommit,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_setnecesar</obj_name>
  <obj_hashval>e1ba2988f30f71fd31d954877e0ecfcc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_setnecesar(anecesar numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PROIECT.vNecesar',(aNecesar)::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiectcrm_sp_lockrecord</obj_name>
  <obj_hashval>8870e5306942925cd047bb292bede8f0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiectcrm_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodProiectCRM INTO Tmp FROM PROIECTCRM WHERE CodProiectCRM = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_promo_setct_monitor</obj_name>
  <obj_hashval>f8fdc04d3075f1bf052a4ac69fe8aa27</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_promo_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_PROMO.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_catp_sp_insertrecord</obj_name>
  <obj_hashval>39e90c33a5e5656e1d85f371493ea4bf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_catp_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_RAC_CATP (CodRAC_CATP) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_raportp_nrdoc_i</obj_name>
  <obj_hashval>7b109cc99e475a325f0ccc7e45d85cd6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_raportp_nrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_RAPORTP.NRDOC_I', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_raportp_sp_gotorecord</obj_name>
  <obj_hashval>a2dbff03649aa44e51e76f61fc1d85e7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_raportp_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  nr    numeric;
  CodI1 numeric;
  I1    numeric;
  aAng  numeric;
  aCmd  varchar;
  aObj  varchar;
  aCodR numeric;
  vAnLuna numeric(20);
BEGIN
  --Florin 02.04.2024 - sinc. Oracle
  --Florin 22.07.2022 - sinc. Oracle (21.07.2022)
  --Florin 10.11.2020 - fixat #40962
  --Florin 09.01.2021 - format data
  --Florin 19.01.2021 - adaugat obs
  --Florin 04.02.2021 - fixat #42293
  --Florin 16.11.2021 - fixat 52001
  --Florin 30.12.2021 - sinc. Oracle (29.12.2021)
  --Florin 04.03.2022 - fixat 53374
  perform pkg_raportp_setct_monitor('MON_xx');

   begin
    select an*12+luna into vAnLuna from raportp where codraportp = recid;
  exception when others then vAnLuna := GetANLUCRU()*12+GetLUNALUCRU();
  end;
  INSERT INTO TMP_RaportP(CODRAPORTP, NRDOC, DATAI, DATAS, Intreruperi, PE_FORMATIE, CODCENTRU, SECTIE, FORMATIE, PROGRAMF, SUBUNITATEA, AN, LUNA, prefixdoc, carnetdoc, seriadoc, SCHIMB, Obs)
  SELECT CODRAPORTP, NRDOC, DATAI, DATAS, Intreruperi, PE_FORMATIE, CODCENTRU, SECTIE, FORMATIE, PROGRAMF, SUBUNITATEA, AN, LUNA, prefixdoc, carnetdoc, seriadoc, SCHIMB, Obs
  FROM RaportP WHERE CodRaportP = RecId;

  INSERT INTO TMP_RaportP0(CODRAPORTP0, CODRAPORTP, CODCOMANDA1, REALIZAT, REBUT, COMANDA, DENOBIECT, CODRETETA, UTILAJ, Codutilaj2c, Derealizat, CLIENTU, FURNU, SERIEF, OBS, Codexterncliu)
  SELECT P0.CODRAPORTP0, P0.CODRAPORTP, P0.CODCOMANDA1, P0.REALIZAT, P0.REBUT, C.PREFIXDOC || C.NRDOC || '/' || TO_CHAR(C.DATADOC, 'dd.mm.yyyy'), OB.DENUMIRE, C1.Codreteta, OBJU.DENUMIRE, U2C.CodUtilaj2C, CMD.Cant, CLI.DEN_PART, FURN.DEN_PART, U.SERIEF, P0.OBS, CLI.CODEXTERN
  FROM RaportP0 P0
      LEFT JOIN Comanda1   C1   ON  C1.CodComanda1  = P0.CodComanda1
      LEFT JOIN CMDPRODMAT CMD  ON  CMD.CODCOMANDA1 = C1.CODCOMANDA1 and  CMD.TIP = 0
      LEFT JOIN NartObj    Ob   ON  Ob.CodObiect    = C1.CodObiect
      LEFT JOIN Comanda    C    ON  C.CodComanda    = C1.CodComanda
      LEFT JOIN UTILAJE2C  U2C  ON  U2C.CODCOMANDA1 = C1.CODCOMANDA1
      LEFT JOIN UTILAJE    U    ON  U.CODUTILAJ     = U2C.CODUTILAJ
      LEFT JOIN NARTOBJ    OBJU ON  OBJU.CODOBIECT  = U.CODOBIECT
      LEFT JOIN NPART      CLI  ON  CLI.CODPART     = U.CODPART
      LEFT JOIN NPART      FURN ON  FURN.CODPART    = U.CODFURNIZOR
  WHERE P0.CodRaportP = RecId;

  INSERT INTO TMP_RaportP1(CODRAPORTP1, CODRAPORTP0, CODRAPORTP, ANGAJAT, Realizat, Indice, Rebut, DEN_ANGAJAT, MARCA, ProdRealizat, Prodrebut)
  SELECT P1.CODRAPORTP1, P1.CODRAPORTP0, P1.CODRAPORTP, P1.ANGAJAT, P1.Realizat, P1.Indice, P1.Rebut,
         CASE WHEN  P1.Angajat=0 THEN A.NUME ELSE  A.NUME || ' ' || A.PRENUME END ,
         A.MARCA, P1.Prodrealizat, P1.Prodrebut
  FROM RaportP1 P1 LEFT JOIN NPERS A ON  A.CodPers = P1.Angajat
  WHERE P1.CodRaportP = RecId;

  INSERT INTO tmp_raportp1c(codraportp1c, codraportp0, codraportp, angajat, realizat, rebut, prodrealizat, prodrebut, den_angajat, marca)
  SELECT ROW_NUMBER() OVER(), x.codraportp0, x.codraportp, x.angajat, x.realizat, x.rebut, x.prodrealizat, x.prodrebut, x.den_angajat, x.marca
  FROM (SELECT codraportp0, codraportp, angajat, sum( realizat) REALIZAT, sum( rebut) REBUT, sum( prodrealizat) PRODREALIZAT, sum( prodrebut) PRODREBUT, den_angajat, marca
        FROM tmp_raportp1
        GROUP BY codraportp0, codraportp, angajat, den_angajat, marca
       ) x;

  INSERT INTO tmp_raportp3(codraportp3, codraportp1, codraportp, codmotiv, ore)
  SELECT codraportp3, codraportp1, codraportp, codmotiv, ore FROM raportp3 WHERE codraportp = RecId;

  INSERT INTO TMP_RaportP2(CODRAPORTP2, CODRAPORTP1, CODCOMANDA1, CODMAN, REALIZAT, REBUT, CODOP, CODLOC, CODTARIF, TU, TUH, CODUTILAJ, VALOARE, INDEXOPER, COMANDA, UTILAJ, OPERATIE, DURATA, DURATAH, TARIF, TIPLOCMUNCA, DATASTART, DATASTOP, DATASTARTC, DATASTOPC, REFACUT, CODIES1, CODRAPORTP0)
  SELECT P2.CODRAPORTP2, P2.CODRAPORTP1, P2.CODCOMANDA1, P2.CODMAN, P2.REALIZAT, P2.REBUT, COALESCE( P2.CODOP, PM.codop),
         CASE WHEN  COALESCE( P2.CODMAN, 0) &gt; 0 THEN pm.codloc ELSE P2.CODLOC END ,
         COALESCE( P2.CODTARIF, pm.codtarif), COALESCE( P2.TU, pm.tu), COALESCE(P2.TU, pm.tu)/60, P2.CODUTILAJ,
         CASE WHEN  p2.codies1 &gt; 0 THEN i1.pu
              ELSE CASE WHEN  COALESCE( p2.codtarif, 0) = 0 THEN TM1.Tarif ELSE T1.Tarif END
         END  * COALESCE( P2.TU, pm.tu) * P2.REALIZAT / 60,
         PM.NrOp, C.PREFIXDOC || C.NRDOC || '/' || C.DATADOC, OB.DENUMIRE,
         COALESCE(PM.NROP::VARCHAR, '') || '/' || CASE WHEN  COALESCE( OP.codop, 0) = 0 THEN OPMan.DENUMIRE ELSE OP.Denumire END ,
         COALESCE( P2.TU, pm.tu) * P2.REALIZAT,
         COALESCE( P2.TU, pm.tu) * P2.REALIZAT / 60,
         CASE WHEN  p2.codies1 &gt; 0 THEN i1.pu ELSE CASE WHEN  COALESCE( p2.codtarif, 0) = 0 THEN TM1.Tarif ELSE T1.Tarif END END ,
         lm.tip, P2.DATASTART, P2.DATASTOP, to_char( P2.DATASTART, 'dd.mm.yyyy hh24:mi:ss'), to_char( P2.DATASTOP, 'dd.mm.yyyy hh24:mi:ss'),
         P2.REFACUT, P2.CODIES1, P1.CODRAPORTP0
  FROM RaportP P
      INNER JOIN RaportP1 P1 ON  P1.CodRaportP  = P.CodRaportP
      INNER JOIN RaportP2 P2 ON  P2.CodRaportP1 = P1.CodRaportP1
      LEFT  JOIN ProdMan  PM ON  PM.CodMan      = P2.CodMan
      LEFT  JOIN locmunca lm ON  p2.codloc      = lm.codloc
      left  JOIN TarifeMan1 T1 on T1.CodTarif = P2.codTarif AND vAnLuna BETWEEN t1.ALSTART AND t1.ALSTOP
      left  JOIN TarifeMan1 TM1 on TM1.CodTarif = Pm.codTarif AND vAnLuna BETWEEN tm1.ALSTART AND tm1.ALSTOP
      LEFT  JOIN NOper    Op    ON  Op.CodOp       = P2.CodOp
      LEFT  JOIN NOper    OpMan ON  OpMan.CodOp    = PM.CodOp
      LEFT  JOIN Comanda1 C1    ON  C1.CodComanda1 = P2.CodComanda1
      LEFT  JOIN Comanda  C     ON  C.CodComanda   = C1.CodComanda
      LEFT  JOIN UTILAJE  U     ON  P2.CODUTILAJ   = U.CODUTILAJ
      LEFT  JOIN NartObj  Ob    ON  Ob.CodObiect   = U.CodObiect
      LEFT  JOIN IESIRI1  I1    ON  I1.CODIES1     = P2.CODIES1
  WHERE P.CodRaportP = RecId;

  INSERT INTO tmp_raportp2c(codraportp2c, codraportp0, codcomanda1, codobiect, codman, realizat, rebut, codop, valoare, operatie, nrop)
  SELECT ROW_NUMBER() OVER(), x.codraportp0, x.codcomanda1, x.codobiect, x.codman, x.realizat, x.rebut, x.codop, x.valoare, x.operatie, x.indexoper
  FROM (SELECT codraportp0, codcomanda1, codobiect, codman, sum( realizat) REALIZAT, sum( rebut) REBUT, codop, sum( valoare) VALOARE, operatie, indexoper
        FROM tmp_raportp2
        GROUP BY codraportp0, codcomanda1, codobiect, codman, codop, operatie, indexoper
       ) x;

  FOR v_rec IN (SELECT * FROM tmp_raportp1c) LOOP
    UPDATE tmp_raportp1 SET codraportp1c = v_rec.codraportp1c WHERE codraportp0 = v_rec.codraportp0 and  codraportp = v_rec.codraportp and  angajat = v_rec.angajat;

    UPDATE tmp_raportp2 tmp SET codraportp1c = v_rec.codraportp1c
    WHERE tmp.codraportp1 IN (SELECT r1.codraportp1 FROM TMP_raportp1 r1 WHERE r1.codraportP1c = v_rec.codraportP1c);
  END LOOP;

  FOR v_rec IN (SELECT * FROM tmp_raportp2c tmp) LOOP
    UPDATE tmp_raportp2 SET codraportp2c = v_rec.codraportp2c
    WHERE codraportp0 = v_rec.codraportp0 and  COALESCE( codcomanda1, 0) = COALESCE( v_rec.codcomanda1, 0) and  COALESCE( codobiect, 0) = COALESCE( v_rec.codobiect, 0)
     and  COALESCE( codman, 0) = COALESCE( v_rec.codman, 0) and  codop = v_rec.codop;
  END LOOP;

  FOR v_rec IN (SELECT tmp.*, t1.codraportp1
                FROM tmp_raportp2c tmp
                    INNER JOIN tmp_raportp2 t2 ON  t2.codraportp2c = tmp.codraportp2c
                    INNER JOIN tmp_raportp1 t1 ON  t1.codraportp1  = t2.codraportp1
               )
  LOOP
    UPDATE tmp_raportp1 SET codraportp2c = v_rec.codraportp2c WHERE codraportp1 = v_rec.codraportp1;
  END LOOP;

  INSERT INTO TMP_MANPRODLINK(CODRAPORTP2, CODCMDPRODMAN, CANT, CODPROGRAMF1)
  SELECT CODRAPORTP2, CODCMDPRODMAN, CANT, CODPROGRAMF1
  FROM MANPRODLINK WHERE CODRAPORTP2 IN (SELECT CODRAPORTP2 FROM TMP_RAPORTP2);

  DELETE FROM TMP_MANPRODLINK_INITIAL;
  INSERT INTO TMP_MANPRODLINK_INITIAL SELECT * FROM TMP_MANPRODLINK;

  FOR v_rec IN (SELECT CODRAPORTP1 FROM TMP_RaportP1) LOOP
    UPDATE TMP_RaportP1
    SET
    VALOARE = (SELECT sum( Valoare) FROM TMP_RaportP2 WHERE CodRaportP1 = v_rec.CodRaportP1),
    Timp    = (SELECT sum( Durata)  FROM TMP_RaportP2 WHERE CodRaportP1 = v_rec.CodRaportP1)
    WHERE CodRaportP1 = v_rec.CodRaportP1;
  END LOOP;

  FOR v_rec IN (SELECT CODRAPORTP0 FROM TMP_RaportP0) LOOP
    UPDATE TMP_RaportP0
    SET
    REBUT = (SELECT sum( ProdREBUT) FROM TMP_RaportP1 WHERE CodRaportP0 = v_rec.CodRaportP0)
    WHERE CodRaportP0 = v_rec.CodRaportP0;
  END LOOP;

  SELECT Count( *) INTO NR FROM TMP_RAPORTP0;

  IF  COALESCE( NR, 0) = 0 THEN
    DELETE FROM TMP_RaportP1;
    I1 := 0;

    FOR v_rec IN (SELECT r2.CodRaportP2, r1.CodRaportP1, r2.CodComanda1
                  FROM Raportp2 r2 INNER JOIN RaportP1 r1 ON  r1.CodRaportP1 = r2.CodRaportP1
                  WHERE r1.CodRaportP = RecId
                 )
    LOOP
      SELECT Count( *) INTO NR FROM TMP_RAPORTP0 WHERE CodComanda1 = v_rec.CodComanda1;
      IF  Nr = 0 THEN
        SELECT C.PREFIXDOC || C.NRDOC || '/' || C.DATADOC, OB.DENUMIRE, C1.CodReteta
        INTO aCmd, aObj, aCodR
        FROM Comanda1 C1
            LEFT JOIN NartObj Ob ON  Ob.CodObiect = C1.CodObiect
            LEFT JOIN Comanda C  ON  C.CodComanda = C1.CodComanda
        WHERE C1.CodComanda1 = v_rec.CodComanda1;

        INSERT INTO TMP_RaportP0(CODRAPORTP0, CODRAPORTP, CODCOMANDA1, Comanda, Denobiect, Codreteta)
        VALUES(-V_REC.CODCOMANDA1, RecID, V_REC.CODCOMANDA1, aCmd, aObj, aCodR);
      END IF;

      SELECT Angajat INTO aAng FROM RAPORTP1 WHERE CodRaportP1 = v_rec.CodRaportP1;
      SELECT Count( *) INTO NR FROM TMP_RAPORTP1 WHERE Angajat = aAng and  CodRaportP0 = -v_rec.CodComanda1;
      IF  Nr = 0 THEN
        I1 := I1 - 1;
        SELECT CASE WHEN  A.CodPers=0 THEN A.NUME ELSE  A.NUME || ' ' || A.PRENUME END , A.MARCA
        INTO aObj, aCodR
        FROM NPERS A WHERE A.CodPers = aAng;

        INSERT INTO TMP_RaportP1(CODRAPORTP1, CODRAPORTP0, CODRAPORTP, Angajat, DEN_ANGAJAT, MARCA)
        VALUES(I1, -V_REC.CODCOMANDA1, RecID, aAng, aObj, aCodR);

        CodI1 := I1;
      ELSE
        SELECT CodRaportP1 INTO CodI1 FROM TMP_RAPORTP1 WHERE CodRaportP0 = -v_rec.CodComanda1;
      END IF;

      UPDATE TMP_RAPORTP2 SET CodRaportP1 = CodI1 WHERE CodRaportP2 = v_rec.CodRaportP2;
    END LOOP;
  END IF;
  PERFORM PKG_CFGTABLES_EXT_GOTORECORD(63);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_setp_flgtipcont</obj_name>
  <obj_hashval>598ac0e2a1b35d983796e71aba40fd68</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_setp_flgtipcont(ap_flgtipcont boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_SELFISAMAG.p_flgTipCont',ap_flgTipCont,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selfisamag_setp_listid</obj_name>
  <obj_hashval>d8fd3547d7c1bf12dd9b5b8bb7eebc8b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selfisamag_setp_listid(ap_listid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_SELFISAMAG.p_ListID',to_char(ap_ListID,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_locmunca_preparegantt</obj_name>
  <obj_hashval>5288005f5310b703db6182a9df5be571</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_locmunca_preparegantt(adata1 character varying, adata2 character varying, adatastart character varying, adatastop character varying, acodproiect numeric DEFAULT 0, acant numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC      RECORD;
  V       RECORD;
  W       RECORD;
  aDataEnd   date;
  aDataBegin date;
  DataStart  date;
  DataStop   date;
  aSapt      numeric;
  aCodLM     numeric;
  i          numeric;
  DataMax    date;
  DataMin    date;
  sSQL       varchar;
  Min1       numeric;
  Max1       numeric;
  Cifre      numeric;
  Min1c      numeric;
  Max1c      numeric;
  CifreC     numeric;
  G_SUBUNIT  numeric;
  OreMatrita double precision;
  OreMasina  double precision;
BEGIN
  --Florin 13.06.2023 - sinc. Oracle
  --Florin 13.04.2023 - fixat 57942
  --Florin 22.11.2022 - sinc. Oracle
  --Florin 20.10.2022 - sinc. Oracle (19.10.2022)
  --Florin 26.09.2022 - sinc. Oracle (23.09.2022)
  --Florin 23.09.2022 - sinc. Oracle (22.09.2022)
  --Florin 20.09.2022 - sinc. Oracle
  --Florin 16.12.2021 - fixat 52325
  --Laura 27.11.2021 - sinc Oracle (26.11.2021)
  --Laura 18.11.2021 - sinc Oracle (17+18.11.2021)
  --Adina 12.08.2021 - sinc.Oracle din 11.08.2021
  --Adina 09.07.2021
  G_SUBUNIT := current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric;
  DataMin   := TO_DATE(aData1    , 'DD.MM.YYYY');
  DataMax   := TO_DATE(aData2    , 'DD.MM.YYYY');
  DataStart := TO_DATE(aDataStart, 'DD.MM.YYYY');
  DataStop  := TO_DATE(aDataStop , 'DD.MM.YYYY');

  SELECT Min(CodComanda1), Max(CodComanda1)
  INTO Min1, Max1
  FROM Comanda1 c1 INNER JOIN Comanda C ON  c.codcomanda = c1.codcomanda
  WHERE TipDoc = 53 and  Operat = 1 and  COALESCE(Inchisa, 0) = 0 and C1.RESTACCEPTAT &gt; 0;

  Cifre := Length((Max1 - Min1)::varchar);
  Min1  := Min1 - 1;

  SELECT Min(CodComanda1), Max(CodComanda1)
  INTO Min1c, Max1c
  FROM Comanda1 c1 INNER JOIN Comanda C ON  c.codcomanda = c1.codcomanda
  WHERE TipDoc = 18 and  Operat = 1 and  COALESCE(Inchisa, 0) = 0 and C1.RESTACCEPTAT &gt; 0;

  CifreC := Length((Max1c - Min1c)::varchar);
  Min1c  := Min1c - 1;

  DELETE FROM TMP_CMDGANTT;
  IF  aCodProiect &gt; 0 THEN
    INSERT INTO TMP_CMDGANTT
    SELECT PN.CODPROIECTNOD CODCOMANDA1,
           PN.CODPROIECT CODCOMANDA,
           PN.codreteta,
           0 PRIORITATE,
           NULL DATASTART,
           NULL TERMEN,
           ACANT CANTLANSAT,
           NULL AS DOCUMENT,
           NULL DATADOC,
           o.Denumire DENOBIECT,
           u.DEN_UM UM,
           uu.DEN_UM DEN_UM1,
           Coalesce(lm.codlocdef, Man.codloc) CODLM,
           0 CODCMDPRODMAN,
           op.codop CODOPERATIE,
           '| '||coalesce(SubStr(PN.Indexparinte, 3, 200),'')||'='||coalesce(o.Denumire,'')||Chr(13)||'| '||coalesce(Man.nrop::varchar ,'')||'.'||coalesce(op.denumire,'') OPERATIE,
           PC.OBS AS DENRETETA,
           P.codProiect,
           P.Versiune,
           PN.NODORIGINAL NODPARINTE,
           PN.CODPROIECTNOD,
           PN.NIVEL NIVELNOD,
           PN.POZITIE POZNOD,
           0 CODCMD1PARINTE,
           0 CODGEST,
           NULL DEN_GEST,
           lm.denumire LOCMUNCA,
           Round(Man.tu * case when coalesce(man.fix,0) = 0 then ACANT/COALESCE(Man.BPS,1)/ 60 else 1 end, 5) TotalOre,
           Round(Man.tu * case when coalesce(man.fix,0) = 0 then ACANT/COALESCE(Man.BPS,1)/ 60 else 1 end, 5) OreGantt,
           case when man.fix &gt; 0 then man.tu else Man.tu/COALESCE(Man.BPS,1) end TU,
           Man.NROP NROPER,
           0 CODCOMANDACLI,
           NULL DOCUMENTCLI,
           NULL DATADOCCC,
           0 CODCOMANDA1,
           NULL DataStartCC,
           NULL TERMENCC,
           NULL DEN_PART,
           o.Denumire DENPRODUS,
           u.den_um UMPRODUS,
           ACANT CANTPRODUS,
           Man.Incepere INCEPEREOP,
           PN.Incepere INCEPEREJNOD,
           Man.Decalaj DECALAJOP,
           PN.Decalaj DECALAJNOD,
           PN.Indexparinte,
           507,
           man.fix,
           man.codman,
           O.CODOBIECT
    FROM ProiectNod PN
      INNER JOIN prodcomp PC  ON  PC.codprodcomp  = PN.codreteta
      INNER JOIN nartobj  o   ON  o.codobiect     = PN.codobiect
      INNER JOIN nart     A   ON  A.CODARTICOL    = o.CODARTICOL
      INNER JOIN NUM      U   ON  U.CodUM         = A.UM
      LEFT  JOIN NUM      UU  ON  UU.CodUM        = A.UM1
      LEFT  JOIN Proiect  P   ON  P.Codproiect    = PN.CodProiect
      INNER JOIN prodman  Man ON  Man.CODPRODCOMP = PC.CODPRODCOMP
      LEFT  JOIN noper    op  ON  op.codop        = Man.codop
      LEFT  JOIN locmunca lm  ON  lm.codloc       = Man.codloc
    where PN.CODPROIECT = ACODPROIECT and coalesce(lm.fara_gant,0) = 0;
  ELSE
    INSERT INTO TMP_CMDGANTT
    SELECT CInt1.codcomanda1,
           CInt1.codcomanda,
           CInt1.codreteta,
           case when coalesce(g.prioritate,0) = 0 then CInt1.Prioritate else coalesce(g.prioritate,0) end Prioritate,
           CInt1.DataStart,
           CInt1.Termen,
           PMAT.cant Cantlansat,
           coalesce(CInt.PREFIXDOC,'') || coalesce(CInt.NrDoc::varchar ,'') || '.' || coalesce(LPAD(CInt1.IndexLocal::varchar, 3, '0'),'') AS DOCUMENT,
           CInt.Datadoc,
           o.Denumire DENOBIECT,
           u.DEN_UM UM,
           uu.DEN_UM DEN_UM1,
           CmdPMan.codloc CODLM,
           CmdPMan.codcmdprodman,
           op.codop CODOPERATIE,
           '| '||coalesce(SubStr(PN.Indexparinte, 3, 200),'')||'='||coalesce(o.Denumire,'')||Chr(13)||'| '||coalesce(CmdPMan.nrop::varchar ,'')||'.'||coalesce(op.denumire,'') OPERATIE,
           ProdCmp.OBS AS DENRETETA,
           CCli1.codProiect,
           Pr.Versiune,
           LANS1.NODPARINTE,
           PN.CODPROIECTNOD,
           CInt1.NIVEL NIVELNOD,
           CInt1.POZITIE POZNOD,
           LANS1.CODCMD1P CODCMD1PARINTE,
           ng.codgest,
           ng.den_gest,
           lm.denumire LOCMUNCA,
           Round(CmdPMan.tu * case when coalesce(CmdPMan.fix,0) = 0 then CInt1.cantacceptat/COALESCE(CmdPMan.BPS,1)/60 else 1 end, 5) TotalOre,
           case when coalesce(CmdPMan.fix,0) = 0 then Round(coalesce(G.AreGant, 0) * CInt1.cantacceptat/coalesce(CmdPMan.BPS,1)/60, 5) else 1 end OreGantt,
           case when CmdPMan.fix &gt; 0 then cmdpman.tu else CmdPMan.tu/coalesce(CmdPMan.BPS,1) end TU,
           CmdPMan.NROP NROPER,
           CCli.codcomanda CODCOMANDACLI,
           coalesce(CCli.PREFIXDOC,'') || coalesce(CCli.NrDoc::varchar ,'') || '.' || coalesce(LPAD(CCli1.IndexLocal::varchar, 3, '0'),'') DOCUMENTCLI,
           CCli.DataDoc DATADOCCC,
           CCli1.codcomanda1,
           coalesce(CCli1.DataStart,CCli.DataDoc)  DataStartCC,
           CCli1.Termen TERMENCC,
           P.Den_Part,
           oc.Denumire DENPRODUS,
           uc.den_um UMPRODUS,
           CCli1.cantacceptat CANTPRODUS,
           PMan.Incepere INCEPEREOP,
           LANS1.Incepere INCEPEREJNOD,
           PMan.Decalaj DECALAJOP,
           LANS1.Decalaj DECALAJNOD,
           PN.Indexparinte,
           CCLI.TIPDOC,
           cmdpman.fix,
           pman.codman,
           O.CODOBIECT
    FROM comanda1           CInt1
      INNER JOIN CMDPRODMAT PMAT ON PMAT.CODCOMANDA1 = CINT1.CODCOMANDA1 AND PMAT.TIP = 0
      INNER JOIN comanda    CInt    ON  CInt.codcomanda     = CInt1.codcomanda
      INNER JOIN Lansare1   LANS1   ON  LANS1.CODCMD1       = CInt1.codComanda1
      LEFT  JOIN ProiectNod PN      ON  PN.CodproiectNod    = LANS1.CodProiectNod
      INNER JOIN Lansare0   LANS0   ON  LANS0.codLansare0   = LANS1.codLansare0
      INNER JOIN Lansare    LANS    ON  LANS .codLansare    = LANS0.codLansare
      INNER JOIN prodcomp   ProdCmp ON  ProdCmp.codprodcomp = CInt1.codreteta
      INNER JOIN nartobj    o       ON  o.codobiect         = CInt1.codobiect
      INNER JOIN nart       A       ON  A.CODARTICOL        = o.CODARTICOL
      INNER JOIN NUM        U       ON  U.CodUM             = A.UM
      LEFT  JOIN NUM        UU      ON  UU.CodUM            = A.UM1
      LEFT  JOIN comanda1   CCli1   ON  LANS0.CODCMD1       = CCli1.codcomanda1
      LEFT  JOIN comanda    CCli    ON  CCli.CODCOMANDA     = CCli1.codcomanda
      LEFT  JOIN Proiect    Pr      ON  Pr.Codproiect       = CCli1.CodProiect
      LEFT  JOIN nartobj    oc      ON  oc.codobiect        = CCli1.codobiect
      INNER JOIN nart       Ac      ON  Ac.CODARTICOL       = oc.CODARTICOL
      INNER JOIN NUM        Uc      ON  Uc.CodUM            = Ac.UM
      LEFT  JOIN npart      p       ON  p.codpart           = CCli.PARTENER
      LEFT  JOIN cmdprodman CmdPMan ON  CmdPMan.codcomanda1 = CInt1.codcomanda1
      LEFT  JOIN prodman    PMan    ON  PMan.CODMAN         = CmdPMan.CODMAN
      LEFT  JOIN ngest      ng      ON  ng.codgest           = CInt.codgest
      LEFT  JOIN noper      op      ON  op.codop            = CmdPMan.codop
      LEFT  JOIN locmunca   lm      ON  lm.codloc           = CmdPMan.codloc
      LEFT  JOIN (select distinct CODCMDPRODMAN, 1 AreGant, Prioritate from Gantt) G ON G.CODCMDPRODMAN = CmdPMan.CODCMDPRODMAN
      LEFT  JOIN (SELECT  DISTINCT CODCMDPRODMAN, 1 AREGANT FROM Gantt) GT ON  GT.CODCMDPRODMAN = CmdPMan.CODCMDPRODMAN
      LEFT JOIN ( select distinct CodComanda1 from Gantt G
              inner join (select CodGantt, Max(Deplasare) Zile from Gantt1 group by CodGantt) G1 on G.CodGantt = G1.CodGantt
              WHERE DStart BETWEEN DataMin AND DataMax or
                  add_days(G.DStart, Zile::integer) between DataMin and DataMax
            ) GX ON  GX.CODCOMANDA1 = CCli1.CODCOMANDA1
      where CInt.TipDoc = 53 and CInt.Operat = 1 and coalesce(CInt.Inchisa,0) = 0  and PMAT.REST &gt; 0
      and (CCli1.DataStart between DataMin and DataMax OR GX.CodComanda1 is not null)
      AND (G_SUBUNIT = 1 OR (CCLI.SUBUNITATEA = G_SUBUNIT AND CCLI.TIPDOC = 18) OR (CCLI.SUBUNITSURSA = G_SUBUNIT AND CCLI.TIPDOC = 44))
      and coalesce(lm.fara_gant,0) = 0;
  END IF;

  SELECT (SELECT wme_result FROM iso_week_to_date(NULL, (EXTRACT(YEAR FROM DataMin))::numeric, to_char(DataMin,'iw')::numeric)),     --TRUNC(DataMin,'iw')
         add_days((SELECT wme_result FROM iso_week_to_date(NULL, (EXTRACT(YEAR FROM DataMax))::numeric, to_char(DataMax,'iw')::numeric)), 6)  --Trunc(TRUNC(DataMax,'iw') + 6)
  INTO aDataBegin, aDataEnd;

  aSapt := to_char(aDataEnd, 'iw')::numeric;

  PERFORM umple_tmp_zile(DataStart, DataStop);
  DELETE FROM TMP_OREGANTT;
  DELETE FROM TMP_OREGANTT1;
  INSERT INTO TMP_OREGANTT1
  WITH
  Recs as
     ( SELECT L.CodLoc CodLM, D.Ziua AS Data from Tmp_Zile D, LocMunca L),
    OLM1 as
     (SELECT L.CodLoc CodLM, L1.CodLoc1 CodLM1, coalesce(L1.ORE, G.Ore) Ore
      FROM LocMunca L
        inner join LocMunca1 L1 on L1.CodLoc = L.CodLoc
        inner join ( Select CodGest, coalesce(NrSchimburi, 0) * coalesce(OreSchimb, 0) Ore from NGEST) G on G.CodGest = L1.CodGest
     )
    Select to_char(Data,'iw')::numeric Sapt, Data, CodLM, CodLM1, Ore, LM1Activ CateLM1
    from
    (
    select Recs.CodLM, OLM1.CodLM1, Recs.Data, coalesce(OreLM.Ore, OLM1.Ore) Ore, Case when ORELM.ORE = 0 then 0 else 1 end LM1Activ,
           OLM1.Ore OreDef, Case when OreLM.Ore = OLM1.Ore then null else OreLM.Ore end OreExcept
    from Recs
      left join OLM1  on OLM1.CodLM   = Recs.CodLM
      left join OreLM on OreLM.DataLM = Recs.Data and OreLM.Codlm1 = OLM1.CodLM1
    ) X;
   --asta e tabela care va modifica TMP_OREGANTT
  if aCodProiect = 0 then
     for V in (
        select * from LocMunca2 where LocMunca2.DataStart between DataMin and DataMax
                              or  LocMunca2.DataStop between DataMin and DataMax
                              or  (LocMunca2.DataStart &lt; DataMin and LocMunca2.DataStop &gt; DataMax)
    ) loop
      if v.datastart = v.datastop then
          OreMatrita := Coalesce(v.Orestart,0) + Coalesce(v.orestop,0);
          OreMasina  :=  OreMatrita + Round(((Coalesce(v.minuneon,0)+Coalesce(v.minuneoff,0))/60)::numeric,2);
          update TMP_OREGANTT1 set ORE = ORE + OreMatrita where DATA = v.datastart and CODLM1 = v.codloc1;
          update TMP_OREGANTT1 set ORE = ORE - OreMasina  where DATA = v.datastart and CODLM1 = v.codloc1asoc;
      else
          OreMatrita := Coalesce(v.Orestart,0);
          OreMasina  :=  OreMatrita + Round((Coalesce(v.minuneon,0)/60)::numeric,2);
          update TMP_OREGANTT1 set ORE = ORE + OreMatrita where DATA = v.datastart and CODLM1 = v.codloc1;
          update TMP_OREGANTT1 set ORE = ORE - OreMasina  where DATA = v.datastart and CODLM1 = v.codloc1asoc;
          OreMatrita := Coalesce(v.orestop,0);
          OreMasina  :=  OreMatrita + Round((Coalesce(v.minuneoff,0)/60)::numeric,2);
          update TMP_OREGANTT1 set ORE = ORE + OreMatrita where DATA = v.datastop and CODLM1 = v.codloc1;
          update TMP_OREGANTT1 set ORE = ORE - OreMasina  where DATA = v.datastop and CODLM1 = v.codloc1asoc;
          for w in ( select * from TMP_OREGANTT1
                   where CodLM1 = v.codloc1asoc and Data between v.datastart + 1 and v.Datastop - 1) loop
            OreMasina  :=  Coalesce(w.ORE,0);
            update TMP_OREGANTT1 set ORE = 0          where DATA = w.data and CODLM1 = v.codloc1asoc;
            update TMP_OREGANTT1 set ORE = OreMasina  where DATA = w.data and CODLM1 = v.codloc1;
          end loop;
      end if;
    end loop;
 end if;
  INSERT INTO TMP_OREGANTT
  Select Sapt, Data, CodLM, 0, Sum(Ore) Ore, Sum(CateLM1) CateLM1 from TMP_OREGANTT1 group by CodLM, Data, Sapt;


/*
  EXECUTE '
    INSERT INTO TMP_OREGANTT
    WITH RECURSIVE drec(Data) AS (
      SELECT $1 AS Data
      UNION ALL
      SELECT Data + 1 FROM drec WHERE Data &lt; $2
    ),
    Recs as
     ( SELECT L.CodLoc CodLM, D.Data from drec D, LocMunca L),
    OLM1 as
     (SELECT L.CodLoc CodLM, L1.CodLoc1 CodLM1, coalesce(L1.ORE, G.Ore) Ore
      FROM LocMunca L
        inner join LocMunca1 L1 on L1.CodLoc = L.CodLoc
        inner join ( Select CodGest, coalesce(NrSchimburi, 0) * coalesce(OreSchimb, 0) Ore from NGEST) G on G.CodGest = L1.CodGest
     )
    Select to_char(Data,''iw'')::numeric Sapt, Data, CodLM, Sum(Ore) Ore, Sum(LM1Activ) CateLM1
    from
    (
    select Recs.CodLM, OLM1.CodLM1, Recs.Data, coalesce(OreLM.Ore, OLM1.Ore) Ore, Case when ORELM.ORE = 0 then 0 else 1 end LM1Activ,
           OLM1.Ore OreDef, Case when OreLM.Ore = OLM1.Ore then null else OreLM.Ore end OreExcept
    from Recs
      left join OLM1  on OLM1.CodLM   = Recs.CodLM
      left join OreLM on OreLM.DataLM = Recs.Data and OreLM.Codlm1 = OLM1.CodLM1
    ) X group by CodLM, Data
    order by CodLM, Data' USING DataStart, DataStop;
*/

  aSapt     := -999;
  aCodLM    := -999;
  i         := 0;
  DataStart := null;

  DELETE FROM TMP_SAPTGANTT;

  FOR V_Rec IN (SELECT * FROM Tmp_Oregantt WHERE Data BETWEEN aDataBegin AND aDataEnd ORDER BY CodLM , Data , Sapt) LOOP
    IF  v_rec.Sapt &lt;&gt; aSapt or  v_rec.CodLM &lt;&gt; aCodLM THEN
      aSapt     := v_rec.Sapt;
      aCodLM    := v_rec.CodLM;
      DataStart := V_REC.DATA;

      INSERT INTO TMP_SAPTGANTT(CodLM, Data1, An, Luna, Sapt)
      VALUES(V_REC.CODLM, V_REC.DATA, Extract( Year FROM V_REC.DATA), Extract( Month FROM V_REC.DATA), v_rec.Sapt);
    END IF;

    i := TRUNC(V_REC.DATA - DataStart + 1);
    sSQL := 'Update TMP_SAPTGANTT set Z' || coalesce(i::varchar,'') || '=' || COALESCE(V_REC.ORE, 0)::varchar ||
            ' WHERE CodLM = ' || coalesce(V_REC.CodLM::varchar ,'') || ' and Sapt = ' || coalesce(V_REC.SAPT::varchar,'');
    EXECUTE sSQL;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mifix_sp_post_reeval</obj_name>
  <obj_hashval>f55d1b011b1189a59a19b6fea8c06449</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mifix_sp_post_reeval(datadoc character varying, tip numeric, acoddoc1 numeric, atipdoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC          RECORD;
  NR             numeric := 0;
  aCODNIRSTOCNOU double precision;
  aPRETNOU       double precision := 0;
  aNEUTIL        double precision := 0;
  aTIPREEVAL     numeric := 0;
  aCODNIRSERNOU  NUMERIC(20, 0);
BEGIN
  --Florin 03.07.2025 - sinc. Oracle
  --Adina 14.01.2021 sinc.Oracle
  DELETE FROM TMP_JURNAL  WHERE TIPDOC &lt;&gt; 36;
  DELETE FROM TMP_JURNAL1 WHERE TIPDOC &lt;&gt; 36;
  aTIPREEVAL := TIP;

  FOR V_REC IN (SELECT TMP.*, T.NRDOC NRDOCTRANSF
                FROM TMP_MIFIX TMP
                     LEFT JOIN TRANSF T ON  T.CODTRANSF = TMP.NRDOCREEVAL
                WHERE (PRETREEVAL IS NOT NULL AND PRETREEVAL &lt;&gt; PRET)
                      OR
                      (AMOREEVAL IS NOT NULL AND AMOREEVAL &lt;&gt; AMO)
                      OR
                      (aTIPREEVAL = 1)
               )
  LOOP
    IF  V_REC.CODNIRSTOCNOU &lt; 0 THEN
      BEGIN
        SELECT CODNOU INTO aCODNIRSTOCNOU FROM TMP_NIRSTOC_RECOD WHERE CODVECHI = V_REC.CODNIRSTOCNOU;
      EXCEPTION WHEN OTHERS THEN
        aCODNIRSTOCNOU := V_REC.CODNIRSTOCNOU;
      END;
    ELSE
      aCODNIRSTOCNOU := V_REC.CODNIRSTOCNOU;
    END IF;

    IF V_REC.PRETREEVAL IS NULL THEN
      aPRETNOU := V_REC.PRET;
    ELSE
      aPRETNOU := V_REC.PRETREEVAL;
    END IF;

    IF V_REC.NEUTILREEVAL IS NULL THEN
      aNEUTIL := V_REC.NEUTIL;
    ELSE
      aNEUTIL := V_REC.NEUTILREEVAL;
    END IF;

    SELECT MIN(CODNIRSER) INTO aCODNIRSERNOU FROM NIRSER WHERE CODNIRSTOC =aCODNIRSTOCNOU;

    UPDATE MIFIX1
    SET
      CODNIRSTOC    = aCODNIRSTOCNOU,
      PRETVECHI     = V_REC.PRET,
      PRETINITIAL   = CASE WHEN  COALESCE( PRETINITIAL, 0) = 0 THEN V_REC.PRET ELSE PRETINITIAL END ,
      PRETINITIAL_F = CASE WHEN COALESCE(PRETINITIAL_F, 0) = 0 THEN V_REC.PRET ELSE PRETINITIAL_F END,
      PRET          = aPRETNOU,
      NEUTIL        = aNEUTIL,
      AMOVECHI      = V_REC.AMOINI,
      AMO           = CASE WHEN  COALESCE( V_REC.TIPREEVAL, 0) = 1 AND  COALESCE( V_REC.INCLUDRATA, 0) = 1 THEN V_REC.AMOINI
                           WHEN  COALESCE( V_REC.TIPREEVAL, 0) = 0 AND  COALESCE( V_REC.INCLUDRATA, 0) = 1 THEN V_REC.AMOINI + (  V_REC.AMOREEVAL - V_REC.AMO)
                           ELSE V_REC.AMOREEVAL
                      END ,
      INCLUDRATA    = V_REC.INCLUDRATA,
      DATAREEVAL    = TO_DATE( DATADOC, 'dd.mm.yyyy'),
      TIPREEVAL     = TIP,
      CODNIRSER  = aCODNIRSERNOU
    WHERE CODMIFIX1 = V_REC.CODMIFIX1 AND ANSTART = getANLUCRU() AND LUNASTART = getLUNALUCRU();

    UPDATE MIFIX1
    SET
      CODNIRSTOC = aCODNIRSTOCNOU,
      PRET       = aPRETNOU,
      NEUTIL     = aNEUTIL
    WHERE CODMIFIX = V_REC.CODMIFIX AND CODNIRSTOC = V_REC.CODNIRSTOC AND  ANSTART * 12 + LUNASTART &gt; getANLUCRU() * 12 + getLUNALUCRU();

    INSERT INTO FISAMF(CODFISAMF, CODMIFIX, CODOPERATIE, DATAOPERATIE, GESTSURSA, GESTDEST, PRETI, PRETE, PREFIXDOC, NRDOC, CODDOC1, TIPDOC, CANT)
    VALUES(NEXTVAL('SEQ_FISAMF_CODFISAMF'), V_REC.CODMIFIX, 6, V_REC.DATAREEVAL, V_REC.CODGEST, V_REC.CODGEST, V_REC.PRET, V_REC.PRETREEVAL, 'PV',
           V_REC.NRDOCTRANSF, aCODDOC1, aTIPDOC, V_REC.CANT
          );
  END LOOP;

  DELETE FROM JURNAl1
  WHERE TIPDOC = 36 AND  AN = getANLUCRU() AND LUNA = getLUNALUCRU()
        AND CODDOC IN (SELECT CODMIFIX FROM TMP_MIFIX_INITIAL)
        AND CODJURNAL1 NOT IN (SELECT CODJURNAL1 FROM TMP_JURNAl1);

  FOR V_REC IN (SELECT * FROM TMP_JURNAL1) LOOP
    IF  V_REC.CODJURNAL1 &gt; 0 THEN
      UPDATE JURNAL1
      SET
        CODDOC        = V_REC.CODDOC,
        TIPDOC        = V_REC.TIPDOC,
        INDEXLOCAL    = V_REC.INDEXLOCAL,
        CODBAZAD      = V_REC.CODBAZAD,
        ICONTBAZAD    = V_REC.ICONTBAZAD,
        TIPBAZAD      = V_REC.TIPBAZAD,
        CODBAZAC      = V_REC.CODBAZAC,
        ICONTBAZAC    = V_REC.ICONTBAZAC,
        TIPBAZAC      = V_REC.TIPBAZAC,
        CODDESCRD     = V_REC.CODDESCRD,
        ICONTD        = V_REC.ICONTD,
        TIPCONTD      = V_REC.TIPCONTD,
        ANALITICCONTD = V_REC.ANALITICCONTD,
        CODDESCRC     = V_REC.CODDESCRC,
        ICONTC        = V_REC.ICONTC,
        TIPCONTC      = V_REC.TIPCONTC,
        ANALITICCONTC = V_REC.ANALITICCONTC,
        GEST          = V_REC.GEST,
        VALOARE       = V_REC.VALOARE,
        VALOAREV      = V_REC.VALOAREV,
        VALOAREGRUP   = V_REC.VALOAREGRUP,
        OBS           = V_REC.OBS,
        AN            = V_REC.AN,
        LUNA          = V_REC.LUNA,
        DIRTY         = V_REC.DIRTY,
        SUBUNITATEA   = V_REC.SUBUNITATEA,
        DATADOC       = V_REC.DATADOC
      WHERE CODJURNAL1 = V_REC.CODJURNAl1;
    ELSE
      INSERT INTO JURNAL1(CODJURNAL1, CODDOC, TIPDOC, INDEXLOCAL, CODBAZAD, ICONTBAZAD, TIPBAZAD, CODDESCRD, ICONTD, TIPCONTD,
                          ANALITICCONTD, CODBAZAC, ICONTBAZAC, TIPBAZAC, CODDESCRC, ICONTC, TIPCONTC, ANALITICCONTC, GEST,
                          VALOARE, VALOAREV, VALOAREGRUP, OBS, AN, LUNA, DIRTY, SUBUNITATEA, DATADOC
                         )
      VALUES(NEXTVAL('SEQ_JURNAL1_CODJURNAL1'), V_REC.CODDOC, V_REC.TIPDOC, V_REC.INDEXLOCAL, V_REC.CODBAZAD, V_REC.ICONTBAZAD,
             V_REC.TIPBAZAD, V_REC.CODDESCRD, V_REC.ICONTD, V_REC.TIPCONTD, V_REC.ANALITICCONTD, V_REC.CODBAZAC, V_REC.ICONTBAZAC,
             V_REC.TIPBAZAC, V_REC.CODDESCRC, V_REC.ICONTC, V_REC.TIPCONTC, V_REC.ANALITICCONTC, V_REC.GEST, V_REC.VALOARE,
             V_REC.VALOAREV, v_rec.VALOAREGRUP, V_REC.OBS, V_REC.AN, V_REC.LUNA, V_REC.DIRTY, V_REC.SUBUNITATEA, V_REC.DATADOC
            );
    END IF;
  END LOOP;

  DELETE FROM JURNAL
  WHERE TIPDOC = 36 AND AN = getANLUCRU() AND LUNA = getLUNALUCRU()
        AND CODDOC IN (SELECT CODMIFIX FROM TMP_MIFIX_INITIAL)
        AND CODJURNAL NOT IN (SELECT CODJURNAL FROM TMP_JURNAL);

  FOR V_REC IN (SELECT * FROM TMP_JURNAL) LOOP
    IF  V_REC.CODJURNAL &gt; 0 THEN
      UPDATE JURNAL
      SET
        CODDOC        = V_REC.CODDOC,
        TIPDOC        = V_REC.TIPDOC,
        INDEXLOCAL    = V_REC.INDEXLOCAL,
        CONTD         = V_REC.CONTD,
        CONTC         = V_REC.CONTC,
        GEST          = V_REC.GEST,
        VALOARE       = V_REC.VALOARE,
        VALOAREV      = V_REC.VALOAREV,
        VALOAREGRUP   = v_rec.VALOAREGRUP,
        OBS           = V_REC.OBS,
        AN            = V_REC.AN,
        LUNA          = V_REC.LUNA,
        SUBUNITATEA   = V_REC.SUBUNITATEA,
        CODAnalizaNod = v_rec.CODAnalizaNod,
        CODCENTRU     = v_rec.CODCENTRU,
        DATADOC       = V_REC.DATADOC,
      DOCUMENT        = V_REC.DOCUMENT
      WHERE CODJURNAL = V_REC.CODJURNAl;
    ELSE
      INSERT INTO JURNAL(CODJURNAL, CODDOC, TIPDOC, INDEXLOCAL, CONTD, CONTC, GEST, VALOARE, VALOAREV, VALOAREGRUP, OBS, AN, LUNA,
                         SUBUNITATEA, CODAnalizaNod, CODCENTRU, DATADOC, DOCUMENT
                        )
      VALUES(NEXTVAL('SEQ_JURNAL_CODJURNAL'), V_REC.CODDOC, V_REC.TIPDOC, V_REC.INDEXLOCAL, V_REC.CONTD, V_REC.CONTC, V_REC.GEST,
                     V_REC.VALOARE, V_REC.VALOAREV, v_rec.VALOAREGRUP, V_REC.OBS, V_REC.AN, V_REC.LUNA, V_REC.SUBUNITATEA,
                     v_rec.CODAnalizaNod, v_rec.CODCENTRU, V_REC.DATADOC, V_REC.DOCUMENT
            );
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_RULAJ) LOOP
    SELECT COUNT( *) INTO NR
    FROM NCONTRUL
    WHERE CODCONT = V_REC.CODCONT AND AN = getANLUCRU() AND LUNA = getLUNALUCRU();

    IF  NR = 0 THEN
      INSERT INTO NCONTRUL(CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, AN, LUNA)
      VALUES(NEXTVAL('SEQ_NCONTRUL_CODCONTRUL'), V_REC.CODCONT, 0, 0, 0, 0, 0, 0, 0, 0, getANLUCRU(), getLUNALUCRU());
    END IF;

    UPDATE NCONTRUL
    SET
      RULAJCD  = RULAJCD  + (CASE WHEN  V_REC.TIP = 'D' THEN V_REC.VALOARE  ELSE 0 END ) ,
      RULAJCC  = RULAJCC  + (CASE WHEN  V_REC.TIP = 'C' THEN V_REC.VALOARE  ELSE 0 END ) ,
      RULAJVCD = RULAJVCD + (CASE WHEN  V_REC.TIP = 'D' THEN V_REC.VALOAREV ELSE 0 END ) ,
      RULAJVCC = RULAJVCC + (CASE WHEN  V_REC.TIP = 'C' THEN V_REC.VALOAREV ELSE 0 END )
  WHERE CODCONT = V_REC.CODCONT AND AN = getANLUCRU() AND LUNA = getLUNALUCRU();
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mifix_sp_postrecords</obj_name>
  <obj_hashval>3f9652d136c569698e88d83426210e6f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mifix_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  V_RECMF     RECORD;
  V_RECTRANSF RECORD;
  V_REC_J     RECORD;
  V_REC_SUB   RECORD;
  aCODMIFIX       numeric;
  NRTRANSF        numeric;
  I               numeric;
  NRMASTERMF      numeric;
  TIPMF           varchar;
  CANTTRANSF      numeric;
  CANTRAMASA      numeric;
  NR              numeric := 0;
  NRMF            numeric := 0;
  TRANSFERURI     numeric := 0;
  TIPNIRNOU       numeric := 0;
  GESTDEST        numeric := 0;
  CODTRANSF1      numeric;
  vTIPDOC         numeric;
  DATANIRDEST     date;
  PRETDEST        numeric;
  PREFIXDOCTRANSF varchar;
  NRDOCTRANSF     numeric;
  aDoc            varchar;
  sOper           varchar;
  vcExt           NUMERIC(20);
BEGIN
  --Florin 10.12.2025 - sinc. Oracle
  --Florin 04.12.2025 - sinc. Oracle
  --Florin 29.10.2025 - sinc. Oracle
  --Florin 28.11.2024 - sinc. Oracle
  --Florin 01.06.2023 - monitor
  --Bogdan 11.08.2022 55225 : Parc auto - asociere nr inventar
    --Florin 11.04.2022 - sinc. Oracle
  --Adina 05.07.2021 - sinc.Oracle din 03.07.2021
  --Bogdan 08.10.2020
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT (36);
  perform pkg_mifix_setct_monitor('MON_15');
  FOR v_rec IN (SELECT coalesce (mf1.codauto, 0) CODVECHI, coalesce (tmp.codauto, 0) CODNOU, tmp.nrinventar
                FROM tmp_mifix     tmp
                  LEFT JOIN mifix  mf  ON tmp.codmifix = mf.codmifix
                  LEFT JOIN mifix1 mf1 ON mf1.codmifix = mf.codmifix and mf1.anstart * 12 + mf1.lunastart = current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric * 12 + current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric
                WHERE coalesce (mf1.codauto, 0) &lt;&gt; coalesce (tmp.codauto, 0))
  LOOP
    IF v_rec.codvechi    = 0 and v_Rec.Codnou &gt; 0 THEN
      UPDATE nparcaut SET nrinv = NULL             WHERE nrinv       = v_rec.nrinventar;
      UPDATE nparcaut SET nrinv = v_rec.nrinventar WHERE codnparcaut = v_rec.codnou;
    ELSE
      IF v_rec.codvechi    &gt; 0 and v_Rec.Codnou = 0 THEN
        UPDATE nparcaut SET nrinv = NULL WHERE codnparcaut = v_rec.codvechi;
      ELSE
        IF v_rec.codvechi    &gt; 0 and v_Rec.Codnou &gt; 0 THEN
          UPDATE nparcaut SET nrinv = NULL             WHERE codnparcaut = v_rec.codvechi;
          UPDATE nparcaut SET nrinv = v_rec.nrinventar WHERE codnparcaut = v_rec.codnou;
        END IF;
      END IF;
    END IF;
  END LOOP;

  IF OPERATION = 0 THEN  --UPDATE
    SELECT CODNIRSTOC INTO RecId FROM TMP_MASTERMIFIX;

    BEGIN
      SELECT  DISTINCT TIP INTO TIPMF FROM TMP_MIFIX;
    EXCEPTION
    WHEN OTHERS THEN
      TIPMF := 'MF';
    END;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT
        FROM   PKG_USERFIRME_ValidPostLog (NULL,current_setting ('PKG_GLOBALS.USERID', true) ::numeric, current_setting ('PKG_MIFIX.CT_MONITOR', true)))
    THEN
      BEGIN
        SELECT  DISTINCT 'rezolvare mifix nr inventar ' || coalesce (mf.nrinventar::varchar ,'') , 'S'
        INTO aDoc, sOper
        FROM mifix mf INNER JOIN mifix1 mf1 ON mf.codmifix = mf1.codmifix and mf1.codnirstoc = recid;
      EXCEPTION
      WHEN others THEN
        BEGIN
          SELECT  DISTINCT 'rezolvare mifix nr inventar ' || coalesce (mf.nrinventar::varchar ,'') , 'A'
          INTO aDoc, sOper
          FROM tmp_mifix mf
          WHERE mf.codnirstoc = recid;
        EXCEPTION
        WHEN others THEN
          aDoc := 'Nu am gasit nr inventar';
        END;
      END;

      PERFORM pkg_userfirme_postlogcucommit('MIFIX', current_setting ('PKG_GLOBALS.USERNAME', true) , sOper, RECID, current_setting ('PKG_GLOBALS.FIRMANAME', true) , 1, LAST_DAY (TO_DATE ('01.'
      || coalesce (current_setting ('PKG_GLOBALS.LUNALUCRU', true) ,'')
      || '.'
      || coalesce (current_setting ('PKG_GLOBALS.ANLUCRU', true) ,'') , 'DD.MM.YYYY')) , aDoc, null, current_setting ('PKG_GLOBALS.EXE_VERSION', true));
    END IF;

    UPDATE MASTERMIFIX
    SET
      (
        CODCLASIF,
        DURATAN,
        DURATANF,
        DURATANG,
        CODCLASIFBLOCAT,
        CODANALIZA
      )
      = (SELECT CODCLASIF,
          DURATAN,
          DURATANF,
          DURATANG,
          CODCLASIFBLOCAT,
          CODANALIZA
         FROM TMP_MASTERMIFIX)
    WHERE
      CODNIRSTOC = RECID;

    FOR V_RECMF IN (SELECT * FROM TMP_MIFIX WHERE CODMIFIX1VECHI IS NOT NULL) LOOP
      IF V_RECMF.CANT &lt; V_RECMF.CANTMIFIX1VECHI THEN
        UPDATE MIFIX1
        SET
          AMO        = (CANT - V_RECMF.CANT) * AMO        / V_RECMF.CANTMIFIX1VECHI,
          AMOREZERVA = (CANT - V_RECMF.CANT) * AMOREZERVA / V_RECMF.CANTMIFIX1VECHI,
          NEUTIL     = (CANT - V_RECMF.CANT) * NEUTIL     / V_RECMF.CANTMIFIX1VECHI,
          CANT       =  CANT - V_RECMF.CANT
        WHERE
          CODMIFIX1 = V_RECMF.CODMIFIX1VECHI;
      END IF;

      IF V_RECMF.CODNIRSTOCVECHI IS NOT NULL THEN
        UPDATE MIFIX1
        SET
          CODNIRSTOC = V_RECMF.CODNIRSTOC,
          PRET       = V_RECMF.PRET
        WHERE
          CODMIFIX       = V_RECMF.CODMIFIX
          AND CODNIRSTOC = V_RECMF.CODNIRSTOCVECHI
          AND ANSTART * 12 + LUNASTART &gt; current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric * 12 + current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric;
      END IF;
    END LOOP;

    TRANSFERURI := 0;
    FOR V_RECMF IN (SELECT * FROM TMP_MIFIX WHERE PLECAT = 1) LOOP
      TRANSFERURI := 1;
      BEGIN
        SELECT COUNT(*) INTO NRTRANSF FROM TMP_MIFIXTRANSF WHERE CODTMPMIFIX = V_RECMF.CODTMPMIFIX;
      EXCEPTION
      WHEN OTHERS THEN
        NRTRANSF := 0;
      END;

      BEGIN
        SELECT SUM (CANTTRANSF) INTO CANTTRANSF FROM TMP_MIFIXTRANSF WHERE CODTMPMIFIX = V_RECMF.CODTMPMIFIX;
      EXCEPTION
      WHEN OTHERS THEN
        CANTTRANSF := 0;
      END;

      IF NRTRANSF &gt; 0 THEN
        I          := 1;
        CANTRAMASA := V_RECMF.CANT;

        FOR V_RECTRANSF IN (SELECT * FROM TMP_MIFIXTRANSF WHERE CODTMPMIFIX = V_RECMF.CODTMPMIFIX) LOOP
          IF I &lt; NRTRANSF THEN
            SELECT NEXTVAL ('SEQ_MIFIX_CODMIFIX') INTO aCODMIFIX;

            UPDATE TMP_FISAMF SET CODMIFIX = aCODMIFIX WHERE CODMIFIX = V_RECMF.CODMIFIX;

            INSERT INTO MIFIX (CODMIFIX,
                TIP,
                NRINVENTAR,
                ANINTRARE,
                LUNAINTRARE)
              VALUES (aCODMIFIX,
                TIPMF,
                0,
                current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric,
                current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric);

            SELECT NEXTVAL('SEQ_MIFIX1_CODMIFIX1') INTO vcExt;
              PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('MIFIX', vcExt, V_RECMF.CODMIFIX1);

            INSERT INTO MIFIX1 (CODMIFIX1,
                CODMIFIX,
                CODNIRSTOC,
                PRET,
                CANT,
                CODCLASIF,
                TIPAMO,
                STARE,
                DURATAN,
                GRADU,
                DURATAF,
                AMO,
                NEUTIL,
                DFBLOCAT,
                DFBLOCAT_F,
                DFBLOCAT_G,
                CODPERS,
                ANSTART,
                LUNASTART,
                CODNIRSER,
                CODPART,
                CODLOCATIE,
                CODAnalizaNod,
                CODSablon,
                CODCENTRU,
                AMOBLOCAT,
                CENTRUBLOCAT,
                CODCLASIFBLOCAT,
                CODPERSBLOCAT,
                NODANALIZABLOCAT,
                CODAUTO,
                AMOREZERVA,
                AMORBLOCAT,
                AMOFBLOCAT,
                AMOGBLOCAT,
                PRETINIBLOCAT,
                PRETINITIAL_FBLOCAT,
                PRETINITIAL,
                PRETINITIAL_F,
                TIPSTORNO,
                AMOANPREC)
              VALUES (vcExt,
                aCODMIFIX,
                V_RECTRANSF.CODNOUNIRSTOC,
                (SELECT PRET FROM NIRSTOC WHERE CODNIRSTOC = V_RECTRANSF.CODNOUNIRSTOC) ,
                V_RECTRANSF.CANTTRANSF,
                V_RECMF.CODCLASIF,
                V_RECMF.TIPAMO,
                V_RECMF.STARE,
                V_RECMF.DURATAN,
                V_RECMF.GRADU,
                V_RECMF.DURATAF,
                V_RECTRANSF.CANTTRANSF * V_RECMF.AMO / V_RECMF.CANT,
                V_RECTRANSF.CANTTRANSF * V_RECMF.NEUTIL / V_RECMF.CANT,
                V_RECMF.DFBLOCAT,
                V_RECMF.DFBLOCAT_F,
                V_RECMF.DFBLOCAT_G,
                V_RECMF.CODPERS,
                V_RECMF.ANSTART,
                V_RECMF.LUNASTART,
                (SELECT CODNIRSER FROM NIRSER WHERE CODNIRSTOC = V_RECTRANSF.CODNOUNIRSTOC limit 1) ,
                V_RECMF.CODPART,
                V_RECMF.CODLOCATIE,
                V_RECMF.CODAnalizaNod,
                V_RECMF.CODSablon,
                V_RECMF.CODCENTRU,
                V_RECMF.AMOBLOCAT,
                V_RECMF.CENTRUBLOCAT,
                V_RECMF.CODCLASIFBLOCAT,
                V_RECMF.CODPERSBLOCAT,
                V_RECMF.NODANALIZABLOCAT,
                V_RECMF.CODAUTO,
                V_RECMF.AMOREZERVA,
                V_RECMF.AMORBLOCAT,
                V_RECMF.AMOFBLOCAT,
                V_RECMF.AMOGBLOCAT,
                V_RECMF.PRETINIBLOCAT,
                V_RECMF.PRETINITIAL_FBLOCAT,
                V_RECMF.PRETINITIAL,
                V_RECMF.PRETINITIAL_F,
                V_RECMF.TIPSTORNO,
                V_RECMF.AMOANPREC);

            SELECT COUNT(*) INTO NRMASTERMF FROM MASTERMIFIX WHERE CODNIRSTOC = V_RECTRANSF.CODNOUNIRSTOC;

            IF NRMASTERMF = 0 THEN
              INSERT INTO MASTERMIFIX (CODNIRSTOC, CODCLASIF, DURATAN) (SELECT V_RECTRANSF.CODNOUNIRSTOC, CODCLASIF, DURATAN FROM TMP_MASTERMIFIX);
            ELSE
              UPDATE MASTERMIFIX
              SET
                (CODCLASIF, DURATAN) = (SELECT CODCLASIF, DURATAN FROM TMP_MASTERMIFIX)
              WHERE
                CODNIRSTOC = V_RECTRANSF.CODNOUNIRSTOC;
            END IF;

            UPDATE TMP_MIFIX
            SET
              AMO        = (CANT - V_RECTRANSF.CANTTRANSF) * AMO        / CANT,
              AMOREZERVA = (CANT - V_RECTRANSF.CANTTRANSF) * AMOREZERVA / CANT,
              NEUTIL     = (CANT - V_RECTRANSF.CANTTRANSF) * NEUTIL     / CANT,
              CANT       =  CANT - V_RECTRANSF.CANTTRANSF
            WHERE
              CODTMPMIFIX = V_RECMF.CODTMPMIFIX;
          ELSE
            IF CANTRAMASA = V_RECTRANSF.CANTTRANSF THEN
              UPDATE TMP_MIFIX
              SET
                CODNIRSTOC = V_RECTRANSF.CODNOUNIRSTOC,
                PRET       = (SELECT PRET FROM NIRSTOC WHERE CODNIRSTOC = V_RECTRANSF.CODNOUNIRSTOC) ,
                AMO        = AMO,
                AMOREZERVA = AMOREZERVA,
                NEUTIL     = NEUTIL,
                CANT       = CANTRAMASA,
                CODNIRSER  = (SELECT CODNIRSER FROM NIRSER WHERE CODNIRSTOC = V_RECTRANSF.CODNOUNIRSTOC)
              WHERE
                CODTMPMIFIX = V_RECMF.CODTMPMIFIX;

              UPDATE MIFIX1
              SET
                CODNIRSTOC    = V_RECTRANSF.CODNOUNIRSTOC,
                PRET          = (SELECT PRET FROM NIRSTOC WHERE CODNIRSTOC = V_RECTRANSF.CODNOUNIRSTOC) ,
                CANT          = CANTRAMASA,
                CODPART       = V_RECMF.CODPART,
                CODLOCATIE    = V_RECMF.CODLOCATIE,
                CODAnalizaNod = V_RECMF.CODAnalizaNod,
                CODSablon     = V_RECMF.CODSablon,
                CODCENTRU     = V_RECMF.CODCENTRU,
                CODAUTO       = V_RECMF.CODAUTO
              WHERE
                CODMIFIX = V_RECMF.CODMIFIX
                AND CODNIRSTOC = V_RECMF.CODNIRSTOC
                AND ANSTART * 12 + LUNASTART &gt; current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric * 12 + current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric;

              IF TIPMF = 'MF' THEN
                BEGIN
                  SELECT N.TIPNIR,
                    N.GEST,
                    T.DATADOC,
                    NS.PRET,
                    T.PREFIXDOC,
                    T.NRDOC,
                    T1.CODTRANSF1,
                    T.TIPDOC
                  INTO
                    TIPNIRNOU,
                    GESTDEST,
                    DATANIRDEST,
                    PRETDEST,
                    PREFIXDOCTRANSF,
                    NRDOCTRANSF,
                    CODTRANSF1,
                    vTIPDOC
                  FROM NIRSTOC NS,
                    NIR      N,
                    TRANSF   T,
                    TRANSF1  T1
                  WHERE
                    NS.CODNIRSTOC = V_RECTRANSF.CODNOUNIRSTOC
                    AND N.CODNIR = NS.CODNIR
                    AND T.CODTRANSF = N.CODTRANSF
                    AND NS.CODTRANSF1 = T1.CODTRANSF1
                    AND T1.CODTRANSF = T.CODTRANSF
                    AND NS.CODNIR = N.CODNIR;
                EXCEPTION
                WHEN OTHERS THEN
                  TIPNIRNOU       := 0;
                  GESTDEST        := 0;
                  DATANIRDEST     := TO_DATE ('01.01.2000', 'DD.MM.YYYY');
                  PRETDEST        := 0;
                  PREFIXDOCTRANSF := ' ';
                  NRDOCTRANSF     := 0;
                END;

                INSERT INTO TMP_FISAMF (CODFISAMF,
                    CODMIFIX,
                    CODOPERATIE,
                    DATAOPERATIE,
                    GESTSURSA,
                    GESTDEST,
                    PRETI,
                    PRETE,
                    PREFIXDOC,
                    NRDOC,
                    CODDOC1,
                    TIPDOC)
                  VALUES (-1,
                    V_RECMF.CODMIFIX,
                    (CASE WHEN TIPNIRNOU = 12 THEN 2 ELSE 3 END),
                    DATANIRDEST,
                    V_RECMF.CODGEST,
                    GESTDEST,
                    V_RECMF.PRET,
                    PRETDEST,
                    PREFIXDOCTRANSF,
                    NRDOCTRANSF,
                    CODTRANSF1,
                    vTIPDOC);
              END IF;
            ELSE
              SELECT NEXTVAL ('SEQ_MIFIX_CODMIFIX') INTO aCODMIFIX;

              UPDATE TMP_FISAMF SET CODMIFIX = aCODMIFIX WHERE CODMIFIX = V_RECMF.CODMIFIX;

              INSERT INTO MIFIX (CODMIFIX,
                  TIP,
                  NRINVENTAR,
                  ANINTRARE,
                  LUNAINTRARE)
                VALUES (aCODMIFIX,
                  TIPMF,
                  0,
                  current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric,
                  current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric);

              SELECT NEXTVAL('SEQ_MIFIX1_CODMIFIX1') INTO vcExt;
                PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('MIFIX', vcExt, V_RECMF.CODMIFIX1);

             INSERT INTO MIFIX1 (CODMIFIX1, CODMIFIX, CODNIRSTOC, PRET, CANT, CODCLASIF, TIPAMO, STARE, DURATAN, GRADU, DURATAF,
                                   AMO, NEUTIL, DFBLOCAT, CODPERS, ANSTART, LUNASTART, CODNIRSER, CODPART, CODLOCATIE,CODAnalizaNod, CODSablon, CODCENTRU, REZERVA,  REZERVABLOCAT, AMOBLOCAT, CENTRUBLOCAT, CODCLASIFBLOCAT, CODPERSBLOCAT, NODANALIZABLOCAT, CODAUTO,
                                   AMOREZERVA, AMORBLOCAT, AMOFBLOCAT, AMOGBLOCAT, PRETINIBLOCAT, pretinitial_fblocat, PRETINITIAL, PRETINITIAL_F, TIPSTORNO, AMOANPREC)
                      VALUES (vcExt, aCODMIFIX, V_RECTRANSF.CODNOUNIRSTOC, (SELECT PRET FROM NIRSTOC WHERE CODNIRSTOC = V_RECTRANSF.CODNOUNIRSTOC), V_RECTRANSF.CANTTRANSF,
                              V_RECMF.CODCLASIF, V_RECMF.TIPAMO, V_RECMF.STARE, V_RECMF.DURATAN, V_RECMF.GRADU, V_RECMF.DURATAF,
                              V_RECTRANSF.CANTTRANSF * V_RECMF.AMO / V_RECMF.CANT , V_RECTRANSF.CANTTRANSF * V_RECMF.NEUTIL / V_RECMF.CANT , V_RECMF.DFBLOCAT, V_RECMF.CODPERS, V_RECMF.ANSTART, V_RECMF.LUNASTART, (SELECT CODNIRSER FROM NIRSER WHERE CODNIRSTOC = V_RECTRANSF.CODNOUNIRSTOC AND ROWNUM=1), --V_RECMF.CODNIRSER,
                              V_RECMF.CODPART, V_RECMF.CODLOCATIE,V_RECMF.CODAnalizaNod, V_RECMF.CODSablon, V_RECMF.CODCENTRU, V_RECMF.REZERVA, V_RECMF.REZERVABLOCAT, V_RECMF.AMOBLOCAT, V_RECMF.CENTRUBLOCAT, V_RECMF.CODCLASIFBLOCAT, V_RECMF.CODPERSBLOCAT, V_RECMF.NODANALIZABLOCAT,
                              V_RECMF.CODAUTO, V_RECMF.AMOREZERVA, V_RECMF.AMORBLOCAT, V_RECMF.AMOFBLOCAT, V_RECMF.AMOGBLOCAT, V_RECMF.PRETINIBLOCAT, V_RECMF.pretinitial_fblocat, V_RECMF.PRETINITIAL, V_RECMF.PRETINITIAL_F, V_RECMF.TIPSTORNO, V_RECMF.AMOANPREC);

              UPDATE TMP_MIFIX
              SET
                AMO        = (CANT - V_RECTRANSF.CANTTRANSF) * AMO        / CANT,
                AMOREZERVA = (CANT - V_RECTRANSF.CANTTRANSF) * AMOREZERVA / CANT,
                NEUTIL     = (CANT - V_RECTRANSF.CANTTRANSF) * NEUTIL     / CANT,
                CANT       =  CANT - V_RECTRANSF.CANTTRANSF
              WHERE
                CODTMPMIFIX = V_RECMF.CODTMPMIFIX;

              UPDATE MIFIX1
              SET CANT = CANT - V_RECTRANSF.CANTTRANSF
              WHERE
                CODMIFIX = V_RECMF.CODMIFIX
                AND CODNIRSTOC = V_RECMF.CODNIRSTOC
                AND ANSTART * 12 + LUNASTART &gt; current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric * 12 + current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric;

              SELECT COUNT(*) INTO NRMASTERMF FROM MASTERMIFIX WHERE CODNIRSTOC = V_RECTRANSF.CODNOUNIRSTOC;

              IF NRMASTERMF = 0 THEN
                INSERT INTO MASTERMIFIX (CODNIRSTOC, CODCLASIF, DURATAN) (SELECT V_RECTRANSF.CODNOUNIRSTOC, CODCLASIF, DURATAN FROM TMP_MASTERMIFIX);
              ELSE
                UPDATE MASTERMIFIX
                SET
                  (CODCLASIF, DURATAN) = (SELECT CODCLASIF, DURATAN FROM TMP_MASTERMIFIX)
                WHERE
                  CODNIRSTOC = V_RECTRANSF.CODNOUNIRSTOC;
              END IF;
            END IF;
          END IF;

          I          := I          + 1;
          CANTRAMASA := CANTRAMASA - V_RECTRANSF.CANTTRANSF;
        END LOOP;
      END IF;
    END LOOP;

    FOR V_REC IN (SELECT * FROM MIFIX1
                  WHERE
                    CODNIRSTOC    = RECID
                    AND ANSTART   = current_setting ('PKG_GLOBALS.ANLUCRU'  , true) ::numeric
                    AND LUNASTART = current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric
                    AND CODMIFIX1 NOT IN (SELECT CODMIFIX1 FROM TMP_MIFIX))
    LOOP
      DELETE FROM MIFIX1 WHERE CODMIFIX1 = V_REC.CODMIFIX1;

      SELECT COUNT(*) INTO NRMF FROM MIFIX1 WHERE CODMIFIX = V_REC.CODMIFIX;

      IF NRMF = 0 THEN
        DELETE FROM MIFIX WHERE CODMIFIX = V_REC.CODMIFIX;
      END IF;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_MIFIX) LOOP
      if coalesce(v_rec.codutilaj,0) = 0 then
        update utilaje set nrinventar = null where nrinventar = v_rec.nrinventar;
      else
        update utilaje set nrinventar = v_rec.nrinventar where codutilaj = v_rec.codutilaj;
      end if;

      IF V_REC.CODMIFIX &gt; 0 THEN
        UPDATE MIFIX
        SET
          TIP          = V_REC.TIP,
          NRINVENTAR   = V_REC.NRINVENTAR,
          SERIEINV     = V_REC.SERIEINV,
          CODMIFIXIMB  = V_REC.CODMIFIXIMB,
          OBS          = V_REC.OBS,
          ANINTRARE    = V_REC.ANINTRARE,
          LUNAINTRARE  = V_REC.LUNAINTRARE,
          ANINTRAREG   = V_REC.ANINTRAREG,
          LUNAINTRAREG = V_REC.LUNAINTRAREG,
          RestIMBMF    = CASE WHEN COALESCE (V_REC.CODMIFIXIMB, 0) &lt;&gt; 0 THEN v_rec.PRET - ( SELECT COALESCE (SUM (IL.CANT) , 0)
                                                                                            FROM IMBMIFIXLINK   IL
                                                                                              LEFT JOIN TRANSF1 T1 ON T1.CODTRANSF1 = IL.CODTRANSF1
                                                                                              LEFT JOIN TRANSF  T  ON T.CODTRANSF   = T1.CODTRANSF
                                                                                            WHERE
                                                                                              IL.CODMIFIX = v_Rec.CODMIFIX
                                                                                              AND T.OPERAT = 1
                                                                                              AND T.ANULAT = 0)
                              ELSE 0
                         END
        WHERE
          CODMIFIX = V_REC.CODMIFIX;

        IF V_REC.CODMIFIX1 &gt; 0 THEN
          UPDATE MIFIX1
          SET
            CODMIFIX            = V_REC.CODMIFIX,
            CODNIRSTOC          = V_REC.CODNIRSTOC,
            PRET                = V_REC.PRET,
            CANT                = V_REC.CANT,
            CODCLASIF           = V_REC.CODCLASIF,
            TIPAMO              = V_REC.TIPAMO,
            STARE               = V_REC.STARE,
            DURATAN             = V_REC.DURATAN,
            GRADU               = V_REC.GRADU,
            DURATAF             = V_REC.DURATAF,
            AMO                 = V_REC.AMO,
            NEUTIL              = V_REC.NEUTIL,
            DFBLOCAT            = V_REC.DFBLOCAT,
            AMOBLOCAT           = V_REC.AMOBLOCAT,
            CENTRUBLOCAT        = V_REC.CENTRUBLOCAT,
            CODCLASIFBLOCAT     = v_rec.codclasifblocat,
            CODPERSBLOCAT       = V_REC.CODPERSBLOCAT,
            NODANALIZABLOCAT    = V_REC.NODANALIZABLOCAT,
            DFBLOCAT_F          = V_REC.DFBLOCAT_F,
            DFBLOCAT_G          = V_REC.DFBLOCAT_G,
            CODPERS             = V_REC.CODPERS,
            CODNIRSER           = V_REC.CODNIRSER,
            ANSTART             = V_REC.ANSTART,
            LUNASTART           = V_REC.LUNASTART,
            CODPART             = V_REC.CODPART,
            CODLOCATIE          = V_REC.CODLOCATIE,
            CODAnalizaNod       = V_REC.CODAnalizaNod,
            CODSablon           = V_REC.CODSablon,
            CODCENTRU           = V_REC.CODCENTRU,
            DURATANF            = V_REC.DURATANF,
            DURATANG            = V_REC.DURATANG,
            DURATAFF            = V_REC.DURATAFF,
            DURATAFG            = V_REC.DURATAFG,
            AMOF                = V_REC.AMOF,
            AMOG                = V_REC.AMOG,
            REZERVA             = V_REC.REZERVA,
            REZERVABLOCAT       = V_REC.REZERVABLOCAT,
            CODAUTO             = V_REC.CODAUTO,
            AMOREZERVA          = V_REC.AMOREZERVA,
            AMORBLOCAT          = V_REC.AMORBLOCAT,
            AMOFBLOCAT          = V_REC.AMOFBLOCAT,
            AMOGBLOCAT          = V_REC.AMOGBLOCAT,
            PRETINIBLOCAT       = V_REC.PRETINIBLOCAT,
            PRETINITIAL_FBLOCAT = V_REC.PRETINITIAL_FBLOCAT,
            PRETINITIAL         = V_REC.PRETINITIAL,
            PRETINITIAL_F       = V_REC.PRETINITIAL_F,
            TIPSTORNO           = V_REC.TIPSTORNO,
            AMOANPREC     = V_REC.AMOANPREC
          WHERE
            CODMIFIX1 = V_REC.CODMIFIX1;
        ELSE
         SELECT NEXTVAL('SEQ_MIFIX1_CODMIFIX1') INTO vcExt;
         PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('MIFIX', vcExt, V_REC.CODMIFIX1);

          INSERT INTO MIFIX1 (CODMIFIX1,
              CODMIFIX,
              CODNIRSTOC,
              PRET,
              CANT,
              CODCLASIF,
              TIPAMO,
              STARE,
              DURATAN,
              GRADU,
              DURATAF,
              AMO,
              NEUTIL,
              DFBLOCAT,
              DFBLOCAT_F,
              DFBLOCAT_G,
              CODPERS,
              CODNIRSER,
              ANSTART,
              LUNASTART,
              CODPART,
              CODLOCATIE,
              CODAnalizaNod,
              CODSablon,
              CODCENTRU,
              DURATANF,
              DURATANG,
              DURATAFF,
              DURATAFG,
              AMOF,
              AMOG,
              REZERVA,
              REZERVABLOCAT,
              AMOBLOCAT,
              CENTRUBLOCAT,
              CODCLASIFBLOCAT,
              CODPERSBLOCAT,
              NODANALIZABLOCAT,
              CODAUTO,
              AMOREZERVA,
              AMORBLOCAT,
              AMOFBLOCAT,
              AMOGBLOCAT,
              PRETINIBLOCAT,
              PRETINITIAL_FBLOCAT,
              PRETINITIAL,
              PRETINITIAL_F,
              TIPSTORNO,
              AMOANPREC)
            VALUES (vcExt,
              V_REC.CODMIFIX,
              V_REC.CODNIRSTOC,
              V_REC.PRET,
              V_REC.CANT,
              V_REC.CODCLASIF,
              V_REC.TIPAMO,
              V_REC.STARE,
              V_REC.DURATAN,
              V_REC.GRADU,
              V_REC.DURATAF,
              V_REC.AMO,
              V_REC.NEUTIL,
              V_REC.DFBLOCAT,
              V_REC.DFBLOCAT_F,
              V_REC.DFBLOCAT_G,
              V_REC.CODPERS,
              V_REC.CODNIRSER,
              V_REC.ANSTART,
              V_REC.LUNASTART,
              V_REC.CODPART,
              V_REC.CODLOCATIE,
              v_rec.CODAnalizaNod,
              V_REC.CODSablon,
              V_REC.CODCENTRU,
              V_REC.DURATANF,
              V_REC.DURATANG,
              V_REC.DURATAFF,
              V_REC.DURATAFG,
              V_REC.AMOF,
              V_REC.AMOG,
              V_REC.REZERVA,
              V_REC.REZERVABLOCAT,
              V_REC.AMOBLOCAT,
              V_REC.CENTRUBLOCAT,
              V_REC.CODCLASIFBLOCAT,
              V_REC.CODPERSBLOCAT,
              V_REC.NODANALIZABLOCAT,
              V_REC.CODAUTO,
              V_REC.AMOREZERVA,
              V_REC.AMORBLOCAT,
              V_REC.AMOFBLOCAT,
              V_REC.AMOGBLOCAT,
              V_REC.PRETINIBLOCAT,
              V_REC.PRETINITIAL_FBLOCAT,
              V_REC.PRETINITIAL,
              V_REC.PRETINITIAL_F,
              V_REC.TIPSTORNO,
              V_REC.AMOANPREC);
        END IF;
      ELSE
        SELECT NEXTVAL ('SEQ_MIFIX_CODMIFIX') INTO aCODMIFIX;

        UPDATE TMP_MIFIX
        SET
          CODMIFIX = aCODMIFIX
        WHERE
          CODMIFIX = V_REC.CODMIFIX;

        UPDATE TMP_JURNAL
        SET
          CODDOC     = aCODMIFIX,
          INDEXLOCAL = aCODMIFIX
        WHERE
          CODDOC = V_REC.CODMIFIX;

        UPDATE TMP_JURNAL1
        SET
          CODDOC     = aCODMIFIX,
          INDEXLOCAL = aCODMIFIX
        WHERE
          CODDOC = V_REC.CODMIFIX;

        UPDATE TMP_FISAMF SET CODMIFIX = aCODMIFIX WHERE CODMIFIX = V_REC.CODMIFIX;

        INSERT INTO MIFIX (CODMIFIX,
            TIP,
            NRINVENTAR,
            OBS,
            ANINTRARE,
            LUNAINTRARE,
            ANINTRAREG,
            LUNAINTRAREG,
            SERIEINV,
            CODMIFIXIMB,
            RESTIMBMF)
          VALUES (aCODMIFIX,
            V_REC.TIP,
            V_REC.NRINVENTAR,
            V_REC.OBS,
            V_REC.ANINTRARE,
            V_REC.LUNAINTRARE,
            V_REC.ANINTRAREG,
            V_REC.LUNAINTRAREG,
            V_REC.SERIEINV,
            V_REC.CODMIFIXIMB,
            0);

        SELECT NEXTVAL('SEQ_MIFIX1_CODMIFIX1') INTO vcExt;
        PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('MIFIX', vcExt, V_REC.CODMIFIX1);

        INSERT INTO MIFIX1 (CODMIFIX1,
            CODMIFIX,
            CODNIRSTOC,
            PRET,
            CANT,
            CODCLASIF,
            TIPAMO,
            STARE,
            DURATAN,
            GRADU,
            DURATAF,
            AMO,
            NEUTIL,
            DFBLOCAT,
            DFBLOCAT_F,
            DFBLOCAT_G,
            CODPERS,
            CODNIRSER,
            ANSTART,
            LUNASTART,
            CODPART,
            CODLOCATIE,
            CODAnalizaNod,
            CODSablon,
            CODCENTRU,
            DURATANF,
            DURATANG,
            DURATAFF,
            DURATAFG,
            AMOF,
            AMOG,
            REZERVA,
            REZERVABLOCAT,
            AMOBLOCAT,
            CENTRUBLOCAT,
            CODCLASIFBLOCAT,
            CODPERSBLOCAT,
            NODANALIZABLOCAT,
            CODAUTO,
            AMOREZERVA,
            AMORBLOCAT,
            AMOFBLOCAT,
            AMOGBLOCAT,
            PRETINIBLOCAT,
            PRETINITIAL_FBLOCAT,
            PRETINITIAL,
            PRETINITIAL_F,
            TIPSTORNO,
            AMOANPREC)
          VALUES (vcExt,
            aCODMIFIX,
            V_REC.CODNIRSTOC,
            V_REC.PRET,
            V_REC.CANT,
            V_REC.CODCLASIF,
            V_REC.TIPAMO,
            V_REC.STARE,
            V_REC.DURATAN,
            V_REC.GRADU,
            V_REC.DURATAF,
            V_REC.AMO,
            V_REC.NEUTIL,
            V_REC.DFBLOCAT,
            V_REC.DFBLOCAT_F,
            V_REC.DFBLOCAT_G,
            V_REC.CODPERS,
            V_REC.CODNIRSER,
            V_REC.ANSTART,
            V_REC.LUNASTART,
            V_REC.CODPART,
            V_REC.CODLOCATIE,
            V_REC.CODAnalizaNod,
            V_REC.CODSablon,
            V_REC.CODCENTRU,
            V_REC.DURATANF,
            V_REC.DURATANG,
            V_REC.DURATAFF,
            V_REC.DURATAFG,
            V_REC.AMOF,
            V_REC.AMOG,
            V_REC.REZERVA,
            V_REC.REZERVABLOCAT,
            V_REC.AMOBLOCAT,
            V_REC.CENTRUBLOCAT,
            V_REC.CODCLASIFBLOCAT,
            V_REC.CODPERSBLOCAT,
            V_REC.NODANALIZABLOCAT,
            V_REC.CODAUTO,
            V_REC.AMOREZERVA,
            V_REC.AMORBLOCAT,
            V_REC.AMOFBLOCAT,
            V_REC.AMOGBLOCAT,
            V_REC.PRETINIBLOCAT,
            V_REC.PRETINITIAL_FBLOCAT,
            V_REC.PRETINITIAL,
            V_REC.PRETINITIAL_F,
            V_REC.TIPSTORNO,
            V_REC.AMOANPREC);
      END IF;
    END LOOP;

    DELETE FROM FISAMF FMF
    WHERE     EXISTS (SELECT CODFISAMF FROM TMP_FISAMF_INI WHERE CODFISAMF = FMF.CODFISAMF)
      AND NOT EXISTS (SELECT CODFISAMF FROM TMP_FISAMF WHERE CODFISAMF = FMF.CODFISAMF);

    FOR V_REC IN (SELECT * FROM TMP_FISAMF) LOOP
      IF V_REC.CODFISAMF &gt; 0 THEN
        UPDATE FISAMF
        SET
          CODMIFIX     = V_REC.CODMIFIX,
          CODOPERATIE  = V_REC.CODOPERATIE,
          DATAOPERATIE = V_REC.DATAOPERATIE,
          GESTSURSA    = V_REC.GESTSURSA,
          GESTDEST     = V_REC.GESTDEST,
          PRETI        = V_REC.PRETI,
          PRETE        = V_REC.PRETE,
          PREFIXDOC    = V_REC.PREFIXDOC,
          NRDOC        = V_REC.NRDOC,
          CANT         = V_REC.CANT,
          OBS          = V_REC.OBS,
          CODDOC1      = V_REC.CODDOC1,
          TIPDOC       = V_REC.TIPDOC
        WHERE
          CODFISAMF = V_REC.CODFISAMF;
      ELSE
        INSERT INTO FISAMF (CODFISAMF,
            CODMIFIX,
            CODOPERATIE,
            DATAOPERATIE,
            GESTSURSA,
            GESTDEST,
            PRETI,
            PRETE,
            PREFIXDOC,
            NRDOC,
            CANT,
            OBS,
            CODDOC1,
            TIPDOC)
          VALUES (NEXTVAL ('SEQ_FISAMF_CODFISAMF') ,
            V_REC.CODMIFIX,
            V_REC.CODOPERATIE,
            V_REC.DATAOPERATIE,
            V_REC.GESTSURSA,
            V_REC.GESTDEST,
            V_REC.PRETI,
            V_REC.PRETE,
            V_REC.PREFIXDOC,
            V_REC.NRDOC,
            V_REC.CANT,
            V_REC.OBS,
            V_REC.CODDOC1,
            V_REC.TIPDOC);

        IF V_REC.CODOPERATIE = 1 THEN
          IF V_REC.TIPDOC  &lt; 12 THEN
            UPDATE INTRARI1 SET CODMIFIX = V_REC.CODMIFIX WHERE CODINTR1 = V_REC.CODDOC1;
          END IF;

          IF V_REC.TIPDOC IN (12, 13) THEN
            UPDATE TRANSF1 SET CODMIFIX = V_REC.CODMIFIX WHERE CODTRANSF1 = V_REC.CODDOC1;
          END IF;

          IF V_REC.TIPDOC = 15 THEN
            UPDATE IESIRI1 SET CODMIFIX = V_REC.CODMIFIX WHERE CODIES1 = V_REC.CODDOC1;
          END IF;
        END IF;
      END IF;
    END LOOP;

    DELETE FROM JURNAl1
    WHERE
      TIPDOC   = 36
      AND AN   = current_setting ('PKG_GLOBALS.ANLUCRU'  , true) ::numeric
      AND LUNA = current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric
      AND CODDOC IN (SELECT CODMIFIX FROM TMP_MIFIX_INITIAL)
      AND CODJURNAL1 NOT IN (SELECT CODJURNAL1 FROM TMP_JURNAl1);

    FOR V_REC IN (SELECT * FROM TMP_JURNAL1) LOOP
      IF V_REC.CODJURNAL1 &gt; 0 THEN
        UPDATE JURNAL1
        SET
          CODDOC        = V_REC.CODDOC,
          TIPDOC        = V_REC.TIPDOC,
          INDEXLOCAL    = V_REC.INDEXLOCAL,
          CODBAZAD      = V_REC.CODBAZAD,
          ICONTBAZAD    = V_REC.ICONTBAZAD,
          TIPBAZAD      = V_REC.TIPBAZAD,
          CODBAZAC      = V_REC.CODBAZAC,
          ICONTBAZAC    = V_REC.ICONTBAZAC,
          TIPBAZAC      = V_REC.TIPBAZAC,
          CODDESCRD     = V_REC.CODDESCRD,
          ICONTD        = V_REC.ICONTD,
          TIPCONTD      = V_REC.TIPCONTD,
          ANALITICCONTD = V_REC.ANALITICCONTD,
          CODDESCRC     = V_REC.CODDESCRC,
          ICONTC        = V_REC.ICONTC,
          TIPCONTC      = V_REC.TIPCONTC,
          ANALITICCONTC = V_REC.ANALITICCONTC,
          GEST          = V_REC.GEST,
          VALOARE       = V_REC.VALOARE,
          VALOAREV      = V_REC.VALOAREV,
          VALOAREGRUP   = v_rec.VALOAREGRUP,
          OBS           = V_REC.OBS,
          AN            = V_REC.AN,
          LUNA          = V_REC.LUNA,
          DIRTY         = CASE WHEN COALESCE (TRANSFERURI, 0) = 0 THEN V_REC.DIRTY ELSE 1 END ,
          SUBUNITATEA   = V_REC.SUBUNITATEA,
          CODAnalizaNod = V_REC.CODAnalizaNod,
          CODCENTRU     = v_rec.CODCENTRU,
          DATADOC       = V_REC.DATADOC,
          DOCUMENT      = V_REC.DOCUMENT
        WHERE
          CODJURNAL1 = V_REC.CODJURNAl1;
      ELSE
        INSERT INTO JURNAL1 (CODJURNAL1,
            CODDOC,
            TIPDOC,
            INDEXLOCAL,
            CODBAZAD,
            ICONTBAZAD,
            TIPBAZAD,
            CODDESCRD,
            ICONTD,
            TIPCONTD,
            ANALITICCONTD,
            CODBAZAC,
            ICONTBAZAC,
            TIPBAZAC,
            CODDESCRC,
            ICONTC,
            TIPCONTC,
            ANALITICCONTC,
            GEST,
            VALOARE,
            VALOAREV,
            VALOAREGRUP,
            OBS,
            AN,
            LUNA,
            DIRTY,
            SUBUNITATEA,
            CODAnalizaNod,
            CODCENTRU,
            DATADOC,
            DOCUMENT)
          VALUES (NEXTVAL ('SEQ_JURNAL1_CODJURNAL1') ,
            V_REC.CODDOC,
            V_REC.TIPDOC,
            V_REC.INDEXLOCAL,
            V_REC.CODBAZAD,
            V_REC.ICONTBAZAD,
            V_REC.TIPBAZAD,
            V_REC.CODDESCRD,
            V_REC.ICONTD,
            V_REC.TIPCONTD,
            V_REC.ANALITICCONTD,
            V_REC.CODBAZAC,
            V_REC.ICONTBAZAC,
            V_REC.TIPBAZAC,
            V_REC.CODDESCRC,
            V_REC.ICONTC,
            V_REC.TIPCONTC,
            V_REC.ANALITICCONTC,
            V_REC.GEST,
            V_REC.VALOARE,
            V_REC.VALOAREV,
            v_rec.VALOAREGRUP,
            V_REC.OBS,
            V_REC.AN,
            V_REC.LUNA,
            V_REC.DIRTY,
            V_REC.SUBUNITATEA,
            v_rec.CODAnalizaNod,
            v_rec.CODCENTRU,
            V_REC.DATADOC,
            V_REC.DOCUMENT);
      END IF;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_MIFIX WHERE CODMIFIX &gt; 0 AND CODMIFIX1 = CODMIFIX1VECHI) LOOP
      FOR V_REC_J IN (SELECT * FROM JURNAL
                      WHERE
                        TIPDOC = 36
                        AND AN = current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric
                        AND LUNA = current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric
                        AND CODDOC = V_REC.CODMIFIX)
      LOOP
        UPDATE NCONTRUL
        SET
          RULAJCD  = RULAJCD  - V_REC_J.VALOARE,
          RULAJVCD = RULAJVCD - V_REC_J.VALOAREV
        WHERE
          CODCONT  = V_REC_J.CONTD
          AND AN   = current_setting ('PKG_GLOBALS.ANLUCRU'  , true) ::numeric
          AND LUNA = current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric;

        UPDATE NCONTRUL
        SET
          RULAJCC  = RULAJCC  - V_REC_J.VALOARE,
          RULAJVCC = RULAJVCC - V_REC_J.VALOAREV
        WHERE
          CODCONT  = V_REC_J.CONTC
          AND AN   = current_setting ('PKG_GLOBALS.ANLUCRU'  , true) ::numeric
          AND LUNA = current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric;

        DELETE FROM JURNAL WHERE CODJURNAL = V_REC_J.CODJURNAL;
      END LOOP;

      DELETE FROM JURNAL1
      WHERE
        TIPDOC = 36
        AND AN = current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric
        AND LUNA = current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric
        AND CODDOC = V_REC.CODMIFIX;
    END LOOP;

    DELETE FROM JURNAL
    WHERE
      TIPDOC = 36
      AND AN = current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric
      AND LUNA = current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric
      AND CODDOC IN (SELECT CODMIFIX FROM TMP_MIFIX_INITIAL)
      AND CODJURNAL NOT IN (SELECT CODJURNAL FROM TMP_JURNAL);

    FOR V_REC IN (SELECT * FROM TMP_JURNAL) LOOP
      IF V_REC.CODJURNAL &gt; 0 THEN
        UPDATE JURNAL
        SET
          CODDOC        = V_REC.CODDOC,
          TIPDOC        = V_REC.TIPDOC,
          INDEXLOCAL    = V_REC.INDEXLOCAL,
          CONTD         = V_REC.CONTD,
          CONTC         = V_REC.CONTC,
          GEST          = V_REC.GEST,
          VALOARE       = V_REC.VALOARE,
          VALOAREV      = V_REC.VALOAREV,
          VALOAREGRUP   = v_rec.VALOAREGRUP,
          OBS           = V_REC.OBS,
          AN            = V_REC.AN,
          LUNA          = V_REC.LUNA,
          SUBUNITATEA   = V_REC.SUBUNITATEA,
          CODAnalizaNod = v_rec.CODAnalizaNod,
          CODCENTRU     = v_rec.CODCENTRU,
          DATADOC       = V_REC.DATADOC,
          DOCUMENT      = V_REC.DOCUMENT
        WHERE
          CODJURNAL = V_REC.CODJURNAl;
      ELSE
        INSERT INTO JURNAL (CODJURNAL,
            CODDOC,
            TIPDOC,
            INDEXLOCAL,
            CONTD,
            CONTC,
            GEST,
            VALOARE,
            VALOAREV,
            VALOAREGRUP,
            OBS,
            AN,
            LUNA,
            SUBUNITATEA,
            CODAnalizaNod,
            CODCENTRU,
            DATADOC,
            DOCUMENT)
          VALUES (NEXTVAL ('SEQ_JURNAL_CODJURNAL') ,
            V_REC.CODDOC,
            V_REC.TIPDOC,
            V_REC.INDEXLOCAL,
            V_REC.CONTD,
            V_REC.CONTC,
            V_REC.GEST,
            V_REC.VALOARE,
            V_REC.VALOAREV,
            v_rec.VALOAREGRUP,
            V_REC.OBS,
            V_REC.AN,
            V_REC.LUNA,
            V_REC.SUBUNITATEA,
            v_rec.CODAnalizaNod,
            v_rec.CODCENTRU,
            V_REC.DATADOC,
            V_REC.DOCUMENT);
      END IF;
    END LOOP;
  END IF;

  IF COALESCE (fnc_GetValConstantaLucru('MifixStatusAuto'), '1') = '1' THEN
    FOR v_rec IN (SELECT p.codnparcaut, mfix1.stare
                  FROM nparcaut       p
                    INNER JOIN mifix  mfix  ON mfix.nrinventar = p.nrinv
                    INNER JOIN mifix1 mfix1 ON mfix1.codmifix  = mfix.codmifix
                  WHERE
                    mfix1.anstart = current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric
                    and mfix1.lunastart = current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric
                    and mfix1.codnirstoc = recid)
    LOOP
      UPDATE nparcaut SET inactiv = CASE WHEN v_rec.stare = 1 THEN 0 ELSE v_rec.stare END WHERE codnparcaut = v_rec.codnparcaut;
    END LOOP;
  END IF;

  FOR V_REC IN (SELECT * FROM TMP_RULAJ) LOOP
    SELECT COUNT(*) INTO NR FROM NCONTRUL
    WHERE
      CODCONT = V_REC.CODCONT
      AND AN = current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric
      AND LUNA = current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric;

    IF NR = 0 THEN
      INSERT INTO NCONTRUL (CODCONTRUL,
          CODCONT,
          RULAJPD,
          RULAJPC,
          RULAJCD,
          RULAJCC,
          RULAJVPD,
          RULAJVPC,
          RULAJVCD,
          RULAJVCC,
          AN,
          LUNA)
        VALUES (NEXTVAL ('SEQ_NCONTRUL_CODCONTRUL') ,
          V_REC.CODCONT,
          0,
          0,
          0,
          0,
          0,
          0,
          0,
          0,
          current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric,
          current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric);
    END IF;

    UPDATE NCONTRUL
    SET
      RULAJCD  = RULAJCD  + (CASE WHEN V_REC.TIP = 'D' THEN V_REC.VALOARE  ELSE 0 END),
      RULAJCC  = RULAJCC  + (CASE WHEN V_REC.TIP = 'C' THEN V_REC.VALOARE  ELSE 0 END),
      RULAJVCD = RULAJVCD + (CASE WHEN V_REC.TIP = 'D' THEN V_REC.VALOAREV ELSE 0 END),
      RULAJVCC = RULAJVCC + (CASE WHEN V_REC.TIP = 'C' THEN V_REC.VALOAREV ELSE 0 END)
    WHERE
      CODCONT  = V_REC.CODCONT
      AND AN   = current_setting ('PKG_GLOBALS.ANLUCRU'  , true) ::numeric
      AND LUNA = current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric;

    IF COALESCE (V_REC.SUBUNITATEA, 0) &lt;&gt; 0 THEN
      FOR V_REC_SUB IN (SELECT *
                        FROM NCONTRUL
                        WHERE
                          CODCONT  = V_REC.CODCONT
                          AND AN   = current_setting ('PKG_GLOBALS.ANLUCRU'  , true) ::numeric
                          AND LUNA = current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric)
      LOOP
        SELECT COUNT(*) INTO NR FROM NCONTRULSUB WHERE CODCONTRUL = V_REC_SUB.CODCONTRUL AND SUBUNITATEA = V_REC.SUBUNITATEA;

        IF NR = 0 THEN
          INSERT INTO NCONTRULSUB (CODCONTRULSUB,
              CODCONTRUL,
              RULAJPD,
              RULAJPC,
              RULAJCD,
              RULAJCC,
              RULAJVPD,
              RULAJVPC,
              RULAJVCD,
              RULAJVCC,
              SUBUNITATEA)
            VALUES (NEXTVAL ('SEQ_NCONTRULSUB_CODRULSUB') ,
              V_REC_SUB.CODCONTRUL,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              V_REC.SUBUNITATEA);
        END IF;

        UPDATE NCONTRULSUB
        SET
          RULAJCD  = RULAJCD  + (CASE WHEN V_REC.TIP = 'D' THEN V_REC.VALOARE  ELSE 0 END),
          RULAJCC  = RULAJCC  + (CASE WHEN V_REC.TIP = 'C' THEN V_REC.VALOARE  ELSE 0 END),
          RULAJVCD = RULAJVCD + (CASE WHEN V_REC.TIP = 'D' THEN V_REC.VALOAREV ELSE 0 END),
          RULAJVCC = RULAJVCC + (CASE WHEN V_REC.TIP = 'C' THEN V_REC.VALOAREV ELSE 0 END)
        WHERE
          CODCONTRUL = V_REC_SUB.CODCONTRUL AND SUBUNITATEA = V_REC.SUBUNITATEA;
      END LOOP;
    END IF;
  END LOOP;

  -- fac link intre mifixul provenit din intrari de la subunitati si mifixul iesit de la subunitati
  for v_rec in (SELECT MF.*
               FROM
                 TMP_MIFIX MF
                 INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = MF.CODNIRSTOC
                 INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
                                    AND N.TIPNIR = 6
                                    AND EXTRACT(YEAR FROM DATANIR) = getanlucru()
                                    AND EXTRACT(MONTH FROM DATANIR) = getLunalucru()
               WHERE
                 COALESCE(CODMIFIXVECHI, 0) &gt; 0 AND CODMIFIX &gt; 0)
  loop
   UPDATE MIFIX
   SET
     CODMIFIXNOU = V_REC.CODMIFIX,
     ANLUNAMIFIXNOU = getanlucru()*12+getlunalucru()
  WHERE
    CODMIFIX = V_REC.CODMIFIXVECHI;
 end loop;

  PERFORM PKG_GLOBALS_MarkDirtyJurnal();
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS(36);
  PERFORM NotifyModif (OPERATION, RECID, 'MIFIX');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_sp_gotorecord</obj_name>
  <obj_hashval>0abde9b2055bfb02f819fa74bf64bc3c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  V_REC        RECORD;
  V_REC_OBJ    RECORD;
  aANSFARSIT   numeric;
  aLUNASFARSIT numeric;
  CLASAART     numeric;
  LENDENART    numeric;
BEGIN
  --Florin 04.12.2024 - sinc. Oracle
  --Florin 22.11.2024 - sinc. Oracle
  --Florin 29.05.2024 - sinc. Oracle
  --Florin 10.04.2024 - fixat 61637
  --Florin 13.10.2023 - sinc. Oracle
  --Florin 31.08.2023 - fixat 59304
  --Florin 29.08.2023 - sinc. Oracle
  --Florin 01.06.2023 - sinc. Oracle
  --Florin 12.04.2023 - sinc. Oracle
  --Florin 01.11.2022 - sinc. Oracle
  --Florin 21.10.2022 - fixat 56017
  --Florin 20.10.2022 - sinc. Oracle
  --Florin 18.07.2022 - fixat 54420
  --Florin 19.04.2022 - sinc. Oracle
  --Laura 15.11.2021 - sinc Oracle (15.11.2021)
  --Laura 15.10.2021 - sinc Oracle (14.10.2021)
  --Bogdan 15.04.2021 46890 : Nomenclator articole - stocuri minime si maxime pe gestiuni
    --Adina 12.04.2021 - sinc.Oracle din 09.04.2021 - add codgest doar pe versiunea la zi
  --Adina 18.02.2021 - sinc.cu modif. Oracle din 17.02.2021 + 18.02.2021
    --Adina 02.02.2021 - sinc.cu modif. Oracle din 29.01.2021
    -- Master NART
    --Bogdan 03.02.2021
   --Bogdan 08.02.2021
   --Florin 01.03.2021 - fixat 44213
    --Bogdan 26.03.2021
  --Florin 16.11.2021 - fixat 52001
  perform pkg_nom_articol_setct_monitor('MON_6');
  perform PKG_CFGTABLES_CHECK_STRUCT_EXTENSIE_X_TIPDOC(501);
  insert into TMP_NART (CodArticol, Den_Articol, UM, Clasa, TipSerie, TipArticol, AreTG, ContImplicit, GestImplicita, Certificat, EvolutiePret, UM1, UM2,
                        ContServiciu, INCREMENTSERIE, RELATIEUM1, RELATIEUM2, CASADEMARCAT, CODCENTRU, D1, D2, D3, ParitateD1, ParitateD2, ParitateD3,
                        CLASASTATIST, COMENZIONLINE, CODEXTERNART, SUFIXCODEXTERN, RESTNEGLIJCMD, NRZILESTOCMEDIU, MUSAICALITATE, Culoare, DCI,
                        ClasaW, CHECKISAUTENTIC, PROCPerisab, codmasca, constructienoua, riscfiscal,  TIPSTOC )
  select CodArticol, Den_Articol, UM, Clasa, TipSerie, TipArticol, AreTG, ContImplicit, GestImplicita, Certificat, EvolutiePret, UM1, UM2, ContServiciu, INCREMENTSERIE,
       RELATIEUM1, RELATIEUM2, CASADEMARCAT, CODCENTRU, D1, D2, D3, coalesce( ParitateD1, 1), coalesce( ParitateD2, 1), coalesce( ParitateD3, 1), CLASASTATIST, COMENZIONLINE,
       CODEXTERNART, SUFIXCODEXTERN, RESTNEGLIJCMD, NRZILESTOCMEDIU, MUSAICALITATE, Culoare, DCI,
       ClasaW, CHECKISAUTENTIC, PROCPerisab, codmasca, constructienoua, riscfiscal,  Coalesce(TIPSTOC,0)
  from NART
  where CodArticol = RecId;

  begin
    select CLASA into CLASAART from TMP_NART;
  exception
    when others then CLASAART := 0;
  end;

-- Detail NART1
   INSERT INTO  TMP_NART1 ( CodArticol1,CodArticol,CodTVA,CodAccize,TaxCode, codtaxa1,CodTaxa2,anstart,lunastart, CodAccizeDVI )
   SELECT CodArticol1,CodArticol,CodTVA,CodAccize,TaxCode, codtaxa1,CodTaxa2,anstart,lunastart, CodAccizeDVI
     FROM NART1 WHERE CodArticol = RecId;

--Detail NARTIMPLICITE
  insert into TMP_NARTIMPLICITE select * from NARTIMPLICITE where CodArticol = RecId;

  aANSFARSIT   := 0;
  aLUNASFARSIT := 0;

  for V_REC in ( select CODARTICOL1, ANSTART, LUNASTART from TMP_NART1 order by ANSTART * 12 + LUNASTART desc ) loop
    if ( aANSFARSIT &lt;&gt; 0) and ( aLUNASFARSIT &lt;&gt; 0) then
      update TMP_NART1
      set
        ANSFARSIT = aANSFARSIT, LUNASFARSIT = aLUNASFARSIT
      where CODARTICOL1 = V_REC.CODARTICOL1 ;
    end if;

 select newan,newluna
  from PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA( V_REC.ANSTART, V_REC.LUNASTART, aANSFARSIT, aLUNASFARSIT) into aANSFARSIT, aLUNASFARSIT;

  end loop;
-- Detail
  INSERT INTO  TMP_NARTOBJ (
    CodObiect, CodArticol, CodExtern, CodIntern, StocMin, StocMed, StocMax, INACTIVCMDONLINE, AUTORIZATIE,EXPIRAREAUTORIZ, TRADUCARTGENERIC, MESAJINACTIV,
    Masa, Volum, CodProducator, CodVamal, Returnabil, LuniGarantie,
    Obs, TARAORIGINE, ZILEVALABIL, ZILEDISTRIB, CODPERISABIL, ProcAdaosNir, Rotunjire, UMAmbalare,
    PRETMINIM, TERMENPLATA, DATAADAUGARII, CODPLU, USESTOCMED, NEFACTURABIL, GREUTSPECIFICA, BLOCAT, DURMAXAPROV, CODCNAS,  CODCARACT, CODD394, INACTIV,
    FARACMDFURN, FARANIVELAPROB, DESCARCAREINTEGRALA, FARASTOC, CODCATEGARTTI,
    AdaosExceptie, Promotie, ROTVALUTA, DiscPromo, PRODUSPROPRIU,
    STOCMINSUB, STOCMAXSUB, STOCMEDSUB, DENUMIRE, COEFCNAS, EXPORTEMCS, CODNC, CODCPV, EXCLUSLISTARECM, CODACCIZABIL,
    RAPCNAS, ANTIBIOTIC, LANSIMP, EXPORTKLG, CODANALIZANOD, SAFT_EXPORT, CANTVANZ, CERTIF_DDS)
  SELECT
    A.CodObiect, A.CodArticol, A.CodExtern, A.CodIntern, A.StocMin, A.StocMed, A.StocMax, A.INACTIVCMDONLINE, A.AUTORIZATIE, A.EXPIRAREAUTORIZ, A.TRADUCARTGENERIC, A.MESAJINACTIV,
    A.Masa, A.Volum, A.CodProducator, A.CodVamal, A.Returnabil, A.LuniGarantie,
    A.Obs, A.TARAORIGINE, A.ZILEVALABIL, A.ZILEDISTRIB, A.CODPERISABIL, A.ProcAdaosNir, A.Rotunjire, A.UMAmbalare,
    A.PRETMINIM, A.TERMENPLATA, A.DATAADAUGARII, A.CODPLU, A.USESTOCMED, A.NEFACTURABIL, A.GREUTSPECIFICA, A.BLOCAT, A.DURMAXAPROV, A.CODCNAS, A.CODCARACT, A.CODD394, A.INACTIV,
    A.FARACMDFURN, A.FARANIVELAPROB, A.DESCARCAREINTEGRALA, A.FARASTOC, A.CODCATEGARTTI,
    A.AdaosExceptie, A.Promotie, A.ROTVALUTA, A.DiscPromo, A.PRODUSPROPRIU,
    STOCMIN, STOCMAX, STOCMED, A.DENUMIRE, A.COEFCNAS, A.EXPORTEMCS, A.CODNC, A.CODCPV, A.EXCLUSLISTARECM, A.CODACCIZABIL,
    Coalesce(A.RAPCNAS, CASE WHEN A.CODCNAS IS NULL THEN 0 ELSE 1 END) RAPCNAS, A.ANTIBIOTIC, A.LANSIMP, A.EXPORTKLG, A.CODANALIZANOD,COALESCE(A.SAFT_EXPORT,0), A.CANTVANZ, A.CERTIF_DDS
  from NARTOBJ a, NART b
  where a.CodArticol = RecId
    and a.codarticol = b.codarticol
  order by a.codObiect ;

  insert into TMP_NARTOBJSUBUNIT ( CODS, CODOBIECT, SUBUNITATE, STOCMIN, STOCMED, STOCMAX, PROCSTOCMIN, PROCSTOCMAX, PROCSTOCMED, CODGEST )
  select S.CODS, S.CODOBIECT, S.SUBUNITATE, S.STOCMIN, S.STOCMED, S.STOCMAX, S.PROCSTOCMIN, S.PROCSTOCMAX, S.PROCSTOCMED, S.CODGEST
  from NARTOBJSUBUNIT S, TMP_NARTOBJ OBJ
  where OBJ.CodObiect = S.CodObiect
  --exists ( select OBJ.CodObiect from TMP_NARTOBJ OBJ where OBJ.CodObiect = S.CodObiect )
        and coalesce(S.SUBUNITATE, 1) = CASE when getsubunitate() = 1 then coalesce(S.SUBUNITATE, 1)
                                                                      else getsubunitate()
                                        END
  --order by S.CodObiect
  ;
  insert into TMP_NARTOBJIMP ( CODOBJIMP, CODOBIECT, CODSUBUNIT, GESTIMPLICITA, LOCATIEIMPLICITA, DURMAXAPROV,CONTIMPLICIT )
  select CODOBJIMP, CODOBIECT, CODSUBUNIT, GESTIMPLICITA, LOCATIEIMPLICITA, DURMAXAPROV,CONTIMPLICIT
  from NARTOBJIMP IMP
  where exists ( select OBJ.CodObiect from TMP_NARTOBJ OBJ where OBJ.CodObiect = IMP.CodObiect );

  if getsubunitate() &lt;&gt; 1 then
    update TMP_NARTOBJ O1
    set
      (STOCMINSUB, STOCMAXSUB, STOCMEDSUB)
      =
      (select OS.STOCMIN, OS.STOCMAX, OS.STOCMED
       from TMP_NARTOBJSUBUNIT OS
       where OS.CodObiect = O1.CodObiect
         and OS.SUBUNITATE = getsubunitate()
         AND (OS.CODGEST IS NULL OR OS.CODGEST = 0) limit 1) ;
  end if;
--  if  fnc_tmpexists ('NARTOBJEXT') = 1 and fnc_tmpexists ('TMP_NARTOBJEXT') = 1 THEN
--    EXECUTE 'DELETE FROM TMP_NARTOBJEXT';
--    EXECUTE 'INSERT INTO TMP_NARTOBJEXT SELECT * FROM NARTOBJEXT WHERE CODOBIECT IN (SELECT CODOBIECT FROM TMP_NARTOBJ) ';
--  end if;
-- Detail PRETM
  INSERT INTO TMP_PRETM (CODPRETM, CODOBIECT, CODCATPRET, LEI, VALUTA, MONEDA, IMPLICIT, GRUPA, PROC, INDEXLOCAL, SUBUNITATEA, ROTUNJIRE, SUMAFIXAIMPLICIT)
  SELECT PM.CODPRETM, PM.CODOBIECT, PM.CODCATPRET, PM.LEI, PM.VALUTA, PM.MONEDA, PM.IMPLICIT, PM.GRUPA, PM.PROC, PM.INDEXLOCAL, PM.SUBUNITATEA, PM.ROTUNJIRE, PM.SUMAFIXAIMPLICIT
  from PRETM PM, TMP_NARTOBJ O
  where PM.CODOBIECT = O.CODOBIECT  -- in (select CODOBIECT from TMP_NARTOBJ )
        and coalesce( PM.SUBUNITATEA, 1) = CASE when getsubunitate() = 1
                                                    then coalesce( PM.SUBUNITATEA, 1)
                                                else getsubunitate()
                                           END
  order by pm.CODOBIECT , INDEXLOCAL ;
  update TMP_PRETM P
  set
    (DENCATPRET, TIPCATPRET, DENTIPCATPRET, CODCATMASTER)
    =
    (select DEN_CATPRET, TIP,
            case
              when TIP =  1 then 'nominal cu TVA'
              when TIP =  2 then 'nominal fara TVA'
              when TIP =  3 then '% adaos aplicat la PU inregistrare'
              when TIP =  4 then '% adaos aplicat la PU achizitie'
              when TIP =  5 then '% diminuare PU maximal'
              when TIP =  6 then '% din stoc aplicat la PU inregistrare'
              when TIP =  7 then '% din stoc aplicat la PU achizitie'
              when TIP =  8 then '% distributie aplicat la PU inregistrare'
              when TIP =  9 then '% distributie aplicat la PU achizitie'
              when TIP = 10 then '% adaos aplicat la ultimul PU achizitie'
              when TIP = 11 then '% adaos aplicat la ultimul PU achizitie in valuta'
            END,
            CODCATMASTER
     from NCATPRET
     where CODCATPRET = P.CODCATPRET ) ;

    -- Detail NARTOBJ1
  insert into TMP_NARTOBJ1 (CodObiect1, CodObiect, PretMaximal, ProcAdaosMaximal, PRETREFERINTA, TIPPRETMAX, COMPENSAT, TIPCOMPENSARE, GRUPA, uplift,
                            codmoneda, AdaosLa, PUNCTE, Umiditate, CORPURI_STRAINE, PUNCTESECTIE, Incoltit, Hectolitrica, Gluten, Fuzaritate, Cadere,
                            Deformare, Sticlozitate, Sparturi, anstart, lunastart, tippret, ValMat, ValMan, ValRegie, D390Exclus, cost, Cantservauto,
                            proteina, aflatoxina, atac_plosnita, continut_ulei, aciditate, sistave, refractie, indice_w, toxina_don, boabe_toxice,
                            MAX_UMIDITATE,MAX_CORPURI_STRAINE,MAX_INCOLTIT,MAX_HECTOLITRICA,MAX_GLUTEN,MAX_FUZARITATE,MAX_CADERE,MAX_DEFORMARE,
                            MAX_STICLOZITATE,MAX_SPARTURI,MAX_PROTEINA,MAX_AFLATOXINA,MAX_ATAC_PLOSNITA,MAX_CONTINUT_ULEI,MAX_ACIDITATE,MAX_SISTAVE,
                            MAX_REFRACTIE,MAX_INDICE_W,MAX_TOXINA_DON,MAX_BOABE_TOXICE,
                            MIN_UMIDITATE,MIN_CORPURI_STRAINE,MIN_INCOLTIT,MIN_HECTOLITRICA,MIN_GLUTEN,MIN_FUZARITATE,MIN_CADERE,MIN_DEFORMARE,MIN_STICLOZITATE,MIN_SPARTURI,
                            MIN_PROTEINA,MIN_AFLATOXINA,MIN_ATAC_PLOSNITA,MIN_CONTINUT_ULEI,MIN_ACIDITATE,MIN_SISTAVE,MIN_REFRACTIE,MIN_INDICE_W,MIN_TOXINA_DON,MIN_BOABE_TOXICE, PRETPROD)
  select CodObiect1, CodObiect, PretMaximal, ProcAdaosMaximal, PRETREFERINTA, TIPPRETMAX, COMPENSAT, TIPCOMPENSARE, GRUPA, uplift, codmoneda, AdaosLa,
         PUNCTE, Umiditate, CORPURI_STRAINE, PUNCTESECTIE, Incoltit, Hectolitrica, Gluten, Fuzaritate, Cadere, Deformare, Sticlozitate, Sparturi,
         anstart, lunastart, coalesce( tippret, 1), ValMat, ValMan, ValRegie, coalesce( D390Exclus, 0), cost, CantServAuto, proteina, aflatoxina,
         atac_plosnita, continut_ulei, aciditate, sistave, refractie, indice_w, toxina_don, boabe_toxice,
         MAX_UMIDITATE,MAX_CORPURI_STRAINE,MAX_INCOLTIT,MAX_HECTOLITRICA,MAX_GLUTEN,MAX_FUZARITATE,MAX_CADERE,MAX_DEFORMARE,
         MAX_STICLOZITATE,MAX_SPARTURI,MAX_PROTEINA,MAX_AFLATOXINA,MAX_ATAC_PLOSNITA,MAX_CONTINUT_ULEI,MAX_ACIDITATE,MAX_SISTAVE,
         MAX_REFRACTIE,MAX_INDICE_W,MAX_TOXINA_DON,MAX_BOABE_TOXICE,
         MIN_UMIDITATE,MIN_CORPURI_STRAINE,MIN_INCOLTIT,MIN_HECTOLITRICA,MIN_GLUTEN,MIN_FUZARITATE,MIN_CADERE,MIN_DEFORMARE,MIN_STICLOZITATE,MIN_SPARTURI,
         MIN_PROTEINA,MIN_AFLATOXINA,MIN_ATAC_PLOSNITA,MIN_CONTINUT_ULEI,MIN_ACIDITATE,MIN_SISTAVE,MIN_REFRACTIE,MIN_INDICE_W,MIN_TOXINA_DON,MIN_BOABE_TOXICE, PRETPROD
  FROM NARTObj1 o1 WHERE exists (Select tmp.codobiect from TMP_NartOBJ tmp where tmp.codobiect = o1.codobiect);

-- traduceri denumiri
  insert into TMP_NARTOBJTRAD ( CodObiectTrad, CodObiect, CodLimba, DenumireTrad, Avertizare, Descriere )
  (select CodObiectTrad, CodObiect, CodLimba, DenumireTrad, Avertizare, descriere
  FROM NARTOBJTRAD n WHERE exists (SELECT tmp.codobiect FROM TMP_NARTOBJ tmp where n.codobiect = tmp.codobiect));

  insert into TMP_DISCPROMORETAIL ( COD, CODPOSTRETAIL, CODOBIECT, DISCPROMO, DENUMIRE )
  (select D.COD, D.CODPOSTRETAIL, D.CODOBIECT, D.DISCPROMO, P.DENUMIRE
   from DISCPROMORETAIL D, POSTRETAIL P
  WHERE exists (SELECT tmp.codobiect FROM TMP_NARTOBJ tmp where d.codobiect = tmp.codobiect)
  and P.COD = D.CODPOSTRETAIL
  );

  for V_REC_OBJ in (select CODOBIECT from TMP_NARTOBJ ) loop
    aANSFARSIT := 0;
    aLUNASFARSIT := 0;

    for V_REC in (select CODOBIECT1, ANSTART, LUNASTART from TMP_NARTOBJ1 where CODOBIECT = V_REC_OBJ.CODOBIECT order by ANSTART * 12 + LUNASTART desc ) loop
      if (aANSFARSIT &lt;&gt; 0) and ( aLUNASFARSIT &lt;&gt; 0) then
        update TMP_NARTOBJ1
        set
          ANSFARSIT   = aANSFARSIT,
          LUNASFARSIT = aLUNASFARSIT
        where CODOBIECT1 = V_REC.CODOBIECT1 ;
      end if;

   select newan,newluna
  from PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA( V_REC.ANSTART, V_REC.LUNASTART, aANSFARSIT, aLUNASFARSIT) into aANSFARSIT, aLUNASFARSIT;

    end loop;
  end loop;
-- Detail NARTCLI
  insert into TMP_NARTCLI (CodArtCli, CodObiect, CodPart, Denumire, CodExtern, UMSec, UMCorelat, DenUMCorel, CODMONEDA, PRET, tipcodafisat,
                           CodLaClient, CODINTERN, implicit, DEN_PART, CODCLASEP, SIMBOLCLASAP, CODGAMA, OBS, DENGAMA, OBS2, UMSECIMPDOC,
                           Duratatr, Zilestoc, GLN, IDspecific )
  select ac.CodArtCli, ac.CodObiect, ac.CodPart, ac.Denumire, ac.CodExtern, ac.UMSec, ac.UMCorelat, u.Den_UM1, ac.CODMONEDA, ac.PRET,
         ac.tipcodafisat, CodLaClient, ac.CODINTERN, ac.IMPLICIT, P.DEN_PART, AC.CODCLASEP, CP.SIMBOL, AC.CODGAMA, AC.OBS, G.DENUMIRE,
         AC.OBS2, AC.UMSECIMPDOC, ac.duratatr, ac.zilestoc, ac.GLN, ac.IDspecific
  from NARTCLI ac
       left join NUM1     u  ON u.CodUM1     = ac.UmCorelat
       left join NPART    P  ON P.CodPART    = ac.CODPART
       left join NCLASEP  CP ON CP.CODCLASEP = AC.CODCLASEP
       left join NGAMEART G  ON G.CODGAMA    = AC.CODGAMA
  where ac.CodObiect in ( select CodObiect from TMP_NARTOBJ );

-- Detail NATROBJ
  insert into TMP_NATROBJ ( CodObiect, CodAtrOBJ, CodArtAtr, CodValAtr, INDEXLOCAL )
  select *
  from (select C2.CodObiect, C2.CodAtrOBJ, C2.CodArtAtr, C2.CodValAtr, C2.INDEXLOCAL
        from NARTOBJ C1, NATROBJ C2
        where C2.CodObiect = C1.CodObiect and C1.CodArticol = RecId
       ) A_PG
  order by INDEXLOCAL ;

-- Detail NARTATR
  insert into TMP_NARTATR ( CodArtAtr, CodArticol, CodAtribut, Activ, CodValPredef, Obligatoriu, OBS, Selectie, Facturabil, INDEXLOCAL )
  select *
  from ( select * from (select CodArtAtr, CodArticol, CodAtribut, Activ, CodValPredef, Obligatoriu, OBS, Selectie, Facturabil, INDEXLOCAL
                        from NARTATR
                        where CodArticol = RecID order by INDEXLOCAL
                       ) B_PG
       ) C_PG
  order by INDEXLOCAL ;

-- Detail NARTATR
  insert into TMP_NARTDIM ( CodArtDim, CodObiect, CodArticol, Tip, D1, D2, D3 )
  select *
  from ( select * from ( select CodArtDim, coalesce( CodObiect, 0), CodArticol, Tip, D1, D2, D3
                         from NARTDIM
                         where CodArticol = RecID
                         order by Tip , D1 , D2 , D3
                       ) D_PG
       ) E_PG
  order by Tip , D1 , D2 , D3 ;
-- completare campuri adaugate
  BEGIN
   SELECT LENGTH(DEN_ARTICOL) INTO LENDENART FROM NART A WHERE CODARTICOL = RECID;
   EXCEPTION WHEN OTHERS THEN
     LENDENART := 0;
  END;

  FOR V_REC IN (SELECT O.*, AO.CODATROBJ FROM
              TMP_NARTOBJ O
              LEFT JOIN LATERAL (select * from TMP_NATROBJ TNT where TNT.CODOBIECT = O.CODOBIECT limit 1 ) AO ON AO.CODOBIECT = O.CODOBIECT
             )
  LOOP
    UPDATE TMP_NARTOBJ O
    SET
      DENOBIECT   = CASE
                      WHEN V_REC.CODATROBJ &lt;&gt; 0 THEN trim(substring(V_REC.DENUMIRE, (LENDENART + 1)::integer, LENGTH(V_REC.DENUMIRE)))
                      ELSE ' .... Fara atribute ...'
                    END,
      AREATRIBUTE = CASE
                      WHEN V_REC.CODATROBJ &lt;&gt; 0  THEN 1
                      ELSE 0
                    END
    WHERE
      o.CODOBIECT = V_REC.CODOBIECT;
  END LOOP;

/*
  update TMP_NARTOBJ O
  set
  DENOBIECT = case
                when ( select count(*) from TMP_NATROBJ A where A.CODOBIECT = O.CODOBIECT ) &gt; 0
                     then ( select PKG_SELECTARTICOLE_GET_JUST_DENOBIECT.WME_RESULT from PKG_SELECTARTICOLE_GET_JUST_DENOBIECT(null, CODOBIECT))
                else ' .... Fara atribute ...'
              end ,
  AREATRIBUTE = case
                  when ( select count(*) from TMP_NATROBJ A where A.CODOBIECT = O.CODOBIECT ) &gt; 0 then 1
                  else 0
                end ;
*/

 -- legaturi cu criterii discounturile
-- Detail CRITERIIDISC -- pentru fiecare obiect INSEREZ IN CRITERII CATE UN SET DE CRITERIU
-- Detail DISCART -- aduc numai inregistrarile coresounzatoare discount-urilor pe OBIECT
  insert into TMP_DISCART ( CodDiscArt, CodDiscount, CodObiect )
  ( select DA.CodDiscArt, DA.CodDiscount, DA.CodObiect
    from DISCART DA
         left join DISCOUNT D ON D.CODDISCOUNT = DA.CODDISCOUNT
         left join CRITERIIDISC CR ON CR.CODCRITERIU = D.CODCRITERIU
    where ( ( CR.PECLASE = 0) and ( DA.CODOBIECT in ( select CODOBIECT from TMP_NARTOBJ )) )
          or
          ( ( CR.PECLASE = 1) and ( DA.CODOBIECT = CLASAART) ) );

-- Detail DISCOUNT
  insert into TMP_DISCOUNT ( CodDiscount, CodCriteriu )
  ( select CodDiscount, CodCriteriu from DISCOUNT where CODDISCOUNT in ( select CODDISCOUNT from TMP_DISCART ) );

-- Detail DISCINTERVAL
  insert into TMP_DISCINTERVAL ( CodDiscInterval, CodDiscount, LimInf, LimSup, Procent )
  ( select CodDiscInterval, CodDiscount, LimInf, LimSup, Procent
    from DISCINTERVAL
    where CODDISCOUNT in ( select CODDISCOUNT from TMP_DISCOUNT ) );

  -- actualizez campul DISCOUNTINFO in TMP_DISCOUNT - musai dupa ce am DISCINTERVAL COMPLETAT
  update TMP_DISCOUNT D
  set
    DISCOUNTINFO = ( select PKG_CRITERIIDISCOUNT_GETDISCINTERVALE.WME_RESULT from PKG_CRITERIIDISCOUNT_GETDISCINTERVALE(null, D.CODDISCOUNT)) ;

  for V_REC in (select * from TMP_NARTOBJ ) loop
    insert into TMP_CRITERIIDISC ( CodCriteriu, DenCriteriu, ExcludVolTr, ExcludCantFact, ExcludTermen, ExcludValDoc, ExcludDistanta, PeClase, CODOBIECT )
    ( select CodCriteriu, DenCriteriu, ExcludVolTr, ExcludCantFact, ExcludTermen, ExcludValDoc, ExcludDistanta, PeClase, V_REC.CODOBIECT
      from CRITERIIDISC
      where CODCRITERIU &gt; 0 and CODCRITERIU in ( select CODCRITERIU from TMP_DISCOUNT )
    );
  end loop;

-- fac legatura intre CRITERII si discount-urile asignate articolelor
  -- PENTRU CELE PE ARTICOL :
  for V_REC in (select DA.CODDISCART, DI.CODDISCOUNT, DA.CODOBIECT, DI.CODCRITERIU
                from TMP_DISCART DA, TMP_DISCOUNT DI, TMP_CRITERIIDISC CR
                where DA.CODDISCOUNT = DI.CODDISCOUNT and DI.CODCRITERIU = CR.CODCRITERIU
               )
  loop
    update TMP_CRITERIIDISC CRIT
    set
      DISCOUNTCURENT = V_REC.CODDISCOUNT
    where CRIT.PECLASE = 0
      and CRIT.CODCRITERIU = V_REC.CODCRITERIU
      and CRIT.CODOBIECT   = V_REC.CODOBIECT ;
  end loop;

-- PENTRU CELE PE CLASE :
  update TMP_CRITERIIDISC CRIT
  set
    DISCOUNTCURENT = ( select DI.CODDISCOUNT
                       from TMP_DISCOUNT DI, TMP_DISCART DA
                       where DI.CODCRITERIU = CRIT.CODCRITERIU
                         and DA.CODDISCOUNT = DI.CODDISCOUNT
                         and DA.CODCLASA = CLASAART
                     )
  where CRIT.PECLASE = 1 ;

  update TMP_CRITERIIDISC CRIT
  set
    INFODISCOUNTCURENT = coalesce( ( select DISCOUNTINFO from TMP_DISCOUNT where CODDISCOUNT = CRIT.DISCOUNTCURENT ), '?')
  where DISCOUNTCURENT is not null ;

  insert into TMP_NECHIV ( CODECHIV, CODOBIECT, CODOBIECTECHIV, PARITATE, CODGRUPA, GENERIC, INDEXLOCAL, Ind )
  select E.CODECHIV, E.CODOBIECT, E.CodObiect, E.PARITATE, E.CODGRUPA, E.GENERIC, E.INDEXLOCAL, E.Ind
  from NECHIV E
  where exists ( select CODOBIECT from TMP_NARTOBJ O where O.CODOBIECT = E.CODOBIECT );
  insert into TMP_NARTOPT ( CODOPT, CODOBIECT, codobiectopt, CodTipLocatie, ForceLei, CANT, STANDARD, OBS, DENOBIECTOPT, CODEXTERN, CODINTERN, SELECTAT, LEI )
  ( select CODOPT, A.CODOBIECT, codobiectopt, CodTipLocatie, ForceLei, CANT, STANDARD, A.OBS, O.DENUMIRE, O.CODEXTERN, O.CODINTERN, 0, PM.LEI
    from NARTOPT A
         left join NARTOBJ O  ON O.CODOBIECT = A.codobiectopt
         left join PRETM   PM ON PM.CODOBIECT = O.CODOBIECT and PM.SUBUNITATEA = ( select PKG_GLOBALS_GETSUBUNITATE.WME_RESULT from PKG_GLOBALS_GETSUBUNITATE(null, null))
                             and PM.IMPLICIT = 1
    where A.CODOBIECT in ( select CODOBIECT from TMP_NARTOBJ ) );

  insert into TMP_NARTAMB ( CODAMB, CODOBIECT, CODOBIECTRETURN, CANT, CANTMIN, UMSEC, CODEXTERN, CODPLU, CODINTERN, MASA, LUNGIME, LATIME, INALTIME,
                            LXLAT, LXH, LATXH, GREUTSPECIFICA, IMPLICITTIPDOC, TIP, DENOBIECTRETURN, DENUMSEC, PARITATE, IMPLICIT, nr_randuri, AdMax, returnabil)
  (select CODAMB, CODOBIECT, CODOBIECTRETURN, CANT, CANTMIN, UMSEC, CODEXTERN, CODPLU, CODINTERN, MASA, LUNGIME, LATIME, INALTIME,
          LXLAT, LXH, LATXH, GREUTSPECIFICA, IMPLICITTIPDOC, TIP,
          (select DENUMIRE  from NARTOBJ  where CODOBIECT = A.CODOBIECTRETURN ),
          (select Den_UM1   from NUM1     where CodUM1 = A.UMSEC ),
          (select Paritate  from NUM1     where CodUM1 = A.UMSEC ),
          case
            when coalesce( UMSEC, -1) in ( select coalesce( UMAMBALARE, 0) from tmp_nartobj ) then 1
            else 0
          END,
          nr_randuri, AdMax, COALESCE(returnabil, 1)
   from NARTAMB A
   where CODOBIECT in ( select CODOBIECT from TMP_NARTOBJ ) );

  insert into TMP_PRETMAMB ( CODPRETMAMB, CODPRETM, CODAMB, LEI, VALUTA, DENUMSEC )
  select PAMB.CODPRETMAMB, PAMB.CODPRETM, PAMB.CODAMB, PAMB.LEI, PAMB.VALUTA, U1.DEN_UM1
  from PRETMAMB PAMB, TMP_NARTAMB AMB, NUM1 U1
  where AMB.UMSEC &gt; 0
    and AMB.CODAMB = PAMB.CODAMB
    and U1.CODUM1 = AMB.UMSEC
    AND EXISTS (SELECT 1 FROM TMP_PRETM WHERE CODPRETM = PAMB.CODPRETM);

  insert into TMP_NARTOBJCOLET select * from NARTOBJCOLET C where exists ( select CODOBIECT from TMP_NARTOBJ where CODOBIECT = C.CODOBIECT );

  INSERT INTO TMP_CODEXTALT (COD, CODOBIECT, CODEXTERN, CODPART, DEN_PART)
  SELECT C.COD, C.CODOBIECT, C.CODEXTERN, C.CODPART, P.DEN_PART
  FROM CODEXTALT C
  LEFT JOIN NPART P ON P.CODPART = C.CODPART
  WHERE EXISTS (SELECT CODOBIECT FROM TMP_NARTOBJ WHERE CODOBIECT = C.CODOBIECT);

  INSERT INTO TMP_CODINTALT (COD, CODOBIECT, CODINTERN, CODPART, DEN_PART)
  SELECT C.COD, C.CODOBIECT, C.CODINTERN, C.CODPART, P.DEN_PART
  FROM CODINTALT C
  LEFT JOIN NPART P ON P.CODPART = C.CODPART
  WHERE EXISTS (SELECT CODOBIECT FROM TMP_NARTOBJ WHERE CODOBIECT = C.CODOBIECT);

  --for v_rec in ( select CodObiect from TMP_NARTOBJ ) loop
  UPDATE TMP_NARTOBJ o
    SET
    OPTIONALE = (SELECT COUNT(*) FROM TMP_NARTOPT tmp WHERE tmp.CODOBIECT = o.CODOBIECT);
  --end loop;

  update TMP_NARTOBJSUBUNIT NS
  set
    DENSUBUNIT = (select DEN_SUBUNIT from NSUBUNIT  where CODSUBUNIT  = NS.SUBUNITATE ),
    DEN_GEST   = (SELECT DEN_GEST    FROM ngest GST WHERE GST.CODGEST = NS.CODGEST) ;

  DELETE from TMP_NARTOBJSUBUNIT_INI;
  insert into TMP_NARTOBJSUBUNIT_INI select CODS from TMP_NARTOBJSUBUNIT;

  for V_REC in ( select PAMB.CODPRETMAMB, PAMB.LEI, U1.PARITATE
                 from TMP_PRETMAMB PAMB, NARTAMB AMB, NUM1 U1
                 where PAMB.CODAMB = AMB.CODAMB and AMB.UMSEC = U1.CODUM1
               )
  loop
    update TMP_PRETMAMB
    set
      PARITATE = V_REC.PARITATE,
      LEIUMP   = case
                   when coalesce( V_REC.PARITATE, 0) &lt;&gt; 0 then V_REC.LEI / V_REC.PARITATE
                   else null
                 end
    where CODPRETMAMB = V_REC.CODPRETMAMB ;
  end loop;
  PERFORM PKG_CFGTABLES_EXT_GOTORECORD(501);
 end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_postretail_preia_puncte_pebaza</obj_name>
  <obj_hashval>fd95e3a888fb2fc5595fbcdc01247608</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_postretail_preia_puncte_pebaza(acodpostretail numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM TOTALPUNCTE WHERE CODPOSTRETAIL = aCODPOSTRETAIL;
  INSERT INTO TOTALPUNCTE(COD, CODPART, CODPUNCTAJ, PUNCTE, VALOARE, CODPOSTRETAIL)
  SELECT NEXTVAL('SEQ_TOTALPUNCTE_COD'), CODPART, CODPUNCTAJ, PUNCTE, VALOARE, CODPOSTRETAIL FROM TMP_TOTALPUNCTE;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_postretail_sp_deleterecord</obj_name>
  <obj_hashval>6cc16a6daec682bd56ecdd7ead5bc4f7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_postretail_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Florin 27.11.2025 - sinc. oracle
  PERFORM PKG_POSTRETAIL_SP_LOCKRECORD( RecId);
  DELETE FROM INACTIVRETAIL WHERE CODPOSTRETAIL = RECID;
  DELETE FROM POSTRETAIL WHERE COD = RecId;
  PERFORM NotifyModif( 2, RecId, 'POSTRETAIL');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_postretail_sp_insertrecord</obj_name>
  <obj_hashval>5861a999193026eb42605eef30479e20</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_postretail_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_POSTRETAIL(COD) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getpretmaterialcompus</obj_name>
  <obj_hashval>ce3228cf6e6eb1f04e90cfe49850bc37</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getpretmaterialcompus(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT apret numeric, INOUT tippret numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC1 RECORD;
  V_REC RECORD;
  V_TMP RECORD;
  aCount      numeric;
  aCount1     numeric;
  aCount2     numeric;
  vPret       numeric;
  valmat      numeric;
  valman      numeric;
  regie       numeric;
  PretDinStoc numeric;
  PretMax     numeric;
  PretMin     numeric;
begin
  --Laura 26.01.2022 - sinc. Oracle (28.12.2021)
  SELECT count (pc.codprodcomp) INTO aCount
  FROM prodcomp_clona pcc INNER JOIN prodcomp pc ON pc.codprodcomp = pcc.codprodcomp
  WHERE pc.codobiect = aCodObiect;

  IF aCount = 0 THEN
    PretDinStoc := (SELECT PKG_PRODCOMP_GetPretFromStoc.WME_RESULT FROM PKG_PRODCOMP_GetPretFromStoc (NULL,aCodObiect));
    IF PretDinStoc = 0 THEN
      WME_Result := aPret;
      RETURN;
    ELSE
      WME_Result := PretDinStoc;
      RETURN;
    END IF;
  END IF;

  SELECT count (valoare) INTO aCount1 FROM tmp_manevra_liste WHERE valoare::numeric = aCodObiect;

  IF aCount1 = 0 THEN
    INSERT INTO tmp_manevra_liste (valoare) VALUES (aCodObiect);
  ELSE
    PretDinStoc := (SELECT PKG_PRODCOMP_GetPretFromCompusi.WME_RESULT FROM PKG_PRODCOMP_GetPretFromCompusi (NULL,aCodObiect));
    IF PretDinStoc &gt; 0 THEN
      WME_Result := PretDinStoc;
      RETURN;
    END IF;
  END IF;

  SELECT count (pc.codprodcomp) INTO aCount2
  FROM prodcomp_clona pcc INNER JOIN prodcomp pc ON pcc.codprodcomp = pc.codprodcomp
  WHERE pc.codobiect = aCodObiect and pc.generic = 1;

  IF aCount2 &gt; 0 THEN
    vPret := 0;
    FOR v_rec1 IN ( SELECT pc.codprodcomp, pc.cant, COALESCE (pc.tippret, COALESCE (Tmp.tippret, 1)) TIPPRET, COALESCE (pc.CoefIndirecte, 0) COEFINDIRECTE
                    FROM prodcomp_clona           pcc
                      INNER JOIN prodcomp         pc  ON pcc.codprodcomp = pc.codprodcomp
                      INNER JOIN tmp_nartobj_luna tmp ON pc.codobiect    = tmp.codobiect
                    WHERE
                      pc.codobiect = aCodObiect
                      and pc.generic = 1)
    LOOP
      IF v_rec1.tippret = 1 THEN
        valmat := 0;
        valman := 0;
        regie  := 0;

        FOR v_rec IN (SELECT codprodgest FROM prodgest WHERE codprodcomp = v_Rec1.codprodcomp) LOOP
          FOR v_tmp IN (SELECT COALESCE (pg.coefman, COALESCE (ng.coefcheltman, 0)) COEFCHELTMAN,
                               round ( ( (t1.tarif * man.tu) / 60 / CASE WHEN COALESCE (man.bps, 1) = 0 THEN 1 ELSE COALESCE (man.bps, 1) END) ::numeric, 7)  VALOARE
                        FROM prodman man
                          INNER JOIN prodgest pg ON man.codprodgest = pg.codprodgest
                          LEFT  JOIN TARIFEMAN1 T1  ON t1.codtarif = man.codtarif AND getANLUNALUCRU() BETWEEN T1.ALStart AND T1.ALStop
                          LEFT JOIN ngest ng ON ng.codgest = pg.codgest
                        WHERE
                          man.codprodcomp = v_rec1.codprodcomp
                          and pg.codprodgest = v_rec.codprodgest)
          LOOP
            valman := valman + v_tmp.valoare;
            IF NOT (current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
                and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2)
            THEN
              regie := regie + v_tmp.valoare * v_tmp.coefcheltman;
            END IF;
          END LOOP;

          FOR v_tmp IN (SELECT mat.codobiect, mat.cant, COALESCE (mat.tip, 3) TIP
                        FROM prodmat          mat
                          INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                          LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                        WHERE
                          mat.codprodcomp = v_rec1.codprodcomp
                          and pg.codprodgest = v_rec.codprodgest
                          and COALESCE (mat.tip, 3) &lt; 3)
          LOOP
            valman := valman + v_tmp.cant / v_Rec1.cant * (SELECT PKG_PRODCOMP_GetValoareMan.WME_RESULT FROM PKG_PRODCOMP_GetValoareMan (NULL,v_tmp.codobiect, TipPret));
          END LOOP;

          FOR v_tmp IN (SELECT mat.codobiect, COALESCE (pg.coefmat, COALESCE (ng.coefcheltmat, 0)) COEFCHELTMAT, mat.cant, mat.pret, COALESCE (mat.tip, 3) TIP
                        FROM prodmat          mat
                          INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                          LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                        WHERE
                          mat.codprodcomp = v_rec1.codprodcomp
                          and pg.codprodgest = v_rec.codprodgest)
          LOOP
            IF v_tmp.tip IN (3, 5) THEN
              valmat := valmat + v_tmp.cant * (SELECT PKG_PRODCOMP_GetPretFromStoc.WME_RESULT FROM PKG_PRODCOMP_GetPretFromStoc (NULL,v_tmp.codobiect));
              IF NOT (current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
                  and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2)
              THEN
                regie := regie + v_tmp.cant * (SELECT PKG_PRODCOMP_GetPretFromStoc.WME_RESULT FROM PKG_PRODCOMP_GetPretFromStoc (NULL,v_tmp.codobiect)) / v_rec1.cant * v_tmp.coefcheltmat;
              END IF;
            ELSE
              valmat := valmat + v_tmp.cant * (SELECT pkg_prodcomp_GetValoareMat.WME_RESULT FROM pkg_prodcomp_GetValoareMat (NULL,v_tmp.codobiect, TipPret));
            END IF;
          END LOOP;

          FOR v_tmp IN (SELECT mat.codobiect, mat.cant, COALESCE (mat.tip, 3) TIP
                        FROM prodmat          mat
                          INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                          LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                        WHERE
                          mat.codprodcomp = v_rec1.codprodcomp
                          and pg.codprodgest = v_rec.codprodgest
                          and COALESCE (mat.tip, 3) &lt; 3)
          LOOP
            regie := regie + v_tmp.cant / v_Rec1.cant * (SELECT pkg_prodcomp_GetRegie.WME_RESULT FROM pkg_prodcomp_GetRegie (NULL,v_tmp.codobiect, TipPret));
          END LOOP;

          ValMat := ValMat / v_Rec1.Cant;
          IF current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
            and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2 THEN
            regie := regie + v_rec1.coefindirecte;
          END IF;
          vpret := vpret + valmat + valman + regie;
        END LOOP;
      ELSE
        valmat := 0;
        FOR v_rec IN (SELECT codprodgest FROM prodgest WHERE codprodcomp = v_Rec1.codprodcomp) LOOP
          FOR v_tmp IN (SELECT mat.codobiect, COALESCE (pg.coefmat, COALESCE (ng.coefcheltmat, 0)) COEFCHELTMAT, mat.cant, mat.pret, COALESCE (mat.tip, 3)                                                               TIP
                        FROM prodmat          mat
                          INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                          LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                        WHERE
                          mat.codprodcomp = v_rec1.codprodcomp
                          and pg.codprodgest = v_rec.codprodgest)
          LOOP
            IF v_tmp.tip IN (3, 5) THEN
              valmat := valmat + v_tmp.cant * (SELECT PKG_PRODCOMP_GetPretFromStoc.WME_RESULT FROM PKG_PRODCOMP_GetPretFromStoc (NULL,v_tmp.codobiect));
            ELSE
              valmat := valmat + v_tmp.cant * (SELECT pkg_prodcomp_GetValoareMat.WME_RESULT FROM pkg_prodcomp_GetValoareMat (NULL,v_tmp.codobiect, TipPret));
            END IF;
          END LOOP;
          ValMat := ValMat / v_Rec1.Cant;
          vpret  := vpret  + valmat;
        END LOOP;
      END IF;
    END LOOP;

    UPDATE tmp_manevra_compusi
    SET pret = vPret / aCount2
    WHERE
      codobiect = aCodObiect;

    WME_Result := vPret / aCount2;
    RETURN;
  ELSE
    vPret := 0;
    IF TipPret = 1 THEN
      PretMax := 0;
      FOR v_rec1 IN ( SELECT pc.codprodcomp, pc.cant, COALESCE (pc.tippret, COALESCE (Tmp.tippret, 1)) TIPPRET, COALESCE (pc.coefindirecte, 0) COEFINDIRECTE
                      FROM prodcomp                 pc
                        INNER JOIN prodcomp         pcc ON pc.codprodcomp = pcc.codprodcomp
                        INNER JOIN tmp_nartobj_luna tmp ON pc.codobiect = tmp.codobiect
                      WHERE pc.codobiect = aCodObiect)
      LOOP
        IF v_rec1.tippret = 1 THEN
          valmat := 0;
          valman := 0;
          regie  := 0;

          FOR v_rec IN (SELECT codprodgest FROM prodgest WHERE codprodcomp = v_Rec1.codprodcomp) LOOP
            FOR v_tmp IN (SELECT COALESCE (pg.coefman, COALESCE (ng.coefcheltman, 0)) COEFCHELTMAN,
                                 round ( ( (t1.tarif * man.tu) / 60 / CASE WHEN COALESCE (man.bps, 1) = 0 THEN 1 ELSE COALESCE (man.bps, 1) END) ::numeric, 7)  VALOARE
                          FROM prodman man
                            INNER JOIN prodgest pg ON man.codprodgest = pg.codprodgest
                            LEFT  JOIN TARIFEMAN1 T1 ON t1.codtarif = man.codtarif AND getANLUNALUCRU() BETWEEN T1.ALStart AND T1.ALStop
                            LEFT JOIN ngest ng ON ng.codgest = pg.codgest
                          WHERE
                            man.codprodcomp = v_rec1.codprodcomp
                            and pg.codprodgest = v_rec.codprodgest)
            LOOP
              valman := valman + v_tmp.valoare;
              IF NOT (current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
                  and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2)
              THEN
                regie := regie + v_tmp.valoare * v_tmp.coefcheltman;
              END IF;
            END LOOP;

            FOR v_tmp IN (SELECT mat.codobiect, mat.cant, COALESCE (mat.tip, 3) TIP
                          FROM prodmat           mat
                            INNER JOIN prodgest  pg ON mat.codprodgest = pg.codprodgest
                            LEFT  JOIN ngest     ng ON ng.codgest = pg.codgest
                          WHERE
                            mat.codprodcomp = v_rec1.codprodcomp
                            and pg.codprodgest = v_rec.codprodgest
                            and COALESCE (mat.tip, 3) &lt; 3)
            LOOP
              valman := valman + v_tmp.cant / v_Rec1.cant * (SELECT PKG_PRODCOMP_GetValoareMan.WME_RESULT FROM PKG_PRODCOMP_GetValoareMan (NULL,v_tmp.codobiect, TipPret));
            END LOOP;

            FOR v_tmp IN (SELECT mat.codobiect, COALESCE (pg.coefmat, COALESCE (ng.coefcheltmat, 0)) COEFCHELTMAT, mat.cant, mat.pret, COALESCE (mat.tip, 3)                                                               TIP
                          FROM prodmat          mat
                            INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                            LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                          WHERE
                            mat.codprodcomp = v_rec1.codprodcomp
                            and pg.codprodgest = v_rec.codprodgest)
            LOOP
              IF v_tmp.tip IN (3, 5) THEN
                valmat := valmat + v_tmp.cant * (SELECT PKG_PRODCOMP_GetPretFromStoc.WME_RESULT FROM PKG_PRODCOMP_GetPretFromStoc (NULL,v_tmp.codobiect));
                IF NOT (current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
                    and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2)
                THEN
                  regie := regie + v_tmp.cant / v_Rec1.cant * (SELECT PKG_PRODCOMP_GetPretFromStoc.WME_RESULT FROM PKG_PRODCOMP_GetPretFromStoc (NULL,v_tmp.codobiect)) * v_tmp.coefcheltmat;
                END IF;
              ELSE
                valmat := valmat + v_tmp.cant * (SELECT pkg_prodcomp_GetValoareMat.WME_RESULT FROM pkg_prodcomp_GetValoareMat (NULL,v_tmp.codobiect, TipPret));
              END IF;
            END LOOP;

            FOR v_tmp IN (SELECT mat.codobiect, mat.cant, COALESCE (mat.tip, 3) TIP
                          FROM prodmat          mat
                            INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                            LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                          WHERE
                            mat.codprodcomp = v_rec1.codprodcomp
                            and pg.codprodgest = v_rec.codprodgest
                            and COALESCE (mat.tip, 3) &lt; 3)
            LOOP
              regie := regie + v_tmp.cant / v_Rec1.cant * (SELECT pkg_prodcomp_GetRegie.WME_RESULT FROM pkg_prodcomp_GetRegie (NULL,v_tmp.codobiect, TipPret));
            END LOOP;

            ValMat := ValMat / v_Rec1.Cant;
            IF current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
              and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2 THEN
              regie := regie + v_rec1.coefindirecte;
            END IF;
            vpret := vpret + valmat + valman + regie;
          END LOOP;
        ELSE
          valmat := 0;
          FOR v_rec IN (SELECT codprodgest FROM prodgest WHERE codprodcomp = v_Rec1.codprodcomp) LOOP
            FOR v_tmp IN (SELECT mat.codobiect, COALESCE (pg.coefmat, COALESCE (ng.coefcheltmat, 0)) COEFCHELTMAT, mat.cant, mat.pret, COALESCE (mat.tip, 3)                                                               TIP
                          FROM prodmat          mat
                            INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                            LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                          WHERE
                            mat.codprodcomp = v_rec1.codprodcomp
                            and pg.codprodgest = v_rec.codprodgest)
            LOOP
              IF v_tmp.tip IN (3, 5) THEN
                valmat := valmat + v_tmp.cant * (SELECT PKG_PRODCOMP_GetPretFromStoc.WME_RESULT FROM PKG_PRODCOMP_GetPretFromStoc (NULL,v_tmp.codobiect));
              ELSE
                valmat := valmat + v_tmp.cant * (SELECT pkg_prodcomp_GetValoareMat.WME_RESULT FROM pkg_prodcomp_GetValoareMat (NULL,v_tmp.codobiect, TipPret));
              END IF;
            END LOOP;
            ValMat := ValMat / v_Rec1.Cant;
            vpret  := vpret  + valmat;
          END LOOP;
        END IF;

        IF vPret &gt; PretMax THEN
          PretMax := vPret;
        END IF;
      END LOOP;

      UPDATE tmp_manevra_compusi SET pret = PretMax WHERE codobiect = aCodObiect;

      WME_Result := PretMax;
      RETURN;
    ELSE
      IF TipPret = 3 THEN
        PretMin := 0;
        FOR v_rec1 IN ( SELECT pc.codprodcomp, pc.cant, COALESCE (pc.tippret, COALESCE (Tmp.tippret, 1)) TIPPRET, COALESCE (pc.coefindirecte, 0) COEFINDIRECTE
                        FROM prodcomp                 pc
                          INNER JOIN prodcomp         pcc ON pc.codprodcomp = pcc.codprodcomp
                          INNER JOIN tmp_nartobj_luna tmp ON pc.codobiect = tmp.codobiect
                        WHERE
                          pc.codobiect = aCodObiect)
        LOOP
          IF v_rec1.tippret = 1 THEN
            valmat := 0;
            valman := 0;
            regie  := 0;
            FOR v_rec IN (SELECT codprodgest FROM prodgest WHERE codprodcomp = v_Rec1.codprodcomp) LOOP
              FOR v_tmp IN (SELECT COALESCE (pg.coefman, COALESCE (ng.coefcheltman, 0)) COEFCHELTMAN,
                                   round ( ( (t1.tarif * man.tu) / 60 / CASE WHEN COALESCE (man.bps, 1) = 0 THEN 1 ELSE COALESCE (man.bps, 1) END) ::numeric, 7)  VALOARE
                            FROM prodman man
                              INNER JOIN prodgest pg ON man.codprodgest = pg.codprodgest
                              LEFT  JOIN TARIFEMAN1 T1 ON t1.codtarif = man.codtarif AND getANLUNALUCRU() BETWEEN T1.ALStart AND T1.ALStop
                              LEFT  JOIN ngest ng ON ng.codgest = pg.codgest
                            WHERE
                              man.codprodcomp = v_rec1.codprodcomp
                              and pg.codprodgest = v_rec.codprodgest)
              LOOP
                valman := valman + v_tmp.valoare;
                IF NOT (current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
                    and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2)
                THEN
                  regie := regie + v_tmp.valoare * v_tmp.coefcheltman;
                END IF;
              END LOOP;

              FOR v_tmp IN (SELECT mat.codobiect, mat.cant, COALESCE (mat.tip, 3) TIP
                            FROM prodmat          mat
                              INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                              LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                            WHERE
                              mat.codprodcomp = v_rec1.codprodcomp
                              and pg.codprodgest = v_rec.codprodgest
                              and COALESCE (mat.tip, 3) &lt; 3)
              LOOP
                valman := valman + v_tmp.cant / v_Rec1.cant * (SELECT PKG_PRODCOMP_GetValoareMan.WME_RESULT FROM PKG_PRODCOMP_GetValoareMan (NULL,v_tmp.codobiect, TipPret));
              END LOOP;

              FOR v_tmp IN (SELECT mat.codobiect, COALESCE (pg.coefmat, COALESCE (ng.coefcheltmat, 0)) COEFCHELTMAT, mat.cant, mat.pret, COALESCE (mat.tip, 3) TIP
                            FROM prodmat          mat
                              INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                              LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                            WHERE
                              mat.codprodcomp = v_rec1.codprodcomp
                              and pg.codprodgest = v_rec.codprodgest)
              LOOP
                IF v_tmp.tip IN (3, 5) THEN
                  valmat := valmat + v_tmp.cant * (SELECT PKG_PRODCOMP_GetPretFromStoc.WME_RESULT FROM PKG_PRODCOMP_GetPretFromStoc (NULL,v_tmp.codobiect));
                  IF NOT (current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
                      and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2)
                  THEN
                    regie := regie + v_tmp.cant / v_Rec1.cant * (SELECT PKG_PRODCOMP_GetPretFromStoc.WME_RESULT FROM PKG_PRODCOMP_GetPretFromStoc (NULL,v_tmp.codobiect)) * v_tmp.coefcheltmat;
                  END IF;
                ELSE
                  valmat := valmat + v_tmp.cant * (SELECT pkg_prodcomp_GetValoareMat.WME_RESULT FROM pkg_prodcomp_GetValoareMat (NULL,v_tmp.codobiect, TipPret));
                END IF;
              END LOOP;

              FOR v_tmp IN (SELECT mat.codobiect, mat.cant, COALESCE (mat.tip, 3) TIP
                            FROM prodmat          mat
                              INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                              LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                            WHERE
                              mat.codprodcomp = v_rec1.codprodcomp
                              and pg.codprodgest = v_rec.codprodgest
                              and COALESCE (mat.tip, 3) &lt; 3)
              LOOP
                regie := regie + v_tmp.cant / v_Rec1.cant * (SELECT pkg_prodcomp_GetRegie.WME_RESULT FROM pkg_prodcomp_GetRegie (NULL,v_tmp.codobiect, TipPret));
              END LOOP;

              ValMat := ValMat / v_Rec1.Cant;
              IF current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
                and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2 THEN
                regie := regie + v_rec1.coefindirecte;
              END IF;
              vpret := vpret + valmat + valman + regie;
            END LOOP;
          ELSE
            valmat := 0;
            FOR v_rec IN (SELECT codprodgest FROM prodgest WHERE codprodcomp = v_Rec1.codprodcomp) LOOP
              FOR v_tmp IN (SELECT mat.codobiect, COALESCE (pg.coefmat, COALESCE (ng.coefcheltmat, 0)) COEFCHELTMAT, mat.cant, mat.pret, COALESCE (mat.tip, 3)                                                               TIP
                            FROM prodmat          mat
                              INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                              LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                            WHERE
                              mat.codprodcomp = v_rec1.codprodcomp
                              and pg.codprodgest = v_rec.codprodgest)
              LOOP
                IF v_tmp.tip IN (3, 5) THEN
                  valmat := valmat + v_tmp.cant * (SELECT PKG_PRODCOMP_GetPretFromStoc.WME_RESULT FROM PKG_PRODCOMP_GetPretFromStoc (NULL,v_tmp.codobiect));
                ELSE
                  valmat := valmat + v_tmp.cant * (SELECT pkg_prodcomp_GetValoareMat.WME_RESULT FROM pkg_prodcomp_GetValoareMat (NULL,v_tmp.codobiect, TipPret));
                END IF;
              END LOOP;
              ValMat := ValMat / v_Rec1.Cant;
              vpret  := vpret  + valmat;
            END LOOP;
          END IF;
          IF vPret &lt; PretMin THEN
            PretMin := vPret;
          END IF;
        END LOOP;

        UPDATE tmp_manevra_compusi SET pret = PretMin WHERE codobiect = aCodObiect;

        WME_Result := PretMin;
        RETURN;
      ELSE
        FOR v_rec1 IN ( SELECT pc.codprodcomp, pc.cant, COALESCE (pc.tippret, COALESCE (Tmp.tippret, 1)) TIPPRET, COALESCE (pc.coefindirecte, 0) COEFINDIRECTE
                        FROM prodcomp                 pc
                          INNER JOIN prodcomp         pcc ON pc.codprodcomp = pcc.codprodcomp
                          INNER JOIN tmp_nartobj_luna tmp ON pc.codobiect = tmp.codobiect
                        WHERE
                          pc.codobiect = aCodObiect)
        LOOP
          IF v_rec1.tippret = 1 THEN
            valmat := 0;
            valman := 0;
            regie  := 0;

            FOR v_rec IN (SELECT codprodgest FROM prodgest WHERE codprodcomp = v_Rec1.codprodcomp) LOOP
              FOR v_tmp IN (SELECT COALESCE (pg.coefman, COALESCE (ng.coefcheltman, 0)) COEFCHELTMAN,
                                   round ( ( (t1.tarif * man.tu) / 60 / CASE WHEN COALESCE (man.bps, 1) = 0 THEN 1 ELSE COALESCE (man.bps, 1) END) ::numeric, 7)  VALOARE
                            FROM prodman man
                              INNER JOIN prodgest pg ON man.codprodgest = pg.codprodgest
                              LEFT  JOIN TARIFEMAN1 T1 ON t1.codtarif = man.codtarif AND getANLUNALUCRU() BETWEEN T1.ALStart AND T1.ALStop
                              LEFT  JOIN ngest ng ON ng.codgest = pg.codgest
                            WHERE
                              man.codprodcomp = v_rec1.codprodcomp
                              and pg.codprodgest = v_rec.codprodgest)
              LOOP
                valman := valman + v_tmp.valoare;
                IF NOT (current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
                    and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2)
                THEN
                  regie := regie + v_tmp.valoare * v_tmp.coefcheltman;
                END IF;
              END LOOP;

              FOR v_tmp IN (SELECT mat.codobiect, mat.cant, COALESCE (mat.tip, 3) TIP
                            FROM prodmat          mat
                              INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                              LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                            WHERE
                              mat.codprodcomp = v_rec1.codprodcomp
                              and pg.codprodgest = v_rec.codprodgest
                              and COALESCE (mat.tip, 3) &lt; 3)
              LOOP
                valman := valman + v_tmp.cant / v_rec1.cant * (SELECT PKG_PRODCOMP_GetValoareMan.WME_RESULT FROM PKG_PRODCOMP_GetValoareMan (NULL,v_tmp.codobiect, TipPret));
              END LOOP;

              FOR v_tmp IN (SELECT mat.codobiect, COALESCE (pg.coefmat, COALESCE (ng.coefcheltmat, 0)) COEFCHELTMAT, mat.cant, mat.pret, COALESCE (mat.tip, 3)                                                               TIP
                            FROM prodmat          mat
                              INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                              LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                            WHERE
                              mat.codprodcomp = v_rec1.codprodcomp
                              and pg.codprodgest = v_rec.codprodgest)
              LOOP
                IF v_tmp.tip IN (3, 5) THEN
                  valmat := valmat + v_tmp.cant * (SELECT PKG_PRODCOMP_GetPretFromStoc.WME_RESULT FROM PKG_PRODCOMP_GetPretFromStoc (NULL,v_tmp.codobiect));
                  IF NOT (current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
                      and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2)
                  THEN
                    regie := regie + v_tmp.cant / v_Rec1.cant * (SELECT PKG_PRODCOMP_GetPretFromStoc.WME_RESULT FROM PKG_PRODCOMP_GetPretFromStoc (NULL,v_tmp.codobiect)) * v_tmp.coefcheltmat;
                  END IF;
                ELSE
                  valmat := valmat + v_tmp.cant * (SELECT pkg_prodcomp_GetValoareMat.WME_RESULT FROM pkg_prodcomp_GetValoareMat (NULL,v_tmp.codobiect, TipPret));
                END IF;
              END LOOP;

              FOR v_tmp IN (SELECT mat.codobiect, mat.cant, COALESCE (mat.tip, 3) TIP
                            FROM prodmat          mat
                              INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                              LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                            WHERE
                              mat.codprodcomp = v_rec1.codprodcomp
                              and pg.codprodgest = v_rec.codprodgest
                              and COALESCE (mat.tip, 3) &lt; 3)
              LOOP
                regie := regie + v_tmp.cant / v_Rec1.cant * (SELECT pkg_prodcomp_GetRegie.WME_RESULT FROM pkg_prodcomp_GetRegie (NULL,v_tmp.codobiect, TipPret));
              END LOOP;

              ValMat := ValMat / v_Rec1.Cant;
              IF current_setting ('PKG_PRODCOMP.KTipCoefIndirecte', true) ::numeric = 3
                and current_setting ('PKG_PRODCOMP.KRegieAntecalcul', true) ::numeric = 2 THEN
                regie := regie + v_rec1.coefindirecte;
              END IF;
              vpret := vpret + valmat + valman + regie;
            END LOOP;
          ELSE
            valmat := 0;
            FOR v_rec IN (SELECT codprodgest FROM prodgest WHERE codprodcomp = v_Rec1.codprodcomp) LOOP
              FOR v_tmp IN (SELECT mat.codobiect, COALESCE (pg.coefmat, COALESCE (ng.coefcheltmat, 0)) COEFCHELTMAT, mat.cant, mat.pret, COALESCE (mat.tip, 3)                                                               TIP
                            FROM prodmat          mat
                              INNER JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                              LEFT  JOIN ngest    ng ON ng.codgest = pg.codgest
                            WHERE
                              mat.codprodcomp = v_rec1.codprodcomp
                              and pg.codprodgest = v_rec.codprodgest)
              LOOP
                IF v_tmp.tip IN (3, 5) THEN
                  valmat := valmat + v_tmp.cant * (SELECT PKG_PRODCOMP_GetPretFromStoc.WME_RESULT FROM PKG_PRODCOMP_GetPretFromStoc (NULL,v_tmp.codobiect));
                ELSE
                  valmat := valmat + v_tmp.cant * (SELECT pkg_prodcomp_GetValoareMat.WME_RESULT FROM pkg_prodcomp_GetValoareMat (NULL,v_tmp.codobiect, TipPret));
                END IF;
              END LOOP;
              ValMat := ValMat / v_Rec1.Cant;
              vpret  := vpret  + valmat;
            END LOOP;
          END IF;
        END LOOP;

        UPDATE tmp_manevra_compusi SET pret = vPret / aCount WHERE codobiect = aCodObiect;

        WME_Result := vPret / aCount;
        RETURN;
      END IF;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getpreturi</obj_name>
  <obj_hashval>bcb919b7bb1afff1b5a8614790151af8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getpreturi(anlunadela numeric, anlunapanala numeric, acodprodcomp numeric, amarja numeric, adinmanevra boolean DEFAULT false)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  V_REC RECORD;
  V_TMP RECORD;
  TipPret     numeric;
  RetGenerica numeric;
BEGIN
  --Florin 23.05.2023 - sinc. Oracle
  --Florin 24.11.2022 - sinc. Oracle
  --Florin 17.06.2022 - fixat 54637
  --Bogdan 02.05.2022 54056 : Antecalcul - afisare Codintern/CodExtern Materiale
  RetGenerica := 0;
  if aCodProdComp &gt; 0 then
    select coalesce (generic, 0) INTO RetGenerica from prodcomp WHERE codprodcomp = aCodProdComp;
  end if;

  perform PKG_PRODCOMP_ArmeazaTMPs (aCodProdComp, aDinManevra);
  TipPret := (fnc_GetValConstantaLucru ('TipEvaluarePret')) ::numeric;
  if TipPret &gt; 3 or TipPret &lt; 1 then
    TipPret := 2;
  end if;

  DELETE from tmp_manevra_preturi;
  DELETE from tmp_manevra_preturi_Detalii;
  if current_setting ('PKG_PRODCOMP.vModGenerice', true) ::numeric = 1 THEN
     if RetGenerica = 1 then
      insert into tmp_manevra_preturi_Detalii (pret, codobiect, codnirstoc, cant, dataachiz, codarticol, codatribut, codobiectgeneric, obj_codextern, obj_codintern)
      select distinct a.PU, a.CodObiect, a.codnirstoc, a.cantnir,
             a.dataachiz, a.codarticol, a.codatribut,
             (select pkg_nom_articol_getcodobiectgeneric.WME_RESULT from pkg_nom_articol_getcodobiectgeneric (null, a.CodArticol)),
             a.obj_codextern, a.obj_codintern
      from
        (select distinct nvl(NS_OK.PU, 0) pu, mat.codobiect, ns_ok.codnirstoc, nvl(ns_ok.cantnir,0) cantnir, ns_ok.dataachiz, obj.codarticol, coalesce(mat.codatribut,0) codatribut,
        obj.codextern as obj_codextern, obj.codintern as obj_codintern
            from prodmat                mat
              inner join prodcomp       pc  on mat.codprodcomp = pc.codprodcomp
              inner join prodcomp_clona pcc on pcc.codprodcomp = pc.codprodcomp
              inner join nartobj        obj on mat.codobiect = obj.codobiect
              left  join (select coalesce (NS.pret, 0) - coalesce (NS.adaos, 0) PU, o.CodArticol, ns.codnirstoc, ns.cantnir, ns.dataachiz, ns.codobiect
                          from nirstoc           ns
                            inner join nartobj o on o.codobiect = ns.codobiect
                            inner join nir       on nir.codnir = ns.codnir
                            inner join intrari i on nir.codintr = i.codintr
                            left join dvi        on dvi.codintr = i.codintr
                            left join (select * from ngest WHERE coalesce (tip, 0) &lt;&gt; 4) g on nir.gest = g.codgest
                          where
                            (extract (year from NS.dataachiz) * 12 + extract (month from NS.dataachiz) &gt;= AnLunaDeLa
                              and extract (year from NS.dataachiz) * 12 + extract (month from NS.dataachiz) &lt;= AnLunaPanaLa)
                            and coalesce (ns.pret, 0) - coalesce (ns.adaos, 0) &lt;&gt; 0
                            and ns.cantnir &lt;&gt; 0
                            and coalesce (dvi.tipimport, 0) = 0
                            and i.anulat = 0 and i.operat = 1 and nir.operat = 1
                         ) NS_OK on obj.codarticol = NS_OK.codarticol
            where
              pc.cant &lt;&gt; 0
              and coalesce (pc.inactiv, 0) = 0
              and coalesce (pc.invizibila, 0) = 0
              and mat.Tip in (3, 5)
              and (aCodProdComp = 0 or pc.codprodcomp = aCodProdComp)
            union ALL
              select distinct nvl(NS_OK.PU,0) pu, mat.codobiect, ns_ok.codnirstoc, nvl(ns_ok.cantnir,0) cantnir, ns_ok.dataachiz, obj.codarticol, coalesce(mat.codatribut,0) codatribut,
              obj.codextern as obj_codextern, obj.codintern as obj_codintern
            from prodmat                mat
              inner join prodcomp       pc  on mat.codprodcomp = pc.codprodcomp
              inner join prodcomp_clona pcc on pcc.codprodcomp = pc.codprodcomp
              inner join nartobj        obj on mat.codobiect = obj.codobiect
              left  join (select coalesce (NS.pret, 0) - coalesce (NS.adaos, 0) PU, NS.CodObiect, ns.codnirstoc, ns.cantnir, ns.dataachiz, o.codarticol
                          from nirstoc           ns
                            inner join nartobj o on ns.codobiect = o.codobiect
                            inner join nir       on nir.codnir = ns.codnir
                            inner join intrari i on nir.codintr = i.codintr
                            left join dvi        on dvi.codintr = i.codintr
                            left join (select * from ngest WHERE coalesce (tip, 0) &lt;&gt; 4) g on nir.gest = g.codgest
                          where
                            (extract (year from NS.dataachiz) * 12 + extract (month from NS.dataachiz) &gt;= AnLunaDeLa
                              and extract (year from NS.dataachiz) * 12 + extract (month from NS.dataachiz) &lt;= AnLunaPanaLa)
                            and coalesce (ns.pret, 0) - coalesce (ns.adaos, 0) &lt;&gt; 0
                            and ns.cantnir &lt;&gt; 0
                            and coalesce (dvi.tipimport, 0) = 0
                            and i.anulat = 0 and i.operat = 1 and nir.operat = 1
                         ) NS_OK on obj.codarticol = NS_OK.codarticol
            where
              pc.cant &lt;&gt; 0
              and coalesce (pc.inactiv, 0) = 0
              and coalesce (pc.invizibila, 0) = 0
              and mat.Tip &lt; 3
              and (aCodProdComp = 0 or pc.codprodcomp = aCodProdComp)
              and not exists (select codprodcomp from prodcomp WHERE codobiect = mat.codobiect)
            union ALL
              select distinct nvl(NS_OK.PU,0) pu, pc.codobiect, ns_ok.codnirstoc, nvl(ns_ok.cantnir,0) cantnir, ns_ok.dataachiz, obj.codarticol, 0 codatribut,
              obj.codextern as obj_codextern, obj.codintern as obj_codintern
            from prodcomp               pc
              inner join prodcomp_clona pcc on pcc.codprodcomp = pc.codprodcomp
              inner join nartobj        obj on pc.codobiect = obj.codobiect
              left  join (select coalesce (NS.pret, 0) - coalesce (NS.adaos, 0) PU, NS.CodObiect, ns.codnirstoc, ns.cantnir, ns.dataachiz, o.codarticol
                          from nirstoc           ns
                            inner join nartobj o on ns.codobiect = o.codobiect
                            inner join nir       on nir.codnir = ns.codnir
                            inner join intrari i on nir.codintr = i.codintr
                            left join dvi        on dvi.codintr = i.codintr
                            left join (select * from ngest WHERE coalesce (tip, 0) &lt;&gt; 4) g on nir.gest = g.codgest
                          where
                            (extract (year from NS.dataachiz) * 12 + extract (month from NS.dataachiz) &gt;= AnLunaDeLa
                              and extract (year from NS.dataachiz) * 12 + extract (month from NS.dataachiz) &lt;= AnLunaPanaLa)
                            and coalesce (ns.pret, 0) - coalesce (ns.adaos, 0) &lt;&gt; 0
                            and ns.cantnir &lt;&gt; 0
                            and coalesce (dvi.tipimport, 0) = 0
                            and i.anulat = 0 and i.operat = 1 and nir.operat = 1
                         ) NS_OK on obj.codarticol = NS_OK.codarticol
            where
              pc.cant &lt;&gt; 0
              and coalesce (pc.inactiv, 0) = 0
              and coalesce (pc.invizibila, 0) = 0
              and pc.tipreteta = 2
              and (aCodProdComp = 0
                or pc.codprodcomp = aCodProdComp)) a;

    ELSE
      insert  into tmp_manevra_preturi_Detalii (pret, codobiect, codnirstoc, cant, dataachiz, codobiectgeneric, codarticol, obj_codextern, obj_codintern)
      select  distinct a.PU, a.CodObiect, a.codnirstoc, a.cantnir, a.dataachiz,
             (select pkg_nom_articol_getcodobiectgeneric.WME_RESULT from pkg_nom_articol_getcodobiectgeneric (null, a.CodArticol)) , a.codarticol,
                   a.obj_codextern, a.obj_codintern
      from
        (select distinct nvl(NS_OK.PU, 0) pu,mat.codobiect, ns_ok.codnirstoc, nvl(ns_ok.cantnir,0) cantnir, ns_ok.dataachiz, obj.codarticol,
        obj.codextern as obj_codextern, obj.codintern as obj_codintern
            from prodmat                mat
              inner join prodcomp       pc  on mat.codprodcomp = pc.codprodcomp
              inner join prodcomp_clona pcc on pcc.codprodcomp = pc.codprodcomp
              inner join nartobj        obj on mat.codobiect = obj.codobiect
              left  join (select coalesce (NS.pret, 0) - coalesce (NS.adaos, 0) PU, NS.CodObiect, ns.codnirstoc, ns.cantnir, ns.dataachiz, o.codarticol
                          from nirstoc           ns
                            inner join nartobj o on o.codobiect = ns.codobiect
                            inner join nir       on nir.codnir = ns.codnir
                            inner join intrari i on nir.codintr = i.codintr
                            left join dvi        on dvi.codintr = i.codintr
                            left join (select * from ngest WHERE coalesce (tip, 0) &lt;&gt; 4) g on nir.gest = g.codgest
                          where
                            (extract (year from NS.dataachiz) * 12 + extract (month from NS.dataachiz) &gt;= AnLunaDeLa
                              and extract (year from NS.dataachiz) * 12 + extract (month from NS.dataachiz) &lt;= AnLunaPanaLa)
                            and coalesce (ns.pret, 0) - coalesce (ns.adaos, 0) &lt;&gt; 0
                            and ns.cantnir &lt;&gt; 0
                            and coalesce (dvi.tipimport, 0) = 0
                            and i.anulat = 0 and i.operat = 1 and nir.operat = 1
                         ) NS_OK on obj.codarticol = NS_OK.codarticol
            where
              pc.cant &lt;&gt; 0
              and coalesce (pc.inactiv, 0) = 0
              and coalesce (pc.invizibila, 0) = 0
              and mat.Tip in (3, 5)
              and (aCodProdComp = 0 or pc.codprodcomp = aCodProdComp)
            union ALL
              select distinct nvl(NS_OK.PU,0) pu, mat.codobiect, ns_ok.codnirstoc, nvl(ns_ok.cantnir,0) cantnir, ns_ok.dataachiz, obj.codarticol,
              obj.codextern as obj_codextern, obj.codintern as obj_codintern
            from prodmat                                                            mat
              inner join prodcomp                                                 pc  on mat.codprodcomp = pc.codprodcomp
              inner join prodcomp_clona                                           pcc on pcc.codprodcomp = pc.codprodcomp
              inner join nartobj                                                  obj on mat.codobiect = obj.codobiect
              left  join (select coalesce (NS.pret, 0) - coalesce (NS.adaos, 0) PU, NS.CodObiect, ns.codnirstoc, ns.cantnir, ns.dataachiz, o.codarticol
                          from nirstoc           ns
                            inner join nartobj o on o.codobiect = ns.codobiect
                            inner join nir       on nir.codnir = ns.codnir
                            inner join intrari i on nir.codintr = i.codintr
                            left join dvi        on dvi.codintr = i.codintr
                            left join (select * from ngest WHERE coalesce (tip, 0) &lt;&gt; 4) g on nir.gest = g.codgest
                          where
                            (extract (year from NS.dataachiz) * 12 + extract (month from NS.dataachiz) &gt;= AnLunaDeLa
                              and extract (year from NS.dataachiz) * 12 + extract (month from NS.dataachiz) &lt;= AnLunaPanaLa)
                            and coalesce (ns.pret, 0) - coalesce (ns.adaos, 0) &lt;&gt; 0
                            and ns.cantnir &lt;&gt; 0
                            and coalesce (dvi.tipimport, 0) = 0
                            and i.anulat = 0 and i.operat = 1 and nir.operat = 1
                         ) NS_OK on obj.codarticol = NS_OK.codarticol
            where
              pc.cant &lt;&gt; 0
              and coalesce (pc.inactiv, 0) = 0
              and coalesce (pc.invizibila, 0) = 0
              and mat.Tip &lt; 3
              and (aCodProdComp = 0 or pc.codprodcomp = aCodProdComp)
              and not exists (select codprodcomp from prodcomp WHERE codobiect = mat.codobiect)
            union ALL
              select distinct nvl(NS_OK.PU,0) pu, pc.codobiect, ns_ok.codnirstoc, nvl(ns_ok.cantnir,0) cantnir, ns_ok.dataachiz, obj.codarticol,
              obj.codextern as obj_codextern, obj.codintern as obj_codintern
            from prodcomp               pc
              inner join prodcomp_clona pcc on pcc.codprodcomp = pc.codprodcomp
              inner join nartobj        obj on pc.codobiect = obj.codobiect
              left  join (select coalesce (NS.pret, 0) - coalesce (NS.adaos, 0) PU, NS.CodObiect, ns.codnirstoc, ns.cantnir, ns.dataachiz, o.codarticol
                          from nirstoc           ns
                            inner join nartobj o on ns.codobiect = o.codobiect
                            inner join nir       on nir.codnir = ns.codnir
                            inner join intrari i on nir.codintr = i.codintr
                            left join dvi        on dvi.codintr = i.codintr
                            left join (select * from ngest WHERE coalesce (tip, 0) &lt;&gt; 4) g on nir.gest = g.codgest
                          where
                            (extract (year from NS.dataachiz) * 12 + extract (month from NS.dataachiz) &gt;= AnLunaDeLa
                              and extract (year from NS.dataachiz) * 12 + extract (month from NS.dataachiz) &lt;= AnLunaPanaLa)
                            and coalesce (ns.pret, 0) - coalesce (ns.adaos, 0) &lt;&gt; 0
                            and ns.cantnir &lt;&gt; 0
                            and coalesce (dvi.tipimport, 0) = 0
                            and i.anulat = 0 and i.operat = 1 and nir.operat = 1
                         ) NS_OK on obj.codarticol = NS_OK.codarticol
            where
              pc.cant &lt;&gt; 0
              and coalesce (pc.inactiv, 0) = 0
              and coalesce (pc.invizibila, 0) = 0
              and pc.tipreteta = 2
              and (aCodProdComp = 0 or pc.codprodcomp = aCodProdComp)) a;
    end if;
  else
    if RetGenerica = 1 then
      insert  into tmp_manevra_preturi_Detalii (pret, codobiect, codnirstoc, cant, dataachiz, codarticol, codatribut, obj_codextern, obj_codintern)
      select  distinct a.PU, a.CodObiect, a.codnirstoc, a.cantnir, a.dataachiz, a.codarticol, a.codatribut, a.obj_codextern, a.obj_codintern
      from
        (select distinct nvl(NS_OK.PU, 0) pu, Mat.codobiect, ns_ok.codnirstoc, nvl(ns_ok.cantnir,0) cantnir, ns_ok.dataachiz, obj.codarticol, coalesce(mat.codatribut,0) codatribut,
        obj.codextern as obj_codextern, obj.codintern as obj_codintern
            from prodmat                                                            mat
              inner join prodcomp                                                 pc  on mat.codprodcomp = pc.codprodcomp
              inner join prodcomp_clona                                           pcc on pcc.codprodcomp = pc.codprodcomp
              inner join nartobj                                                  obj on mat.codobiect = obj.codobiect
              left  join (select coalesce (NS.pret, 0) - coalesce (NS.adaos, 0) PU, NS.CodObiect, ns.codnirstoc, ns.cantnir, ns.dataachiz
                          from nirstoc ns
                            inner join nir       on nir.codnir = ns.codnir
                            inner join intrari i on nir.codintr = i.codintr
                            left join dvi        on dvi.codintr = i.codintr
                            left join (select * from ngest WHERE coalesce (tip, 0) &lt;&gt; 4) g on nir.gest = g.codgest
                          where
                            (extract (year from NS.dataachiz) * 12 + extract (month from NS.dataachiz) &gt;= AnLunaDeLa
                              and extract (year from NS.dataachiz) * 12 + extract (month from NS.dataachiz) &lt;= AnLunaPanaLa)
                            and coalesce (ns.pret, 0) - coalesce (ns.adaos, 0) &lt;&gt; 0
                            and ns.cantnir &lt;&gt; 0
                            and coalesce (dvi.tipimport, 0) = 0
                            and i.anulat = 0 and i.operat = 1 and nir.operat = 1
                         ) NS_OK on mat.codobiect = NS_OK.codobiect
            where
              pc.cant &lt;&gt; 0
              and coalesce (pc.inactiv, 0) = 0
              and coalesce (pc.invizibila, 0) = 0
              and mat.Tip in (3, 5)
              and (aCodProdComp = 0 or pc.codprodcomp = aCodProdComp)
            union ALL
              select distinct nvl(NS_OK.PU,0) pu, Mat.codobiect, ns_ok.codnirstoc, nvl(ns_ok.cantnir,0) cantnir, ns_ok.dataachiz, obj.codarticol, coalesce(mat.codatribut,0) codatribut,
              obj.codextern as obj_codextern, obj.codintern as obj_codintern
            from prodmat                mat
              inner join prodcomp       pc  on mat.codprodcomp = pc.codprodcomp
              inner join prodcomp_clona pcc on pcc.codprodcomp = pc.codprodcomp
              inner join nartobj        obj on mat.codobiect = obj.codobiect
              left  join (select coalesce (NS.pret, 0) - coalesce (NS.adaos, 0) PU, NS.CodObiect, ns.codnirstoc, ns.cantnir, ns.dataachiz
                          from nirstoc ns
                            inner join nir       on nir.codnir = ns.codnir
                            inner join intrari i on nir.codintr = i.codintr
                            left join dvi        on dvi.codintr = i.codintr
                            left join (select * from ngest WHERE coalesce (tip, 0) &lt;&gt; 4) g on nir.gest = g.codgest
                          where
                            (extract (year from NS.dataachiz) * 12 + extract (month from NS.dataachiz) &gt;= AnLunaDeLa
                              and extract (year from NS.dataachiz) * 12 + extract (month from NS.dataachiz) &lt;= AnLunaPanaLa)
                            and coalesce (ns.pret, 0) - coalesce (ns.adaos, 0) &lt;&gt; 0
                            and ns.cantnir &lt;&gt; 0
                            and coalesce (dvi.tipimport, 0) = 0
                            and i.anulat = 0 and i.operat = 1 and nir.operat = 1
                         ) NS_OK on mat.codobiect = NS_OK.codobiect
            where
              pc.cant &lt;&gt; 0
              and coalesce (pc.inactiv, 0) = 0
              and coalesce (pc.invizibila, 0) = 0
              and mat.Tip &lt; 3
              and (aCodProdComp = 0 or pc.codprodcomp = aCodProdComp)
              and not exists (select codprodcomp from prodcomp WHERE codobiect = mat.codobiect)
            union ALL
              select distinct nvl(NS_OK.PU,0) pu, pc.codobiect, ns_ok.codnirstoc, nvl(ns_ok.cantnir,0) cantnir, ns_ok.dataachiz, obj.codarticol, 0 codatribut,
              obj.codextern as obj_codextern, obj.codintern as obj_codintern
            from prodcomp               pc
              inner join prodcomp_clona pcc on pcc.codprodcomp = pc.codprodcomp
              inner join nartobj        obj on pc.codobiect = obj.codobiect
              left  join (select coalesce (NS.pret, 0) - coalesce (NS.adaos, 0) PU, NS.CodObiect, ns.codnirstoc, ns.cantnir, ns.dataachiz, o.codarticol
                          from nirstoc           ns
                            inner join nartobj o on ns.codobiect = o.codobiect
                            inner join nir       on nir.codnir = ns.codnir
                            inner join intrari i on nir.codintr = i.codintr
                            left join dvi        on dvi.codintr = i.codintr
                            left join (select * from ngest WHERE coalesce (tip, 0) &lt;&gt; 4) g on nir.gest = g.codgest
                          where
                            (extract (year from NS.dataachiz) * 12 + extract (month from NS.dataachiz) &gt;= AnLunaDeLa
                              and extract (year from NS.dataachiz) * 12 + extract (month from NS.dataachiz) &lt;= AnLunaPanaLa)
                            and coalesce (ns.pret, 0) - coalesce (ns.adaos, 0) &lt;&gt; 0
                            and ns.cantnir &lt;&gt; 0
                            and coalesce (dvi.tipimport, 0) = 0
                            and i.anulat = 0 and i.operat = 1 and nir.operat = 1
                         ) NS_OK on obj.codarticol = NS_OK.codarticol
            where
              pc.cant &lt;&gt; 0
              and coalesce (pc.inactiv, 0) = 0
              and coalesce (pc.invizibila, 0) = 0
              and pc.tipreteta = 2
              and (aCodProdComp = 0 or pc.codprodcomp = aCodProdComp)) a;
    else
      insert  into tmp_manevra_preturi_Detalii (pret, codobiect, codnirstoc, cant, dataachiz, codarticol, obj_codextern, obj_codintern)
      select  distinct a.PU, a.CodObiect, a.codnirstoc, a.cantnir, a.dataachiz, a.codarticol, a.obj_codextern, a.obj_codintern
      from
        (select distinct nvl(NS_OK.PU, 0) pu, Mat.codobiect, ns_ok.codnirstoc, nvl(ns_ok.cantnir,0) cantnir, ns_ok.dataachiz, obj.codarticol,
        obj.codextern as obj_codextern, obj.codintern as obj_codintern
            from prodmat                mat
              inner join prodcomp       pc  on mat.codprodcomp = pc.codprodcomp
              inner join prodcomp_clona pcc on pcc.codprodcomp = pc.codprodcomp
              inner join nartobj        obj on mat.codobiect = obj.codobiect
              left  join (select coalesce (NS.pret, 0) - coalesce (NS.adaos, 0) PU, NS.CodObiect, ns.codnirstoc, ns.cantnir, ns.dataachiz
                          from nirstoc ns
                            inner join nir       on nir.codnir = ns.codnir
                            inner join intrari i on nir.codintr = i.codintr
                            left join dvi        on dvi.codintr = i.codintr
                            left join (select * from ngest WHERE coalesce (tip, 0) &lt;&gt; 4) g on nir.gest = g.codgest
                          where
                            (extract (year from NS.dataachiz) * 12 + extract (month from NS.dataachiz) &gt;= AnLunaDeLa
                              and extract (year from NS.dataachiz) * 12 + extract (month from NS.dataachiz) &lt;= AnLunaPanaLa)
                            and coalesce (ns.pret, 0) - coalesce (ns.adaos, 0) &lt;&gt; 0
                            and ns.cantnir &lt;&gt; 0
                            and coalesce (dvi.tipimport, 0) = 0
                            and i.anulat = 0 and i.operat = 1 and nir.operat = 1
                         ) NS_OK on mat.codobiect = NS_OK.codobiect
            where
              pc.cant &lt;&gt; 0
              and coalesce (pc.inactiv, 0) = 0
              and coalesce (pc.invizibila, 0) = 0
              and mat.Tip in (3, 5)
              and (aCodProdComp = 0 or pc.codprodcomp = aCodProdComp)
            union ALL
              select distinct nvl(NS_OK.PU,0) pu, Mat.codobiect, ns_ok.codnirstoc, nvl(ns_ok.cantnir,0) cantnir, ns_ok.dataachiz, obj.codarticol,
              obj.codextern as obj_codextern, obj.codintern as obj_codintern
            from prodmat                mat
              inner join prodcomp       pc  on mat.codprodcomp = pc.codprodcomp
              inner join prodcomp_clona pcc on pcc.codprodcomp = pc.codprodcomp
              inner join nartobj        obj on mat.codobiect = obj.codobiect
              left  join (select coalesce (NS.pret, 0) - coalesce (NS.adaos, 0) PU, NS.CodObiect, ns.codnirstoc, ns.cantnir, ns.dataachiz
                          from nirstoc ns
                            inner join nir       on nir.codnir = ns.codnir
                            inner join intrari i on nir.codintr = i.codintr
                            left join dvi        on dvi.codintr = i.codintr
                            left join (select * from ngest WHERE coalesce (tip, 0) &lt;&gt; 4) g on nir.gest = g.codgest
                          where
                            (extract (year from NS.dataachiz) * 12 + extract (month from NS.dataachiz) &gt;= AnLunaDeLa
                              and extract (year from NS.dataachiz) * 12 + extract (month from NS.dataachiz) &lt;= AnLunaPanaLa)
                            and coalesce (ns.pret, 0) - coalesce (ns.adaos, 0) &lt;&gt; 0
                            and ns.cantnir &lt;&gt; 0
                            and coalesce (dvi.tipimport, 0) = 0
                            and i.anulat = 0 and i.operat = 1 and nir.operat = 1
                         ) NS_OK on mat.codobiect = NS_OK.codobiect
            where
              pc.cant &lt;&gt; 0
              and coalesce (pc.inactiv, 0) = 0
              and coalesce (pc.invizibila, 0) = 0
              and mat.Tip &lt; 3
              and (aCodProdComp = 0 or pc.codprodcomp = aCodProdComp)
              and not exists (select codprodcomp from prodcomp WHERE codobiect = mat.codobiect)
            union all
              select distinct nvl(NS_OK.PU,0) pu, pc.codobiect, ns_ok.codnirstoc, nvl(ns_ok.cantnir,0) cantnir, ns_ok.dataachiz, obj.codarticol,
              obj.codextern as obj_codextern, obj.codintern as obj_codintern
            from prodcomp               pc
              inner join prodcomp_clona pcc on pcc.codprodcomp = pc.codprodcomp
              inner join nartobj        obj on pc.codobiect = obj.codobiect
              left  join (select coalesce (NS.pret, 0) - coalesce (NS.adaos, 0) PU, NS.CodObiect, ns.codnirstoc, ns.cantnir, ns.dataachiz, o.codarticol
                          from nirstoc           ns
                            inner join nartobj o on ns.codobiect = o.codobiect
                            inner join nir       on nir.codnir = ns.codnir
                            inner join intrari i on nir.codintr = i.codintr
                            left join dvi        on dvi.codintr = i.codintr
                            left join (select * from ngest WHERE coalesce (tip, 0) &lt;&gt; 4) g on nir.gest = g.codgest
                          where
                            (extract (year from NS.dataachiz) * 12 + extract (month from NS.dataachiz) &gt;= AnLunaDeLa
                              and extract (year from NS.dataachiz) * 12 + extract (month from NS.dataachiz) &lt;= AnLunaPanaLa)
                            and coalesce (ns.pret, 0) - coalesce (ns.adaos, 0) &lt;&gt; 0
                            and ns.cantnir &lt;&gt; 0
                            and coalesce (dvi.tipimport, 0) = 0
                            and i.anulat = 0 and i.operat = 1 and nir.operat = 1
                         ) NS_OK on obj.codarticol = NS_OK.codarticol
            where
              pc.cant &lt;&gt; 0
              and coalesce (pc.inactiv, 0) = 0
              and coalesce (pc.invizibila, 0) = 0
              and pc.tipreteta = 2
              and (aCodProdComp = 0 or pc.codprodcomp = aCodProdComp)) a;
    end if;
  end if;
  if current_setting ('PKG_PRODCOMP.vModGenerice', true) ::numeric &lt;&gt; 1 THEN
    if TipPret = 1 then
      insert  into tmp_manevra_preturi (codobiect, pret, denumire, DEN_CLASEAS, codarticol, codatribut, obj_codextern, obj_codintern)
      select tmp.codobiect, max (coalesce (tmp.pret, 0)) , obj.denumire, nclaseas.den_claseas, tmp.codarticol, tmp.codatribut,
                 obj.codextern as obj_codextern, obj.codintern as obj_codintern
      from tmp_manevra_preturi_Detalii tmp
        inner join nartobj           obj on tmp.codobiect = obj.codobiect
        inner join nart                  on obj.codarticol = nart.codarticol
        left join nclaseas               on nart.clasastatist = nclaseas.codclaseas
      group by
        tmp.codobiect, obj.denumire, nclaseas.den_claseas, tmp.codarticol,
        tmp.codatribut, obj.codextern, obj.codintern;
    else
      if TipPret = 3 then
        insert  into tmp_manevra_preturi (codobiect, pret, denumire, DEN_CLASEAS, codarticol, codatribut, obj_codextern, obj_codintern)
        select tmp.codobiect, min (coalesce (tmp.pret, 0)) , obj.denumire, nclaseas.den_claseas, tmp.codarticol, tmp.codatribut,
                    obj.codextern as obj_codextern, obj.codintern as obj_codintern
        from tmp_manevra_preturi_Detalii tmp
          inner join nartobj           obj on tmp.codobiect = obj.codobiect
          inner join nart                  on obj.codarticol = nart.codarticol
          left join nclaseas               on nart.clasastatist = nclaseas.codclaseas
        group by
          tmp.codobiect, obj.denumire, nclaseas.den_claseas, tmp.codarticol,
          tmp.codatribut, obj.codextern, obj.codintern;
      else
        insert  into tmp_manevra_preturi (codobiect, pret, denumire, DEN_CLASEAS, codarticol, codatribut, obj_codextern, obj_codintern)
        select codobiect,
               CASE when coalesce (cantitate, 0) = 0 then 0 else coalesce (valoare, 0) / coalesce (cantitate, 0) end ,
               denumire, den_claseas, codarticol, codatribut, obj_codextern, obj_codintern
        from (select tmp.codobiect, sum (tmp.cant * tmp.pret) VALOARE, sum (coalesce (tmp.cant, 0)) CANTITATE, obj.denumire,
                     nclaseas.den_claseas, tmp.codarticol, tmp.codatribut,
                                   obj.codextern as obj_codextern, obj.codintern as obj_codintern
            from tmp_manevra_preturi_Detalii tmp
              inner join nartobj           obj on tmp.codobiect = obj.codobiect
              inner join nart                  on obj.codarticol = nart.codarticol
              left join nclaseas               on nart.clasastatist = nclaseas.codclaseas
            group by
              tmp.codobiect, obj.denumire, nclaseas.den_claseas, tmp.codarticol,
              tmp.codatribut, obj.codextern, obj.codintern) A_PG;
      end if;
    end if;
  else
    if TipPret = 1 THEN
      insert  into tmp_manevra_preturi (codobiect, pret, denumire, DEN_CLASEAS, codarticol, codatribut, obj_codextern, obj_codintern)
      select mat.codobiect, max (coalesce (tmp.pret, 0)) , obj.denumire, nclaseas.den_claseas, tmp.codarticol, tmp.codatribut,
                   obj.codextern as obj_codextern, obj.codintern as obj_codintern
      from prodmat                             mat
        inner join prodcomp                    pc  on mat.codprodcomp = pc.codprodcomp
        inner join prodcomp_clona              pcc on pcc.codprodcomp = pc.codprodcomp
        inner join nartobj                     obj on mat.codobiect = obj.codobiect
        inner join tmp_manevra_preturi_Detalii tmp on tmp.codarticol = obj.codarticol
        inner join nart                            on obj.codarticol = nart.codarticol
        left join nclaseas                         on nart.clasastatist = nclaseas.codclaseas
      group by
        mat.codobiect, obj.denumire, nclaseas.den_claseas, tmp.codarticol,
        tmp.codatribut, obj.codextern, obj.codintern;
    else
      if TipPret = 3 then
        insert  into tmp_manevra_preturi (codobiect, pret, denumire, DEN_CLASEAS, codarticol, codatribut, obj_codextern, obj_codintern)
        select mat.codobiect, min (coalesce (tmp.pret, 0)) , obj.denumire, nclaseas.den_claseas, tmp.codarticol, tmp.codatribut,
                   obj.codextern as obj_codextern, obj.codintern as obj_codintern
        from prodmat                               mat
          inner join prodcomp                    pc  on mat.codprodcomp = pc.codprodcomp
          inner join prodcomp_clona              pcc on pcc.codprodcomp = pc.codprodcomp
          inner join nartobj                     obj on mat.codobiect = obj.codobiect
          inner join tmp_manevra_preturi_Detalii tmp on tmp.codarticol = obj.codarticol
          inner join nart                            on obj.codarticol = nart.codarticol
          left join nclaseas                         on nart.clasastatist = nclaseas.codclaseas
        GROUP by
          mat.codobiect, obj.denumire, nclaseas.den_claseas, tmp.codarticol,
          tmp.codatribut, obj.codextern, obj.codintern;
      ELSE
        insert  into tmp_manevra_preturi (codobiect, pret, denumire, DEN_CLASEAS, codarticol, codatribut, obj_codextern, obj_codintern)
        select codobiect,
               CASE when coalesce (cantitate, 0) = 0 then 0 else coalesce (valoare, 0) / coalesce (cantitate, 0) end ,
               denumire, den_claseas, codarticol, codatribut, obj_codextern, obj_codintern
        from (select mat.codobiect, sum (tmp.cant * tmp.pret) VALOARE, sum (coalesce (tmp.cant, 0)) CANTITATE, obj.denumire,
                     nclaseas.den_claseas, tmp.codarticol, tmp.codatribut, obj.codextern as obj_codextern, obj.codintern as obj_codintern
            from prodmat                             mat
              inner join prodcomp                    pc  on mat.codprodcomp = pc.codprodcomp
              inner join prodcomp_clona              pcc on pcc.codprodcomp = pc.codprodcomp
              inner join nartobj                     obj on mat.codobiect = obj.codobiect
              inner join tmp_manevra_preturi_Detalii tmp on tmp.codarticol = obj.codarticol
              inner join nart                            on obj.codarticol = nart.codarticol
              left join nclaseas                         on nart.clasastatist = nclaseas.codclaseas
            group by
              mat.codobiect, obj.denumire, nclaseas.den_claseas, tmp.codarticol,
              tmp.codatribut, obj.codextern, obj.codintern) B_PG;
      end if;
    end if;
  end if;

  DELETE from tmp_manevra_preturi_Detalii WHERE pret = 0;
  for v_Rec in (select tmp.codobiect, tmp.codarticol, tmp.pret, tmp.obj_codextern, tmp.obj_codintern
                from tmp_manevra_preturi tmp
                     left join (select count(*) NR, codarticol, codobiect from tmp_manevra_preturi_Detalii group BY codarticol, codobiect
                               ) Detalii on coalesce (Detalii.codobiect, 0) = coalesce (tmp.codobiect, 0) and coalesce (Detalii.codarticol, 0) = coalesce (tmp.codarticol, 0)
                where Detalii.nr = 0)
  loop
    insert  into tmp_manevra_preturi_Detalii (codobiect, codarticol, pret, obj_codextern, obj_codintern)
    values (v_rec.codobiect, v_rec.codarticol, v_rec.pret, v_rec.obj_codextern, v_rec.obj_codintern);
  end loop;

  for v_rec in (select  distinct codobiect from tmp_manevra_preturi_Detalii) loop
    for v_tmp in (select a.*, row_number() over() RowNum
                  from (select tmp.codobiect, tmp.pret, tmp.codnirstoc, tmp.ordine
                        from tmp_manevra_preturi_Detalii tmp left join nirstoc ns on tmp.codnirstoc = ns.codnirstoc
                        where tmp.codobiect = v_Rec.Codobiect
                        order BY ns.dataachiz DESC
                       ) a
                 )
    loop
      update tmp_manevra_preturi_Detalii set ordine = v_tmp.RowNum WHERE codnirstoc = v_tmp.codnirstoc and codobiect = v_rec.codobiect;
    end loop;
  end loop;

  perform PKG_PRODCOMP_SeteazaStare (aMarja);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodnet_sp_postrecords</obj_name>
  <obj_hashval>ad90fb1215cbb5c729ed10cdaed45815</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodnet_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  V_REC_SUB RECORD;
  VcOD      numeric;
  NR        numeric;
begin
  IF  Operation = 0 THEN
    SELECT codprodnet INTO RecId FROM TMP_prodnet;

    UPDATE prodnet
    SET
    (An, Luna, Obs, Tip, Subunitatea, CodGest, CodCentru) = (SELECT An, Luna, Obs, Tip, Subunitatea, CodGest, CodCentru FROM TMP_prodnet)
    WHERE
     codprodnet = RecId;

    DELETE FROM PRODNET1 WHERE CodPRODNET = RecID AND CodPRODNET1 NOT IN (SELECT CodPRODNET1 FROM TMP_PRODNET1);

    FOR v_rec IN (SELECT * FROM TMP_PRODNET1) LOOP
      IF  COALESCE( v_rec.CodPRODNET1, 0) &gt; 0 THEN
        UPDATE PRODNET1
        SET
        Tip           = V_REC.Tip,
        coddoc1       = V_REC.CODDOC1,
        explicatii    = V_REC.EXPLICATII,
        valmat        = V_REC.VALMAT,
        valman        = V_rEC.Valman,
        CodGest       = v_rec.CodGest,
        CODCENTRU     = v_rec.CODCENTRU,
        CODANALIZANOD = V_REC.CODANALIZANOD,
        CODCMDPRODMAT = V_REC.CODCMDPRODMAT,
        PRET          = V_REC.PRET,
        DIFCANT       = V_REC.DIFCANT,
        CANTREAL      = V_REC.CANTREAL,
        codies1       = v_rec.codies1
        WHERE
         CODPRODNET1 = v_rec.CODPRODNET1;
    ELSE
      SELECT NEXTVAL('SEQ_PRODNET1_CODPRODNET1') INTO vCod;

      INSERT INTO PRODNET1(codprodnet1, codprodnet, Tip, coddoc1, explicatii, valmat, valman, CodGest, CODCENTRU, CODANALIZANOD, CODCMDPRODMAT, CANTREAL, DIFCANT, PRET, codies1)
      VALUES(vCod, RecId, V_REC.Tip, V_REC.coddoc1, V_REC.explicatii, V_REC.valmat, V_REC.valman, v_rec.CodGest, v_rec.CODCENTRU, v_rec.CODANALIZANOD, v_rec.CODCMDPRODMAT, v_rec.CANTREAL, v_rec.DIFCANT, v_rec.PRET, v_rec.codies1);
    END IF;
    END LOOP;

    DELETE FROM JURNAl1 WHERE TIPDOC = 71 AND  CODDOC = RECID AND CODJURNAL1 NOT IN (SELECT CODJURNAL1 FROM TMP_JURNAl1);

    FOR V_REC IN (SELECT * FROM TMP_JURNAL1) LOOP
      IF  V_REC.CODJURNAL1 &gt; 0 THEN
        UPDATE JURNAL1
        SET
        CODDOC        = V_REC.CODDOC,
        TIPDOC        = V_REC.TIPDOC,
        INDEXLOCAL    = V_REC.INDEXLOCAL,
        CODBAZAD      = V_REC.CODBAZAD,
        ICONTBAZAD    = V_REC.ICONTBAZAD,
        TIPBAZAD      = V_REC.TIPBAZAD,
        CODBAZAC      = V_REC.CODBAZAC,
        ICONTBAZAC    = V_REC.ICONTBAZAC,
        TIPBAZAC      = V_REC.TIPBAZAC,
        CODDESCRD     = V_REC.CODDESCRD,
        ICONTD        = V_REC.ICONTD,
        TIPCONTD      = V_REC.TIPCONTD,
        ANALITICCONTD = V_REC.ANALITICCONTD,
        CODDESCRC     = V_REC.CODDESCRC,
        ICONTC        = V_REC.ICONTC,
        TIPCONTC      = V_REC.TIPCONTC,
        ANALITICCONTC = V_REC.ANALITICCONTC,
        GEST          = V_REC.GEST,
        VALOARE       = V_REC.VALOARE,
        VALOAREV      = V_REC.VALOAREV,
        OBS           = V_REC.OBS,
        AN            = V_REC.AN,
        LUNA          = V_REC.LUNA,
        DIRTY         = V_REC.DIRTY,
        SUBUNITATEA   = V_REC.SUBUNITATEA,
        CODCENTRU     = v_rec.CODCENTRU,
        CODANALIZANOD = v_rec.CODANALIZANOD,
        DATADOC       = V_REC.DATADOC,
        DOCUMENT      = V_REC.DOCUMENT
        WHERE
         CODJURNAL1 = V_REC.CODJURNAl1;
      ELSE
        INSERT INTO JURNAL1(CODJURNAL1, CODDOC, TIPDOC, INDEXLOCAL, CODBAZAD, ICONTBAZAD, TIPBAZAD, CODDESCRD, ICONTD, TIPCONTD, ANALITICCONTD, CODBAZAC, ICONTBAZAC, TIPBAZAC, CODDESCRC, ICONTC, TIPCONTC, ANALITICCONTC, GEST, VALOARE, VALOAREV, OBS, AN, LUNA, DIRTY, SUBUNITATEA, CODCENTRU, CODANALIZANOD, DATADOC, DOCUMENT)
        VALUES(NEXTVAL('SEQ_JURNAL1_CODJURNAL1'), RECID, V_REC.TIPDOC, V_REC.INDEXLOCAL, V_REC.CODBAZAD, V_REC.ICONTBAZAD, V_REC.TIPBAZAD, V_REC.CODDESCRD, V_REC.ICONTD, V_REC.TIPCONTD, V_REC.ANALITICCONTD, V_REC.CODBAZAC, V_REC.ICONTBAZAC, V_REC.TIPBAZAC, V_REC.CODDESCRC, V_REC.ICONTC, V_REC.TIPCONTC, V_REC.ANALITICCONTC, V_REC.GEST, V_REC.VALOARE, V_REC.VALOAREV, V_REC.OBS, V_REC.AN, V_REC.LUNA, V_REC.DIRTY, V_REC.SUBUNITATEA, V_REC.CODCENTRU, V_REC.CODANALIZANOD, V_REC.DATADOC, V_REC.DOCUMENT);
      END IF;
    END LOOP;

    DELETE FROM JURNAL WHERE TIPDOC = 71 AND  CODDOC = RECID AND CODJURNAL NOT IN (SELECT CODJURNAL FROM TMP_JURNAl);

    FOR V_REC IN (SELECT * FROM TMP_JURNAL) LOOP
      IF  V_REC.CODJURNAL &gt; 0 THEN
        UPDATE JURNAL
        SET
        CODDOC        = V_REC.CODDOC,
        TIPDOC        = V_REC.TIPDOC,
        INDEXLOCAL    = V_REC.INDEXLOCAL,
        CONTD         = V_REC.CONTD,
        CONTC         = V_REC.CONTC,
        GEST          = V_REC.GEST,
        VALOARE       = V_REC.VALOARE,
        VALOAREV      = V_REC.VALOAREV,
        OBS           = V_REC.OBS,
        AN            = V_REC.AN,
        LUNA          = V_REC.LUNA,
        SUBUNITATEA   = V_REC.SUBUNITATEA,
        CODCENTRU     = v_rec.CODCENTRU,
        CODANALIZANOD = V_REC.CODANALIZANOD,
        DATADOC       = V_REC.DATADOC,
        DOCUMENT      = V_REC.DOCUMENT
        WHERE
         CODJURNAL = V_REC.CODJURNAl;
      ELSE
        INSERT INTO JURNAL(CODJURNAL, CODDOC, TIPDOC, INDEXLOCAL, CONTD, CONTC, GEST, VALOARE, VALOAREV, OBS, AN, LUNA, SUBUNITATEA, CODCENTRU, CODANALIZANOD, DATADOC, DOCUMENT)
        VALUES(NEXTVAL('SEQ_JURNAL_CODJURNAL'), RECID, V_REC.TIPDOC, V_REC.INDEXLOCAL, V_REC.CONTD, V_REC.CONTC, V_REC.GEST, V_REC.VALOARE, V_REC.VALOAREV, V_REC.OBS, V_REC.AN, V_REC.LUNA, V_REC.SUBUNITATEA, V_REC.CODCENTRU, V_REC.CODANALIZANOD, V_REC.DATADOC, V_REC.DOCUMENT);
      END IF;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_PRODNET_CODPRODNET') INTO RecId;

    INSERT INTO PRODNET(Codprodnet, An, Luna, Obs, Tip, Subunitatea, CodGest, CodCentru)
    SELECT RECID, An, Luna, Obs, Tip, Subunitatea, CodGest, CodCentru FROM TMP_PRODNET;

    FOR V_REC IN (SELECT * FROM TMP_PRODNET1) LOOP
      SELECT NEXTVAL('SEQ_PRODNET1_CODPRODNET1') INTO VCOD;

      INSERT INTO PRODNET1(codprodnet1, codprodnet, tip, coddoc1, explicatii, valmat, valman, CodGest, CODCENTRU, CODANALIZANOD, CODCMDPRODMAT, CANTREAL, DIFCANT, PRET, CODies1)
      VALUES(vCod, RecId, V_REC.tip, V_REC.coddoc1, V_REC.explicatii, V_REC.valmat, V_REC.valman, v_rec.CodGest, v_Rec.CODCENTRU, v_Rec.CODANALIZANOD, v_Rec.CODCMDPRODMAT, v_Rec.CANTREAL, v_Rec.DIFCANT, v_rec.PRET, V_REC.CODies1);
    END LOOP;

    INSERT INTO JURNAL1(CODJURNAL1, CODDOC, TIPDOC, INDEXLOCAL, CODBAZAD, ICONTBAZAD, TIPBAZAD, CODDESCRD, ICONTD, TIPCONTD, ANALITICCONTD, CODBAZAC, ICONTBAZAC, TIPBAZAC, CODDESCRC, ICONTC, TIPCONTC, ANALITICCONTC, GEST, VALOARE, VALOAREV, OBS, AN, LUNA, DIRTY, SUBUNITATEA, CODCENTRU, CODANALIZANOD, DATADOC, DOCUMENT)
    (SELECT NEXTVAL('SEQ_JURNAL1_CODJURNAL1'), RECID, TIPDOC, INDEXLOCAL, CODBAZAD, ICONTBAZAD, TIPBAZAD, CODDESCRD, ICONTD, TIPCONTD, ANALITICCONTD, CODBAZAC, ICONTBAZAC, TIPBAZAC, CODDESCRC, ICONTC, TIPCONTC, ANALITICCONTC, GEST, VALOARE, VALOAREV, OBS, AN, LUNA, DIRTY, SUBUNITATEA, CODCENTRU, CODANALIZANOD, DATADOC, DOCUMENT
      FROM TMP_JURNAL1
    );

    INSERT INTO JURNAL(CODJURNAL, CODDOC, TIPDOC, INDEXLOCAL, CONTD, CONTC, GEST, VALOARE, VALOAREV, OBS, AN, LUNA, SUBUNITATEA, CODCENTRU, CODANALIZANOD, DATADOC, DOCUMENT)
    (SELECT NEXTVAL('SEQ_JURNAL_CODJURNAL'), RECID, TIPDOC, INDEXLOCAL, CONTD, CONTC, GEST, VALOARE, VALOAREV, OBS, AN, LUNA, SUBUNITATEA, CODCENTRU, CODANALIZANOD, DATADOC, DOCUMENT
     FROM TMP_JURNAL
    );
  END IF;

  FOR V_REC IN (SELECT * FROM TMP_RULAJ) LOOP
    SELECT COUNT( *)
    INTO NR
    FROM NCONTRUL
    WHERE CODCONT = V_REC.CODCONT AND  AN = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') AND  LUNA = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999');

    IF  NR = 0 THEN
      INSERT INTO NCONTRUL(CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, AN, LUNA)
      VALUES(NEXTVAL('SEQ_NCONTRUL_CODCONTRUL'), V_REC.CODCONT, 0, 0, 0, 0, 0, 0, 0, 0, TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999'), TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999'));
    END IF;

    UPDATE NCONTRUL
    SET
    RULAJCD  = RULAJCD  + (CASE WHEN  V_REC.TIP = 'D' THEN V_REC.VALOARE  ELSE 0 END ) ,
    RULAJCC  = RULAJCC  + (CASE WHEN  V_REC.TIP = 'C' THEN V_REC.VALOARE  ELSE 0 END ) ,
    RULAJVCD = RULAJVCD + (CASE WHEN  V_REC.TIP = 'D' THEN V_REC.VALOAREV ELSE 0 END ) ,
    RULAJVCC = RULAJVCC + (CASE WHEN  V_REC.TIP = 'C' THEN V_REC.VALOAREV ELSE 0 END )
    WHERE
     CODCONT = V_REC.CODCONT AND  AN = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') AND  LUNA = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999');

    IF  COALESCE( V_REC.SUBUNITATEA, 0) &lt;&gt; 0 THEN
      FOR V_REC_SUB IN (SELECT * FROM NCONTRUL
                        WHERE CODCONT = V_REC.CODCONT AND  AN = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') AND  LUNA = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999')
                       )
      LOOP
        SELECT COUNT( *) INTO NR FROM NCONTRULSUB WHERE CODCONTRUL = V_REC_SUB.CODCONTRUL AND  SUBUNITATEA = V_REC.SUBUNITATEA;
        IF  NR = 0 THEN
          INSERT INTO NCONTRULSUB(CODCONTRULSUB, CODCONTRUL, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, SUBUNITATEA)
          VALUES(NEXTVAL('SEQ_NCONTRULSUB_CODRULSUB'), V_REC_SUB.CODCONTRUL, 0, 0, 0, 0, 0, 0, 0, 0, V_REC.SUBUNITATEA);
        END IF;

        UPDATE NCONTRULSUB
        SET
        RULAJCD  = RULAJCD  + (CASE WHEN  V_REC.TIP = 'D' THEN V_REC.VALOARE  ELSE 0 END ) ,
        RULAJCC  = RULAJCC  + (CASE WHEN  V_REC.TIP = 'C' THEN V_REC.VALOARE  ELSE 0 END ) ,
        RULAJVCD = RULAJVCD + (CASE WHEN  V_REC.TIP = 'D' THEN V_REC.VALOAREV ELSE 0 END ) ,
        RULAJVCC = RULAJVCC + (CASE WHEN  V_REC.TIP = 'C' THEN V_REC.VALOAREV ELSE 0 END )
        WHERE
         CODCONTRUL = V_REC_SUB.CODCONTRUL AND  SUBUNITATEA = V_REC.SUBUNITATEA;
      END LOOP;
    END IF;
  END LOOP;

  PERFORM PKG_GLOBALS_MarkDirtyJurnal();
  PERFORM NotifyModif( Operation, RecId, 'PRODNET');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_calcul_cmd</obj_name>
  <obj_hashval>cbc1f045f66c2b601924e9de418e8f61</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_calcul_cmd(xt character varying, yt character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vDATASTART date;
  vDATASTOP  date;
  vZILEN     numeric;
BEGIN
  --Adina 16.08.2021 - sinc.Oracle din 14.08.2021
  --Adina 12.07.2021 - sinc.Oracle din 10.07.2021
  --Adina 09.07.2021 - sinc.Oracle din 09.07.2021
  SELECT VDELA   INTO vDATASTART FROM TMP_PROGRAMF_MANEVRA;
  SELECT VPANALA INTO vDATASTOP  FROM TMP_PROGRAMF_MANEVRA;

  SELECT count(zn1.data) INTO vZILEN FROM zineluc1 zn1
  WHERE zn1.data BETWEEN (SELECT VDELA FROM tmp_programf_manevra limit 1) AND (SELECT VpanaLA FROM tmp_programf_manevra limit 1);

  DELETE FROM TMP_PF_MAT_CMD;
  DELETE FROM TMP_PF_SDV_CMD;
  DELETE FROM TMP_PF_LOCM_CMD;
  DELETE FROM TMP_PF_MAN_CMD;

  IF  (fnc_GetValConstantaLucru('RAPORDMAN')) = '1' THEN
    INSERT INTO TMP_PF_MAT_CMD(NRDOC, DATADOC, DENOBJ, CODEXTERN, DEN_UM, CANT, CODGEST, CODOBIECT, STOCREZ, CANTPROD, PRIORITATE, CODCOMANDA1, D1, D2, D3)
    SELECT ROUND((C.NRDOC + c1.indexlocal / 1000)::numeric, 3),
           C.DATADOC, NOBJ.DENUMIRE, NOBJ.CODEXTERN, NUM1.DEN_UM1, ROUND((CMD.CANT * TMP.CANT / MAN.CANT)::numeric, 2), C.CODGEST, BAZAM.CODOBIECT,
           COALESCE(REZ.CANTREZERVAT, 0), PF1.Cantprogramat, PF1.Prioritate, C1.CODCOMANDA1, C1.D1, C1.D2, C1.D3
    FROM TMP_PROGRAMFMAN_MANEVRA TMP
        INNER JOIN CMDPRODMAN    MAN   ON  MAN.CODCMDPRODMAN = TMP.CODCMDPRODMAN
        INNER JOIN COMANDA1      C1    ON  MAN.CODCOMANDA1   = C1.CODCOMANDA1
        INNER JOIN COMANDA       C     ON  C.CODCOMANDA      = C1.CODCOMANDA AND  C.TIPDOC = 53
        INNER JOIN NARTOBJ       NOBJ  ON  NOBJ.CODOBIECT    = C1.CODOBIECT
        INNER JOIN NART                ON  NART.CODARTICOL   = NOBJ.CODARTICOL
        INNER JOIN NUM1                ON  NUM1.CODUM1       = C1.UMSEC
        INNER JOIN CMDPRODMAT    CMD   ON  CMD.CODCMDPRODMAN = TMP.CODCMDPRODMAN
        INNER JOIN TMP_PF_MAT    BAZAM ON  CMD.CODOBIECT     = BAZAM.CODOBIECT
        INNER JOIN TMP_PROGRAMF1 PF1   ON  PF1.CODCOMANDA1   = C1.CODCOMANDA1 AND  PF1.CODPROGRAMF = TMP.CODPROGRAMF
        LEFT  JOIN (SELECT REZ.CODCMDPRODMAT, SUM(REZ.REST) CANTREZERVAT FROM REZERVATS REZ GROUP BY REZ.CODCMDPRODMAT
                   ) REZ ON  REZ.CODCMDPRODMAT = CMD.CODCMDPRODMAT
    WHERE
      (C1.CONSUM = 1 AND  CMD.TIP = 1)  OR (C1.CONSUM = 2 AND CMD.TIP IN (0, 1)) ;

    INSERT INTO TMP_PF_SDV_CMD(NRCMD, PRIORITATE, DEN_OBIECT, CODEXTERN, UM, CANTPROGRAMAT, SECTIE, CODOBIECT)
    SELECT ROUND((C.NRDOC + c1.indexlocal / 1000)::numeric, 3), PF1.PRIORITATE, OBJ.DENUMIRE, OBJ.CODEXTERN, NUM.DEN_UM, PF1.CANTPROGRAMAT, C.CODGEST SECTIE, SDV.CODSDV
    FROM TMP_PROGRAMFMAN_MANEVRA PFM
        INNER JOIN CMDPRODMAN    MAN ON  MAN.CODCMDPRODMAN = PFM.CODCMDPRODMAN
        INNER JOIN COMANDA1      C1  ON  C1.CODCOMANDA1    = MAN.CODCOMANDA1
        INNER JOIN COMANDA       C   ON  C1.CODCOMANDA     = C.CODCOMANDA
        INNER JOIN PRODSDV       SDV ON  SDV.CODPRODMAN    = MAN.CODMAN
        INNER JOIN NARTOBJ       OBJ ON  OBJ.CODOBIECT     = C1.CODOBIECT
        INNER JOIN NART          A   ON  OBJ.CODARTICOL    = A.CODARTICOL
        INNER JOIN NUM               ON  NUM.CODUM         = A.UM
        INNER JOIN TMP_PROGRAMF1 PF1 ON  PF1.CODCOMANDA1   = C1.CODCOMANDA1 AND  PF1.CODPROGRAMF = PFM.CODPROGRAMF;

    INSERT INTO TMP_PF_LOCM_CMD(CODLMC, CODPROGRAMF, CODGEST, CODLOC, CODCOMANDA1, DATAPROGRAMARE, NRCMD, PRIORITATE, DEN_OBIECT, CODEXTERN, NECESAR, NECESARM, DEN_UM, CANTPROD, CODOP)
    SELECT -row_number() over(), PF1.CODPROGRAMF, C.CODGEST, MAN.CODLOC, PF1.CODCOMANDA1, vDataStart,
           ROUND((C.NRDOC + c1.indexlocal / 1000)::numeric, 3),
           PF1.PRIORITATE, OBJ.DENUMIRE, OBJ.CODEXTERN,
           ROUND((PFM.CANT * coalesce(MAN.TPI, 0) + PFM.CANT * MAN.TU / 60)::numeric, 2)  NECESAR,
           COALESCE(ROUND((PFM.CANT * COALESCE(MAN.TPI, 0) + PFM.CANT * MAN.TU)::numeric, 2), 0) NECESARM, NUM1.DEN_UM1, PF1.CANTPROGRAMAT, MAN.CODOP
    FROM TMP_PROGRAMFMAN_MANEVRA PFM
        INNER JOIN CMDPRODMAN    MAN ON  PFM.CODCMDPRODMAN = MAN.CODCMDPRODMAN
        INNER JOIN COMANDA1      C1  ON  C1.CODCOMANDA1    = MAN.CODCOMANDA1
        INNER JOIN COMANDA       C   ON  C1.CODCOMANDA     = C.CODCOMANDA
        INNER JOIN NARTOBJ       OBJ ON  OBJ.CODOBIECT     = C1.CODOBIECT
        INNER JOIN NUM1              ON  NUM1.CODUM1       = C1.UMSEC
        INNER JOIN PRODCOMP      PC  ON  C1.CODRETETA      = PC.CODPRODCOMP
        INNER JOIN NGEST         PG  ON  PG.CODGEST        = C.CODGEST
        INNER JOIN TMP_PROGRAMF1 PF1 ON  PF1.CODCOMANDA1   = C1.CODCOMANDA1 AND  PF1.CODPROGRAMF = PFM.CODPROGRAMF;

    INSERT INTO TMP_PF_MAN_CMD(CODOP, CODGEST, CODCOMANDA1, DATADOC, NRDOC, DENUMIRE, CODEXTERN, NECESAR, NECESARM,
                               DEN_UM, CANTPROD, VALOARE, PRIORITATE, OPERATII, CODCMDPRODMAN)
    SELECT MAN.CODOP, C.CODGEST, C1.CODCOMANDA1, C.DATADOC, ROUND((C.NRDOC + c1.indexlocal / 1000)::numeric, 3), OBJ.DENUMIRE, OBJ.CODEXTERN,
           round((TMP.CANT * coalesce(MAN.TPI, 0) + TMP.CANT * coalesce(MAN.TU, 0) / 60)::numeric, 3),
           round((TMP.CANT * coalesce(MAN.TPI, 0) + TMP.CANT * coalesce(MAN.TU, 0))::numeric, 3),
           NUM1.DEN_UM1, PF1.CANTPROGRAMAT,
           round((TMP.CANT * coalesce(MAN.TPI, 0) + TMP.CANT * coalesce(MAN.TU, 0) / 60)::numeric, 3) * TMPM.TARIF,
           PF1.Prioritate, MAN.CANT, PFM.CODCMDPRODMAN
    FROM TMP_PROGRAMFMAN_MANEVRA TMP
        INNER JOIN CMDPRODMAN    MAN  ON  MAN.CODCMDPRODMAN = TMP.CODCMDPRODMAN
        INNER JOIN PROGRAMFMAN   PFM  ON PFM.CODCMDPRODMAN  = MAN.CODCMDPRODMAN
        INNER JOIN COMANDA1      C1   ON  C1.CODCOMANDA1    = MAN.CODCOMANDA1
        INNER JOIN COMANDA       C    ON  C.CODCOMANDA      = C1.CODCOMANDA
        INNER JOIN NARTOBJ       OBJ  ON  C1.CODOBIECT      = OBJ.CODOBIECT
        INNER JOIN PRODCOMP      PC   ON  PC.CODPRODCOMP    = C1.CODRETETA
        INNER JOIN NUM1               ON  NUM1.CODUM1       = C1.UMSEC
        LEFT  JOIN TMP_PF_MAN    TMPM ON  TMPM.CODOP        = MAN.CODOP
        LEFT  JOIN TMP_PROGRAMF1 PF1  ON  PF1.CODCOMANDA1   = C1.CODCOMANDA1 AND  PF1.CODPROGRAMF = TMP.CODPROGRAMF;
  ELSE
    INSERT INTO TMP_PF_MAT_CMD(NRDOC, DATADOC, DENOBJ, CODEXTERN, DEN_UM, CANT, CODGEST, CODOBIECT, STOCREZ, CANTPROD, PRIORITATE, CODCOMANDA1, D1, D2, D3)
    SELECT ROUND((C.NRDOC + c1.indexlocal / 1000)::numeric, 3),
           C.DATADOC, NOBJ.DENUMIRE, NOBJ.CODEXTERN, NUM1.DEN_UM1, ROUND((CMD.CANT * PF1.CANTPROGRAMAT / C1.CANTACCEPTAT)::numeric, 2), C.CODGEST, BAZAM.CODOBIECT,
           COALESCE(REZ.CANTREZERVAT, 0), PF1.Cantprogramat, PF1.Prioritate, C1.CODCOMANDA1, C1.D1, C1.D2, C1.D3
    FROM TMP_PROGRAMF1_MANEVRA PF1
        INNER JOIN comanda1   c1    ON  PF1.codcomanda1 = c1.codcomanda1
        INNER JOIN COMANDA    C     ON  C.CODCOMANDA    = C1.CODCOMANDA AND  C.TIPDOC = 53
        INNER JOIN cmdprodmat CMD   ON  C1.CODCOMANDA1  = cmd.codcomanda1
        INNER JOIN NARTOBJ    NOBJ  ON  NOBJ.CODOBIECT  = C1.CODOBIECT
        INNER JOIN NART             ON  NART.CODARTICOL = NOBJ.CODARTICOL
        INNER JOIN NUM1             ON  NUM1.CODUM1     = C1.UMsec
        INNER JOIN TMP_PF_MAT BAZAM ON  CMD.CODOBIECT   = BAZAM.CODOBIECT
        LEFT  JOIN (SELECT REZ.CODCMDPRODMAT, SUM(REZ.REST) CANTREZERVAT FROM REZERVATS REZ GROUP BY REZ.CODCMDPRODMAT
                   ) REZ ON  REZ.CODCMDPRODMAT = CMD.CODCMDPRODMAT
    WHERE
      (C1.CONSUM = 1 AND  CMD.TIP = 1)  OR (C1.CONSUM = 2 AND CMD.TIP IN (0, 1)) ;

    INSERT INTO TMP_PF_SDV_CMD(NRCMD, PRIORITATE, DEN_OBIECT, CODEXTERN, UM, CANTPROGRAMAT, SECTIE, CODOBIECT)
    SELECT ROUND((C.NRDOC + c1.indexlocal / 1000)::numeric, 3), PF1.PRIORITATE, OBJ.DENUMIRE, OBJ.CODEXTERN, NUM.DEN_UM, PF1.CANTPROGRAMAT, C.CODGEST SECTIE, SDV.CODSDV
    FROM TMP_PROGRAMF1_MANEVRA PF1
        INNER JOIN COMANDA1 C1  ON  C1.CODCOMANDA1  = PF1.CODCOMANDA1
        INNER JOIN COMANDA  C   ON  C1.CODCOMANDA   = C.CODCOMANDA
        INNER JOIN PRODSDV  SDV ON  SDV.CODPRODCOMP = C1.CODRETETA
        INNER JOIN NARTOBJ  OBJ ON  OBJ.CODOBIECT   = C1.CODOBIECT
        INNER JOIN NART     A   ON  OBJ.CODARTICOL  = A.CODARTICOL
        INNER JOIN NUM          ON  NUM.CODUM       = A.UM;

    INSERT INTO TMP_PF_LOCM_CMD(CODLMC, CODPROGRAMF, CODGEST, CODLOC, CODCOMANDA1, DATAPROGRAMARE, NRCMD, PRIORITATE, DEN_OBIECT, CODEXTERN, NECESAR, NECESARM, den_um, cantprod, CODOP)
    SELECT -row_number() over(), PF1.CODPROGRAMF, C.CODGEST, PMAN.CODLOC, PF1.CODCOMANDA1, vDataStart,
           ROUND((C.NRDOC + c1.indexlocal / 1000)::numeric, 3),
           PF1.PRIORITATE, OBJ.DENUMIRE, OBJ.CODEXTERN,
           coalesce(CASE WHEN PC.CANT &lt;&gt; 1 THEN PF1.CANTPROGRAMAT / PC.CANT * coalesce(PMAN.TPI, 0)  + PF1.CANTPROGRAMAT / PMAN.BPS * PMAN.TU
                         ELSE coalesce(PMAN.TPI, 0) + PF1.CANTPROGRAMAT / PMAN.BPS * PMAN.TU
                    END,0) / 60  NECESAR,
           COALESCE(CASE WHEN  PC.CANT &lt;&gt; 1 THEN PF1.CANTPROGRAMAT / PC.CANT * COALESCE(PMAN.TPI, 0) + PF1.CANTPROGRAMAT / PMAN.BPS * PMAN.TU
                         ELSE COALESCE(PMAN.TPI, 0) + PF1.CANTPROGRAMAT / PMAN.BPS * PMAN.TU
                    END , 0) NECESARM,
           NUM1.DEN_UM1, PF1.CANTPROGRAMAT, PMAN.CODOP
    FROM TMP_PROGRAMF1_MANEVRA PF1
        INNER JOIN COMANDA1   C1   ON  C1.CODCOMANDA1   = PF1.CODCOMANDA1
        INNER JOIN COMANDA    C    ON  C1.CODCOMANDA    = C.CODCOMANDA
        INNER JOIN NARTOBJ    OBJ  ON  OBJ.CODOBIECT    = C1.CODOBIECT
        INNER JOIN NUM1            ON  NUM1.CODUM1      = C1.UMSEC
        INNER JOIN PRODCOMP   PC   ON  C1.CODRETETA     = PC.CODPRODCOMP
        INNER JOIN CMDPRODMAN PMAN ON  PMAN.CODCOMANDA1 = C1.CODCOMANDA1
        INNER JOIN NGEST      PG   ON  PG.CODGEST       = C.CODGEST;

    INSERT INTO TMP_PF_MAN_CMD(CODOP, CODGEST, CODCOMANDA1, DATADOC, NRDOC, DENUMIRE, CODEXTERN, NECESAR, NECESARM, den_um, cantprod, valoare, Prioritate, OPERATII)
    SELECT MAN.CODOP, C.CODGEST, C1.CODCOMANDA1, C.DATADOC, ROUND((C.NRDOC + c1.indexlocal / 1000)::numeric, 3), OBJ.DENUMIRE, OBJ.CODEXTERN,
           round((sum(CASE WHEN PC.CANT &lt;&gt; 1 THEN round((TMP.CANTPROGRAMAT/coalesce(PC.CANT, 1) * coalesce(MAN.TPI, 0) + TMP.CANTPROGRAMAT / coalesce(MAN.BPS, 1) * coalesce(MAN.TU, 0))::numeric, 6)
                          ELSE round((coalesce(MAN.TPI, 0) + TMP.CANTPROGRAMAT * coalesce(MAN.TU, 0))::numeric, 6)
                     END
                    ) / 60)::numeric, 6) ,
           round((sum(CASE WHEN  PC.CANT &lt;&gt; 1 THEN round((TMP.CANTPROGRAMAT / COALESCE(PC.CANT, 1) * COALESCE(MAN.TPI, 0) + TMP.CANTPROGRAMAT / COALESCE(MAN.BPS, 1) * COALESCE(MAN.TU, 0))::numeric, 6)
                           ELSE round((COALESCE(MAN.TPI, 0) + TMP.CANTPROGRAMAT * COALESCE(MAN.TU, 0))::numeric, 6)
                      END ))::numeric, 6),
           TMP.UM, TMP.CANTPROGRAMAT,
           round((sum(CASE WHEN  PC.CANT &lt;&gt; 1 THEN round((TMP.CANTPROGRAMAT / COALESCE(PC.CANT, 1) * COALESCE(MAN.TPI, 0) + TMP.CANTPROGRAMAT / COALESCE(MAN.BPS, 1) * COALESCE(MAN.TU, 0))::numeric, 6)
                           ELSE round((COALESCE(MAN.TPI, 0) + TMP.CANTPROGRAMAT * COALESCE(MAN.TU, 0))::numeric, 6)
                      END ) / 60)::numeric, 6) * TMPM.TARIF,
           TMP.Prioritate, SUM(MAN.CANT)
    FROM COMANDA1 C1
        INNER JOIN TMP_PROGRAMF1_MANEVRA TMP  ON  C1.CODCOMANDA1  = TMP.CODCOMANDA1
        INNER JOIN COMANDA               C    ON  C.CODCOMANDA    = C1.CODCOMANDA
        INNER JOIN NARTOBJ               OBJ  ON  C1.CODOBIECT    = OBJ.CODOBIECT
        INNER JOIN PRODCOMP              PC   ON  PC.CODPRODCOMP  = C1.CODRETETA
        INNER JOIN CMDPRODMAN            MAN  ON  MAN.CODCOMANDA1 = C1.CODCOMANDA1
        INNER JOIN TMP_PF_MAN            TMPM ON  TMPM.CODOP      = MAN.CODOP
    GROUP BY MAN.CODOP, C.CODGEST, C1.CODCOMANDA1, C.NRDOC, C1.IndexLocal, C.DATADOC, OBJ.DENUMIRE, OBJ.CODEXTERN, TMP.UM, TMP.CANTPROGRAMAT, TMPM.TARIF, TMP.Prioritate;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_sp_gotorecord</obj_name>
  <obj_hashval>5cb382e9325315345c60d6a822235cf7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  X         numeric;
  Total     numeric;
  Facut     numeric;
  NewOrdine numeric := -1;
  aMarja    numeric;
  aNivel    numeric;
BEGIN
  --Florin 12.04.2023 - sinc. Oracle (11.04.2023)
  --Adina 10.06.2021 - sinc.Oracle din 09 si 10.06.2021
  --Florin 16.11.2021 - fixat 52001
  perform pkg_proiect_setct_monitor('MON_42');
  INSERT INTO TMP_PROIECT(CodProiect, CodVersiune, CodObiectProd, Versiune, Intocmita, DataProiect, Clasa, Procesare, Complex, activ, Finalizat, Blocat, Den_Procesare,
                          Den_Pers, Masa, Den_Obiect, Invizibila, Durata, MarjaOrdine, implicit, Generic, Obs1, Obs2, Obs3, Obs4, Obs5, Obs6, CodUtilizare, CodExtern, CodIdentificare
                         )
  (
  SELECT P.CodProiect, P.CodVersiune, P.CodObiectProd, P.Versiune, P.Intocmita, P.DataProiect, P.Clasa, P.Procesare, P.Complex, P.activ, P.Finalizat, P.Blocat,
         CASE WHEN  P.Procesare = 1 THEN 'Agregare' ELSE 'Dezagregare' END  DEN_PROCESARE,
         coalesce(NP.NUME,'') || ' ' || coalesce(NP.PRENUME,'') DEN_PERS,
         (SELECT PKG_PROIECT_GetMasa.WME_RESULT FROM PKG_PROIECT_GetMasa(NULL,P.Codproiect)),
         OBJ.Denumire, P.Invizibila, P.Durata, COALESCE(P.MarjaOrdine, 0), P.implicit, P.Generic, P.Obs1, P.Obs2, P.Obs3, P.Obs4, P.Obs5, P.Obs6, P.CodUtilizare, P.CodExtern,
         P.CODIDENTIFICARE
  FROM PROIECT P
      LEFT JOIN NPERS   NP  ON  P.Intocmita     = NP.Codpers
      LEFT JOIN NARTOBJ OBJ ON  P.CODOBIECTPROD = OBJ.CODOBIECT
  WHERE P.CodProiect = RecId
  );

  INSERT INTO TMP_PROIECTNOD(CODPROIECTNOD, CODPROIECT, CANT, NECESAR, NODORIGINAL, POZITIE, CODRETETA, TIP, CODOBIECT, DenUM, INDEXPARINTE, CodProdMat, DENUMIRE, OBS,
                             IDENTIFICATOR, DATADOCUMENTATIE, ARHIVA, PROIECTANT, ordine, nivel, DECALAJ)
  (
  SELECT PN.CODPROIECTNOD, PN.CODPROIECT, PN.CANT, PN.CANT, PN.NODORIGINAL, PN.POZITIE, PN.CODRETETA, PN.TIP, PN.CodObiect, U.DEN_UM, PN.INDEXPARINTE, PN.CodProdMat,
         OBJ.DENUMIRE, PC.OBS, PC.IDENTIFICATOR, PC.DATA, PC.ARHIVA, PC.PROIECTANT, COALESCE(pn.ordine, 0), PN.NIVEL, coalesce(PN.DECALAJ,2) DECALAJ
  FROM PROIECTNOD PN
      INNER JOIN NARTOBJ  OBJ ON  PN.CODOBIECT = OBJ.CODOBIECT
      INNER JOIN NART     A   ON  A.CODARTICOL = OBJ.CODARTICOL
      INNER JOIN NUM      U   ON  U.CodUM      = A.UM
      LEFT  JOIN PRODCOMP PC  ON  PN.CodReteta = PC.CodProdComp
  WHERE PN.CODPROIECT = RecId
  );

  INSERT INTO tmp_proiectman(CODPROIECTNOD, CODPROIECT, NODORIGINAL, POZITIE, CODRETETA, DEN_OBIECT, TIP, SIMBOL, DURATA, CANT, NIVEL, ORDINE,
                             INCEPERE, Decalaj, DURATANOD, COPILMAXIM, NODCRITIC, BARA, LOTOPTIM, INDEXPARINTE)
  SELECT PN.CODPROIECTNOD, PN.CODPROIECT, PN.NODORIGINAL, PN.POZITIE, PN.CODRETETA, obj.denumire DEN_OBIECT, 0, pn.IndexParinte SIMBOL,
         Round((pn.Cant * COALESCE(pc.Durata, 0) / pc.cant)::numeric, 3) DURATA, pn.Cant, pn.nivel, COALESCE(o.Ordine*10000 + Pozitie, 0),
         COALESCE(Incepere, 0), PN.DECALAJ, 0, -1, '...' NODCRITIC, '...' BARA,
         pc.cant, PN.INDEXPARINTE
  FROM proiectnod pn
      INNER JOIN prodcomp pc ON  pn.codreteta  = pc.codprodcomp
      INNER JOIN nartobj obj ON  obj.codobiect = pc.codobiect
      INNER JOIN (SELECT DISTINCT Nivel,
                         (SELECT Max(Nivel) FROM proiectnod WHERE CodProiect = RecId) - Nivel AS ORDINE
                  FROM proiectnod WHERE CodProiect = RecId GROUP BY Nivel
                 ) O ON  O.Nivel = pn.Nivel
  WHERE PN.CodProiect = RecId and  pc.codprodcomp &gt; 0;

/*
  PERFORM PKG_PROIECT_SetCopilMaxim(RecId);

  BEGIN
    SELECT CodProiectNod, COALESCE(DurataNod, 0) INTO X, Total FROM tmp_proiectman WHERE COALESCE(NodOriginal, 0) = 0;
  EXCEPTION WHEN others THEN
    X     := 0;
    Total := 0;
  END;

  IF  Total &gt; 0 THEN
    PERFORM PKG_PROIECT_SetDrumCritic (X);
    PERFORM PKG_PROIECT_SetDecalaj(X, Total);

    SELECT COALESCE(MarjaOrdine, 0) INTO aMarja FROM tmp_proiect;

    FOR v_rec IN (SELECT CodProiectNod FROM tmp_proiectman ORDER BY Incepere) LOOP
      BEGIN
        SELECT COALESCE(Incepere, 0), Tip, Nivel INTO X, Facut, aNivel FROM tmp_proiectman WHERE CodProiectNod = v_rec.CodProiectNod;
      EXCEPTION WHEN others THEN
        X     := 0;
        Facut := 0;
      END;

      IF  FACUT &lt;&gt; 1 THEN
        NewOrdine := NewOrdine + 1;
        UPDATE tmp_proiectman
        SET
        Tip      = 1,
        Ordine   = NewOrdine,
        Incepere = X,
        Decalaj  = Decalaj - X + Incepere
        WHERE
         Nivel &gt; aNivel and  Incepere &gt;= X and  Incepere &lt;= X + aMarja;
      END IF;
    END LOOP;

    UPDATE Tmp_Proiectnod n SET Ordine = (SELECT COALESCE(m.Ordine, 0) FROM TMP_ProiectMan m WHERE m.Codproiectnod = n.codproiectnod);
    UPDATE Tmp_Proiectnod n SET Ordine = 0 WHERE n.Ordine IS NULL;

    INSERT INTO tmp_proiectGrid(ORDINE, INCEPERE)
    (SELECT  DISTINCT ORDINE, INCEPERE + Durata FROM tmp_proiectMan);
  END IF;

  for v_rec in (select t.codproiectnod from tmp_proiectman t order by t.nivel desc, t.pozitie) loop
    PERFORM pkg_proiect_SETDURATANOD(v_rec.CODPROIECTNOD);
  end loop;
*/

  update tmp_proiect set durata = (select coalesce(incepere,0) + coalesce(durata,0) from tmp_proiectman where nodoriginal = 0);
  PERFORM PKG_CFGTABLES_EXT_GOTORECORD(507);

end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmaefurn_processlist</obj_name>
  <obj_hashval>9c7793bdcc6a55eabd8b2e43df5dac93</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmaefurn_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert      varchar := '';
  sSelect1     varchar := '';
  sSelect2     varchar := '';
  sSelect3     varchar := '';
  sPer         varchar := '';
  sNotBcar     varchar := '';
  gSuplCols    VARCHAR :=
    'intrari ae, intrari1 ae1, nartobj o, nart art, num1 u, npart p, intrari i, intrari1 i1, nclasea cla, nclasep clp, nagenda ag, traseulivr t, '||
    'npart prod, ncarsupart cs, nparttr d, nartcli ac, nlocalit loc, ntari tari, nartobjtrad trad, nechiv e, grechiv gre, oferta1 o1, bcar bcar, iesiri ies, iesiri1 ies1';
  gUserFields  VARCHAR := '';
  gUserAlias   VARCHAR := '';
  gNullAlias   VARCHAR := '';
  gSuplJoins   VARCHAR := '';
  gDataS       VARCHAR := '';
  gDataF       VARCHAR := '';
  gOpt1        BOOLEAN      ;
BEGIN
  --Laura 29.10.2021 - sinc Oracle (29.10.2021)
  --Adina 19 august 2020
  gOpt1 := current_setting('PKG_LIST_ALEGPERIOADA.gOpt1', true)::boolean;

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = O.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = O.CODOBIECT',NULL);

  IF  coalesce(fnc_GetValConstanta('CumulezBcar', getANLUCRU(), getLUNALUCRU()),'0') = '2' THEN
    call pkg_list_struct_addsupltabs(gSuplCols, 'BCAR', 'BCAR', 'bcar.CODDOC1 = AE1.CODIES1 AND BCAR.TIPDOC = AE.TIPDOC',NULL);
    call pkg_list_struct_addsupltabs(gSuplCols, 'BCAREXT', 'BCAREXT', 'bcarext.codbcar = bcar.codbcar',NULL);
  END IF;

  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_URMAEFURN.gSuplCols',gSuplCols,false);

  sInsert := 'INSERT INTO ' || tmpName || '(
      NAV_CodDoc,NAV_TipDoc,
      Ae,
      Doc, Part,
      Art, UM, Cant, CantAe, CantPrel, RestC,
      RestV, PUAE,
      NrLinAe, Ordine,
      DenLaCli, CodLaCli,
      CodListat' || gUserFields || ')';

  gDataS := COALESCE(current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true),'');
  gDataF := COALESCE(current_setting('PKG_LIST_ALEGPERIOADA.gDataF', true),'');

  IF  to_date(gDataS,'dd.mm.yyyy') = to_date(gDataF,'dd.mm.yyyy') THEN
    sPer := '= TO_DATE(''' || gDataS || ''',''dd.mm.yyyy'')';
  ELSE
    sPer := 'BETWEEN TO_DATE(''' || gDataS || ''',''dd.mm.yyyy'') AND TO_DATE(''' || gDataF || ''',''dd.mm.yyyy'')';
  END IF;

  sSelect1 := '
  SELECT
    ae.CodIntr, ae.tipdoc,
    CASE
      WHEN i.codintr IS NOT NULL THEN i.PrefixDoc||i.NrDoc||''/''||to_char(i.Datadoc,''dd.mm.yyyy'')
      ELSE ae.PrefixDoc||ae.NrDoc||''/''||to_char(ae.Datadoc,''dd.mm.yyyy'')
    END Ae,
    ae.PrefixDoc||ae.NrDoc||''/''||to_char(ae.Datadoc,''dd.mm.yyyy'') Doc, p.Den_Part Part,
    o.denumire Art, u.den_um1 UM, ae1.cant/u.paritate Cant, ae1.cant/u.paritate CantAe, 0 CantPrel, ae1.cant/u.paritate RestC,
    ae1.cant*Coalesce(i1.pu,ae1.pu,0) RestV, Coalesce(i1.pu,ae1.pu,0) * u.paritate PUAE,
    Coalesce(i1.indexlocal, ae1.indexlocal, 0) NrLinAe, (case when i.codintr is NULL then 0 else 1 end) Ordine,
    COALESCE(ac.denumire,trad.denumiretrad,o.denumire) DenLaCli, coalesce(ac.codextern,o.codextern) CodLaCli,
    coalesce((case when ac.tipcodafisat=1 then gre.cod when ac.tipcodafisat=2 then ac.codextern when ac.tipcodafisat=3 then o.codextern when ac.tipcodafisat=4 then o.codintern when ac.tipcodafisat=5 then o.codvamal when ac.tipcodafisat=6 then o.codplu::varchar when ac.tipcodafisat=7 then o1.codextofe end),o.codextern) CodListat' || gUserAlias || '
  FROM intrari ae
    INNER JOIN intrari1   ae1   ON ae1.codintr     = ae.codintr
    INNER JOIN nartobj     o    ON o.codobiect     = ae1.codobiect
    INNER JOIN nart        art  ON o.codarticol    = art.codarticol
    INNER JOIN num1        u    ON u.codum1        = ae1.umsec
    INNER JOIN npart       p    ON p.codpart       = ae.partener
    LEFT  JOIN intrari1    i1   ON i1.codintr1     = ae1.codintr1storno
    LEFT  JOIN intrari     i    ON i.codintr       = i1.codintr
    LEFT  JOIN nclasea     cla  on cla.codclasea   = art.clasa
    LEFT  JOIN nclasep     clp  on clp.codclasep   = p.codclasa
    LEFT  JOIN nagenda     ag   on ag.codagenda    = ae.codlocatie
    LEFT  JOIN traseulivr  t    on t.codtraseulivr = ag.codtraseu
    LEFT  JOIN npart       prod ON prod.codpart    = o.codproducator
    LEFT  JOIN ncarsupart  cs   ON cs.codcarsupart = o.codcaract
    LEFT  JOIN nparttr     d    ON d.codparttr     = ae.delegat
    LEFT  JOIN nartcli     ac   ON ac.codobiect    = ae1.codobiect AND ac.codpart = ae.partener
    LEFT  JOIN nlocalit    loc  ON loc.codlocalit  = ag.codlocalit
    LEFT  JOIN ntari       tari ON tari.codtara    = loc.codtara
    LEFT  JOIN nartobjtrad trad ON trad.codlimba   = tari.codlimba and trad.codobiect = ae1.codobiect
    LEFT  JOIN nechiv      e    ON e.codobiect     = ae1.codobiect
    LEFT  JOIN grechiv     gre  ON gre.codgrechiv  = e.codgrupa
    LEFT  JOIN oferta1     o1   ON o1.codoferta1   = ae1.codoferta1
    LEFT  JOIN iesiri1     ies1 ON ies1.codies1    = ae.codintr - ae.codintr
  LEFT  JOIN iesiri      ies  ON ies.codies      = ies1.codies'
    || gSuplJoins || '
  WHERE ae.tipdoc = 2 AND ae.operat = 1 AND ae.anulat = 0 ' || PKG_LIST_BASE_UTILS_COND_SUBUNIT('AE',NULL,NULL,NULL) || '
    AND ae.DataDoc ' || sPer;

  sSelect2 := '
  SELECT
    i.codintr, i.tipdoc,
    ae.PrefixDoc||ae.NrDoc||''/''||to_char(ae.Datadoc,''dd.mm.yyyy'') Ae,
    i.PrefixDoc||i.NrDoc||''/''||to_char(i.Datadoc,''dd.mm.yyyy'') Doc, p.Den_Part Part,
    o.denumire Art, u.den_um1 UM, il.cant/u.paritate Cant, 0 CantAe, il.cant/u.paritate CantPrel, -il.cant/u.paritate RestC,
    -il.cant*coalesce(ae1.pu,0) RestV, coalesce(ae1.pu,0) * u.paritate PUAE,
    coalesce(ae1.IndexLocal, 0) NrLinAe, 2 Ordine,
    COALESCE(ac.denumire,trad.denumiretrad,o.denumire) DenLaCli, coalesce(ac.codextern,o.codextern) CodLaCli,
    coalesce((case when ac.tipcodafisat=1 then gre.cod when ac.tipcodafisat=2 then ac.codextern when ac.tipcodafisat=3 then o.codextern when ac.tipcodafisat=4 then o.codintern when ac.tipcodafisat=5 then o.codvamal when ac.tipcodafisat=6 then o.codplu::varchar when ac.tipcodafisat=7 then o1.codextofe end),o.codextern) CodListat' || gUserAlias || '
  FROM intrari ae
    INNER JOIN intrari1    ae1  ON ae1.codintr     = ae.codintr
    INNER JOIN nartobj     o    ON o.codobiect     = ae1.codobiect
    INNER JOIN nart        art  ON o.codarticol    = art.codarticol
    INNER JOIN num1        u    ON u.codum1        = ae1.umsec
    INNER JOIN npart       p    ON p.codpart       = ae.partener
    INNER JOIN intrlink    il   ON il.codlinieaviz = ae1.codintr1
    INNER JOIN intrari1    i1   ON i1.codintr1     = il.codintr1
    INNER JOIN intrari     i    ON i.codintr       = i1.codintr
    LEFT  JOIN nclasea     cla  on cla.codclasea   = art.clasa
    LEFT  JOIN nclasep     clp  on clp.codclasep   = p.codclasa
    LEFT  JOIN nagenda     ag   on ag.codagenda    = ae.codlocatie
    LEFT  JOIN traseulivr  t    on t.codtraseulivr = ag.codtraseu
    LEFT  JOIN npart       prod ON prod.codpart    = o.codproducator
    LEFT  JOIN ncarsupart  cs   ON cs.codcarsupart = o.codcaract
    LEFT  JOIN nparttr     d    ON d.codparttr     = ae.delegat
    LEFT  JOIN nartcli     ac   ON ac.codobiect    = ae1.codobiect AND ac.codpart = ae.partener
    LEFT  JOIN nlocalit    loc  ON loc.codlocalit  = ag.codlocalit
    LEFT  JOIN ntari       tari ON tari.codtara    = loc.codtara
    LEFT  JOIN nartobjtrad trad ON trad.codlimba   = tari.codlimba and trad.codobiect = ae1.codobiect
    LEFT  JOIN nechiv      e    ON e.codobiect     = ae1.codobiect
    LEFT  JOIN grechiv     gre  ON gre.codgrechiv  = e.codgrupa
    LEFT  JOIN oferta1     o1   ON o1.codoferta1   = ae1.codoferta1
    LEFT  JOIN iesiri1     ies1 ON ies1.codies1    = ae.codintr - ae.codintr
  LEFT  JOIN iesiri      ies  ON ies.codies      = ies1.codies'
    || gSuplJoins || '
  WHERE ae.tipdoc = 2 AND ae.operat = 1 AND ae.anulat = 0 AND il.cant &lt;&gt; 0 ' || PKG_LIST_BASE_UTILS_COND_SUBUNIT('AE',NULL,NULL,NULL) || '
    AND i.operat = 1 AND i.anulat = 0
    AND ae.DataDoc ' || sPer || coalesce(CASE WHEN gOpt1 THEN ' AND i.DataDoc ' || sPer  END,'');

  sSelect3 := '
  SELECT
    ies.codies, ies.tipdoc,
    ae.PrefixDoc||ae.NrDoc||''/''||to_char(ae.Datadoc,''dd.mm.yyyy'') Ae,
    ies.PrefixDoc||ies.NrDoc||''/''||to_char(ies.Datadoc,''dd.mm.yyyy'') Doc, p.Den_Part Part,
    o.denumire Art, u.den_um1 UM, ies1.cant/u.paritate Cant, 0 CantAE, ies1.cant/u.paritate CantPrel, -ies1.cant/u.paritate RestC,
    -ies1.cant*coalesce(ae1.pu,0) RestV, coalesce(ae1.pu,0) * u.paritate PUAE,
    coalesce(ae1.IndexLocal, 0) NrLinAe, 2 Ordine,
    COALESCE(ac.denumire,trad.denumiretrad,o.denumire) DenLaCli, coalesce(ac.codextern,o.codextern) CodLaCli,
    coalesce((case when ac.tipcodafisat=1 then gre.cod when ac.tipcodafisat=2 then ac.codextern when ac.tipcodafisat=3 then o.codextern when ac.tipcodafisat=4 then o.codintern when ac.tipcodafisat=5 then o.codvamal when ac.tipcodafisat=6 then o.codplu::varchar when ac.tipcodafisat=7 then o1.codextofe end),o.codextern) CodListat' || gUserAlias || '
  FROM intrari ae
    INNER JOIN intrari1    ae1  ON ae1.codintr     = ae.codintr
    INNER JOIN nartobj     o    ON o.codobiect     = ae1.codobiect
    INNER JOIN nart        art  ON o.codarticol    = art.codarticol
    INNER JOIN num1        u    ON u.codum1        = ae1.umsec
    INNER JOIN npart       p    ON p.codpart       = ae.partener
    INNER JOIN iesiri1     ies1 ON ies1.codliniedocimp = ae1.codintr1 AND ies1.tipdocimp = ae.tipdoc
    INNER JOIN iesiri      ies  ON ies.codies      = ies1.codies
    LEFT  JOIN intrari1    i1   ON i1.codintr1     = ae1.codintr1-ae1.codintr1
    LEFT  JOIN intrari     i    ON i.codintr       = i1.codintr
    LEFT  JOIN nclasea     cla  on cla.codclasea   = art.clasa
    LEFT  JOIN nclasep     clp  on clp.codclasep   = p.codclasa
    LEFT  JOIN nagenda     ag   on ag.codagenda    = ae.codlocatie
    LEFT  JOIN traseulivr  t    on t.codtraseulivr = ag.codtraseu
    LEFT  JOIN npart       prod ON prod.codpart    = o.codproducator
    LEFT  JOIN ncarsupart  cs   ON cs.codcarsupart = o.codcaract
    LEFT  JOIN nparttr     d    ON d.codparttr     = ae.delegat
    LEFT  JOIN nartcli     ac   ON ac.codobiect    = ae1.codobiect AND ac.codpart = ae.partener
    LEFT  JOIN nlocalit    loc  ON loc.codlocalit  = ag.codlocalit
    LEFT  JOIN ntari       tari ON tari.codtara    = loc.codtara
    LEFT  JOIN nartobjtrad trad ON trad.codlimba   = tari.codlimba and trad.codobiect = ae1.codobiect
    LEFT  JOIN nechiv      e    ON e.codobiect     = ae1.codobiect
    LEFT  JOIN grechiv     gre  ON gre.codgrechiv  = e.codgrupa
    LEFT  JOIN oferta1     o1   ON o1.codoferta1   = ae1.codoferta1' || gSuplJoins || '
  WHERE ae.tipdoc = 2 AND ae.operat = 1 AND ae.anulat = 0 AND ies1.cant &lt;&gt; 0 ' || PKG_LIST_BASE_UTILS_COND_SUBUNIT('AE',NULL,NULL,NULL) || '
    AND coalesce(ies1.custodieintrare,0) = 1
    AND ies.operat = 1 AND ies.anulat = 0
    AND ae.DataDoc ' || sPer || coalesce(CASE WHEN gOpt1 THEN ' AND i.DataDoc ' || sPer END,'');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect1, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect2, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect3, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmarireincasari_processlist</obj_name>
  <obj_hashval>d2fc83c1e6e9d641bc64e1c05bf5cbe9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmarireincasari_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplCols   VARCHAR := '';
  gSuplJoins  VARCHAR := '';

  sInsert     TEXT;
  sSelect     TEXT;
  sSelect_Ini TEXT;
  sAux        TEXT         := '';
  An          numeric(4,0);
  Luna        numeric(2,0);
  dDataS      DATE         := (SELECT pkg_list_alegperioada_getDataS.WME_RESULT FROM pkg_list_alegperioada_getDataS(NULL,NULL));
  dDataF      DATE         := (SELECT pkg_list_alegperioada_getDataF.WME_RESULT FROM pkg_list_alegperioada_getDataF(NULL,NULL));
  AnS         numeric(4,0) := EXTRACT(YEAR  FROM dDataS);
  LunaS       numeric(2,0) := EXTRACT(MONTH FROM dDataS);
  ZiS         numeric(2,0) := EXTRACT(DAY   FROM dDataS);
  sDataS      varchar      := To_Char(dDataS, 'dd.mm.yyyy');
  sDataF      varchar      := To_Char(dDataF, 'dd.mm.yyyy');
BEGIN
  --Stef 23.06.2023
  --PERFORM PKG_GLOBALS_SetDebugMode(TRUE);
  gSuplCols :=
    'npart npart, nmonede mon, nclasep clsp, nagenda ag, nlocalit locS, njudet jud, npers agent, npers agent_inc,'||
    'nsubunit substingatori, nsubunit substinsi, ntipsedii ts';

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NAGENDA'   , 'SSOC'     , 'SSOC.CODPART = NPART.CODPART AND SSOC.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(SSOC.INACTIV, 0) = 0');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPERS'     , 'PAG'      , 'PAG.CODPERS = SSOC.CODAGENT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI'    , 'STINS_IES', 'STINSI.CODDOC = STINS_IES.CODIES AND STINSI.TIPDOC = STINS_IES.TIPDOC', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NC'        , 'STINS_NC' , 'STINSI.CODDOC = STINS_NC.CODNC AND STINSI.TIPDOC = 35', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'TREZOR1'   , 'STINS_TR1', 'STINSI.CODDOC = STINS_TR1.CODTREZOR1 AND STINSI.TIPDOC IN (29,30,31,33)', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'TREZOR'    , 'STINS_TR' , 'STINS_TR.CODTREZOR = STINS_TR1.CODTREZOR', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMPENS'   , 'STINS_C'  , 'STINSI.CODDOC = STINS_C.CODCOMPENS AND STINSI.TIPDOC = 28', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'TREZOR1'   , 'STING_TR1', 'STINGATORI.CODDOC1 = STING_TR1.CODTREZOR1 AND STINGATORI.TIPDOC IN (29,30,31,33)', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'TREZOR'    , 'STING_TR' , 'STINGATORI.CODDOC  = STING_TR.CODTREZOR AND STINGATORI.TIPDOC = STING_TR.TIPDOC', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMPENS'   , 'STING_C'  , 'STINGATORI.CODDOC = STING_C.CODCOMPENS AND STINGATORI.TIPDOC = 28', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'DOCCARNETE', 'STINS_CC' , 'STINS_CC.CODCARNET = STINSI.CARNETDOC', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'DOCCARNETE', 'STING_DC' , 'STING_DC.CODCARNET = STINGATORI.CARNETDOC', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'OBLIGPIF'  , 'STING_OBL', 'STING_OBL.CODOBLIGPIF = STINGATORI.CODOBLIGPIF', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'GENERAL'   , 'STING_GEN', 'STING_GEN.CODGENERAL = STING_OBL.CODGENERAL', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'OBLIGPIF'  , 'STINS_OBL', 'STINS_OBL.CODOBLIGPIF = STINSI.CODOBLIGPIF', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'GENERAL'   , 'STINS_GEN', 'STINS_GEN.CODGENERAL = STINS_OBL.CODGENERAL', 1);

  CALL pkg_list_struct_getsuplcols( aLISTID, aLISTVER, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config('PKG_LIST_BASE_URMARIREINCASARI.gSuplCols',gSuplCols,false);

  select  pkg_setluni_GetLunaInitiala.an , pkg_setluni_GetLunaInitiala.luna from pkg_setluni_GetLunaInitiala(an, luna) into an,luna;

  IF ZiS &lt;&gt; 1 THEN
    sAux := '  -
      (
        SELECT Coalesce(sum(s.valoare), 0)
        FROM stingere s
          inner join obligpif o on s.codstingatorpif = o.codobligpif
          inner join general g on o.codgeneral = g.codgeneral
          LEFT JOIN trezor1 t1 on g.coddoc = t1.codtrezor1
          LEFT JOIN compens c ON g.coddoc = c.codcompens
        WHERE s.codstinspif = ol.codobligpif
          AND ( (g.tipdoc &lt;&gt; 28 AND t1.datadoc &lt; TO_DATE('''||sDataS||''',''dd.mm.yyyy'') and t1.luna = '||To_Char(LunaS)||' and t1.an = '||To_Char(AnS)||') OR
                (g.tipdoc  = 28 AND c.datadoc  &lt; TO_DATE('''||sDataS||''',''dd.mm.yyyy'') and c.luna  = '||To_Char(LunaS)||' and c.an  = '||To_Char(AnS)||') )
      )  -
      (
        SELECT Coalesce(sum(es.valoare), 0)
        FROM emulare e
          INNER JOIN emulare1 e1 on e1.codemulare = e.codemulare
          INNER JOIN emulstingeri es ON es.codemulstingere = e1.codemulstingere
          INNER JOIN obligpif o ON o.codobligpif = es.codobligpif
          INNER JOIN general g ON g.codgeneral = o.codgeneral
          INNER JOIN iesiri i ON  g.coddoc = i.codies AND g.tipdoc = i.tipdoc
          LEFT JOIN  iesiri m ON m.codies = e.codmonetar
        WHERE o.codobligpif = ol.codobligpif
          AND E.DATABON &lt; TO_DATE('''||sDataS||''',''dd.mm.yyyy'')
          AND (M.CODIES IS NULL OR I.An*12+I.LUNA &gt;= '||To_Char(LunaS*12+AnS)||')
      )';
  END IF;

  sInsert := 'INSERT INTO '||tmpName ||'(
    NAV_CodDoc, NAV_CodDoc1, NAV_TipDoc, DOCSTINS, TOTAL_DOCUMENT, VAL_NESTINSA_DOCUMENT, VAL_STINGATOR, SOLD_DOC, DOCSTINGATOR, PARTENER, LOCATIE,
    DATADECONT, DATAV, DATA_STINS, ORDINE, TERMEN, MONEDA, SUBUNITATEA, SUBUNITATEA_ST, SCADENTA, DIFZILE,
    INC_VAL, INC_VAL1, INC_VAL2, INC_VAL3, INC_VAL4, INC_VAL5,
    DEPZILE, AGENT, AGENT_INCASATOR,
    CONT, TIPDOCSTINS, TIPDOCSTINGATOR, NRDOCSTINGATOR, LOCS, PROCTVAMEDIU'||gUserFields||')';

  sSelect := '
  WITH
  crs_sold as (
    SELECT
      ol.codobligpif codobligpif,
      ol.rest'||sAux||' rest
    FROM obligpifluna ol
      INNER JOIN obligpif op on ol.codobligpif = op.codobligpif
      INNER JOIN general g on op.codgeneral = g.codgeneral
    WHERE g.tipdoc IN (19, 20, 21, 22, 26, 35)
      AND ol.luna + ol.an*12 = '||To_Char(AnS*12+Lunas-1)||'
  ),
  stinsi as (
    SELECT
      I.CodIes CodDoc, I.TipDoc, I.CodIes, i.carnetdoc,
      obstins.codgeneral codgeneral, CASE WHEN Coalesce(i.initializari, 0) = 0 THEN i.prefixdoc ELSE ''sold initial '' END||i.nrdoc||''/''||to_char(i.datadoc, ''DD.MM.YYYY'') docstins,
      i.datadoc data_stins, i.subunitatea, g.moneda, obstins.codobligpif, obstins.valoare, obstins.codpart, i.codlocatie, obstins.termen, i.agent,
      obstins.icont, i.an*12+i.luna al, obstins.semnificatie, CASE WHEN Coalesce(i.initializari, 0) = 0 THEN i.prefixdoc ELSE ''sold initial '' END TipDocStinsi,
      round(i.tvadoc/Coalesce(NULLIF(CASE i.tipdoc WHEN 22 THEN i.valdoc ELSE i.valdoc-i.tvadoc END, 0), 1)*100,2) TVAMediu
    FROM iesiri i
      INNER JOIN general   g      ON g.coddoc     = i.codies and g.tipdoc = i.tipdoc and g.semnificatie &lt;&gt; 500
      INNER JOIN obligpif obstins ON g.codgeneral = obstins.codgeneral
    WHERE Coalesce(i.anulat, 0) = 0
      AND i.datadoc &lt;= TO_DATE('''||sDataF||''',''dd.mm.yyyy'')
    UNION ALL
    SELECT
      NC.CodNc CodDoc, 35 TipDoc, 0 CodIes, nc.carnetdoc,
      obstins.codgeneral codgeneral, ''NC ''  ||nc.nrdoc||''/''||to_char(nc.datadoc, ''dd.mm.yyyy'') docstins,
      nc.datadoc data_stins, nc.subunitatea, g.moneda, obstins.codobligpif, obstins.valoare, obstins.codpart, 0 codlocatie, obstins.termen, nc1.agent,
      obstins.icont, nc1.an*12+nc1.luna al, obstins.semnificatie, ''NC'' tipdocstinsi,
      0 TVAMediu
    FROM nc
      INNER JOIN nc1 ON nc1.codnc = nc.codnc
      INNER JOIN general g ON g.coddoc = nc1.codnc1 AND g.tipdoc = 35 AND g.semnificatie = 1200
      INNER JOIN obligpif obstins ON g.codgeneral = obstins.codgeneral
    WHERE nc.datadoc &lt;= TO_DATE('''||sDataF||''',''dd.mm.yyyy'')
    UNION ALL
    SELECT
      tr1.CodTrezor1 CodDoc, tr.TipDoc, 0 CodIes, tr1.carnetdoc,
      obstins.codgeneral codgeneral, tr1.doc ||tr1.nrdoc||''/''||to_char(tr1.datadoc, ''dd.mm.yyyy'') docstins,
      tr1.datadoc data_stins, tr.subunitatea, g.moneda, obstins.codobligpif, obstins.valoare, obstins.codpart, tr1.codlocatie, obstins.termen, Coalesce(NULLIF(tr1.agent,0),tr.agent,0) agent,
      obstins.icont,tr1.an*12+tr1.luna al,obstins.semnificatie, tr1.doc tipdocstinsi,
      0 TVAMediu
    FROM trezor1 tr1
      INNER JOIN general g ON g.coddoc = tr1.codtrezor1 AND g.tipdoc in (29,30,31) AND g.semnificatie &lt;&gt; 500
      INNER JOIN obligpif obstins ON g.codgeneral = obstins.codgeneral
      INNER JOIN trezor tr ON tr1.codtrezor = tr.codtrezor
    WHERE Coalesce(tr1.anulat, 0) = 0 AND Coalesce(tr1.OBIECTTRANZ,0) &lt;&gt; 3
      AND tr1.datadoc &lt;= TO_DATE('''||sDataF||''',''dd.mm.yyyy'')
      AND obstins.semnificatie IN (330,410,600)
    UNION ALL
    SELECT
      cstins.CodCompens CodDoc, 28 TipDoc, 0 CodIes, cstins.carnetdoc,
      obstins.codgeneral codgeneral, ''PV '' ||cstins.nrdoc||''/''||to_char(cstins.datadoc, ''dd.mm.yyyy'') docstins,
      cstins.datadoc data_stins, cstins.subunitatea, g.moneda, obstins.codobligpif, obstins.valoare, obstins.codpart, 0 codlocatie, obstins.termen, cstins.agent,
      obstins.icont,cstins.an*12+cstins.luna al, obstins.semnificatie, ''PV'' tipdocstinsi,
      0 TVAMediu
    FROM compens cstins
      INNER JOIN general g ON g.coddoc = cstins.codcompens and g.semnificatie &lt;&gt; 500
      INNER JOIN obligpif obstins ON g.codgeneral = obstins.codgeneral
    WHERE g.tipdoc = 28
      AND cstins.datadoc &lt;= TO_DATE('''||sDataF||''',''dd.mm.yyyy'')
  ),
  stingatori as (
    SELECT
      t.codtrezor, CASE os.semnificatie WHEN 1303 THEN os.codobligasociat ELSE os.codobligpif END codstinspif, case when t1.obiecttranz = 1 then -1 else 1 end * s.valoare valstins, o.CodObligPIF, o.Codgeneral, t.codtrezor CodDoc, t1.codtrezor1 CodDoc1, g.TipDoc, t1.carnetdoc,
      t1.doc||'' '' ||t1.nrdoc||''/''||to_char(t1.datadoc, ''dd.mm.yyyy'') DOCSTINGATOR, o.codpart,
      Coalesce(t1.DATADECONT,t.datadoc) DATADECONT, t1.datadoc AS DATAV, Coalesce(NULLIF(t1.agent,0),t.agent,0) agent, t.Subunitatea, t1.doc tipdocstingatori, t1.nrdoc nrdocstingatori,
      CASE os.semnificatie WHEN 1303 THEN 1 ELSE 0 END stingLit
    FROM trezor1 t1
      INNER JOIN trezor t ON t1.codtrezor = t.codtrezor
      INNER JOIN general g ON t1.codtrezor1 = g.coddoc and g.tipdoc = t.tipdoc
      INNER JOIN obligpif o ON o.codgeneral = g.codgeneral
      INNER JOIN stingere s ON s.codstingatorpif = o.codobligpif
      INNER JOIN obligpif os ON os.codobligpif = s.codstinspif
    WHERE T.TIPDOC IN (29,30,31,33)
      AND g.semnificatie IN (400,420,750,751)--AND t1.TipTranz IN (0,1) AND t1.ObiectTranz IN (0,1) AND t1.TipTranz &lt;&gt; t1.ObiectTranz
      AND T1.DATADOC BETWEEN TO_DATE('''||sDataS||''',''dd.mm.yyyy'') AND TO_DATE('''||sDataF||''',''dd.mm.yyyy'')
      AND Coalesce(t1.Initializari,0) = 0 '||
      CASE
        WHEN NOT (SELECT pkg_list_alegperioada_optiunea3.WME_RESULT FROM pkg_list_alegperioada_optiunea3(NULL,NULL))
        THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('T')
        ELSE ''
      END ||'
    UNION ALL
    SELECT
      0 codtrezor, s.codstinspif, CASE WHEN os.valoare * s.valoare &lt; 0 THEN -1 ELSE 1 END * s.valoare valstins, o.CodObligPIF, o.Codgeneral, c.codcompens CodDoc, NULL CodDoc1, g.TipDoc, c.carnetdoc,
      ''PV''||'' '' ||c.nrdoc||''/''||to_char(c.datadoc, ''dd.mm.yyyy'') DOCSTINGATOR, o.codpart,
      c.datadoc DATADECONT, c.datadoc AS DATAV, c.Agent, c.Subunitatea, ''PV'' tipdocstingatori, c.nrdoc nrdocstingatori,
      0 stingLit
    FROM compens c
      INNER JOIN general g ON g.coddoc = c.codcompens
      INNER JOIN obligpif o ON o.codgeneral = g.codgeneral
      INNER JOIN stingere s ON s.codstingatorpif = o.codobligpif
      INNER JOIN obligpif os ON os.codobligpif = s.codstinspif
    WHERE C.DATADOC BETWEEN TO_DATE('''||sDataS||''',''dd.mm.yyyy'') AND TO_DATE('''||sDataF||''',''dd.mm.yyyy'')
      AND G.TipDoc = 28
      AND os.semnificatie NOT IN (410)
      AND o.icont IN (3,5,7,10,11,18) '||
      CASE
        WHEN NOT (SELECT pkg_list_alegperioada_optiunea3.WME_RESULT FROM pkg_list_alegperioada_optiunea3(NULL,NULL))
        THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('C')
        ELSE ''
      END ||'
    UNION ALL
    SELECT
      0 codtrezor, o.codobligpif codstinspif, es.valoare valstins, 0 CodObligPIF, 0 Codgeneral, e.codemulare CodDoc, NULL CodDoc1, 64 TipDoc, i.carnetdoc,
      ''BON''||'' '' ||e.nrbon||''/''||to_char(e.databon, ''dd.mm.yyyy'') DOCSTINGATOR, o.codpart,
      e.databon DATADECONT, e.databon AS DATAV, 0 Agent, NULL Subunitatea, ''BON'' tipdocstingatori, e.nrbon nrdocstingatori,
      0 stingLit
    FROM emulare e
      INNER JOIN emulare1 e1 on e1.codemulare = e.codemulare
      INNER JOIN emulstingeri es ON es.codemulstingere = e1.codemulstingere
      INNER JOIN obligpif o ON o.codobligpif = es.codobligpif
      INNER JOIN general g ON g.codgeneral = o.codgeneral
      INNER JOIN iesiri i ON  g.coddoc = i.codies AND g.tipdoc = i.tipdoc
    WHERE E.DATABON BETWEEN TO_DATE('''||sDataS||''',''dd.mm.yyyy'') AND TO_DATE('''||sDataF||''',''dd.mm.yyyy'') '||
      CASE
        WHEN NOT (SELECT pkg_list_alegperioada_optiunea3.WME_RESULT FROM pkg_list_alegperioada_optiunea3(NULL,NULL))
        THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('I')
        ELSE ''
      END ||'
    UNION ALL
    SELECT
      0 codtrezor, o.codobligpif codstinspif, e.valoare valstins, 0 CodObligPIF, 0 Codgeneral, e.codemulare CodDoc, NULL CodDoc1, 64 TipDoc, i.carnetdoc,
      ''BON''||'' '' ||e.nrbon||''/''||to_char(e.databon, ''dd.mm.yyyy'') DOCSTINGATOR, o.codpart,
      e.databon DATADECONT, e.databon AS DATAV, 0 Agent, NULL Subunitatea, ''BON'' tipdocstingatori, e.nrbon nrdocstingatori,
      0 stingLit
    FROM emulare e
      INNER JOIN iesiri i ON i.codies = e.codies
      INNER JOIN general g ON g.coddoc = i.codies AND g.tipdoc = i.tipdoc
      INNER JOIN obligpif o ON o.codgeneral = g.codgeneral
    WHERE E.DATABON BETWEEN TO_DATE('''||sDataS||''',''dd.mm.yyyy'') AND TO_DATE('''||sDataF||''',''dd.mm.yyyy'') '||
      CASE
        WHEN NOT (SELECT pkg_list_alegperioada_optiunea3.WME_RESULT FROM pkg_list_alegperioada_optiunea3(NULL,NULL))
        THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('I')
        ELSE ''
      END ||'
  )
  SELECT
    CASE WHEN tmps.codsubunit IS NOT NULL THEN stingatori.coddoc END NAV_CodDoc, CASE WHEN tmps.codsubunit IS NOT NULL THEN stingatori.coddoc1 END NAV_CodDoc1, CASE WHEN tmps.codsubunit IS NOT NULL THEN stingatori.tipdoc END NAV_TipDoc,
    CASE stingatori.stingLit WHEN 1 THEN ''Litigiu '' ELSE '''' END||stinsi.docstins, stinsi.valoare + Coalesce(e.valoare,0) TOTAL_DOCUMENT,
    Coalesce(
      stingatori.valstins + CASE Coalesce(crs_sold.rest,0) WHEN 0 THEN stinsi.valoare ELSE crs_sold.rest END + Coalesce(e.valoare,0) -
      SUM(stingatori.valstins) over (PARTITION BY stingatori.codstinspif ORDER BY stingatori.codgeneral ROWS BETWEEN unbounded preceding AND CURRENT ROW )
      , 0
    ) VAL_NESTINSA_DOCUMENT,
    stingatori.valstins VAL_STINGATOR,
    Coalesce(
      CASE Coalesce(crs_sold.rest,0) WHEN 0 THEN stinsi.valoare ELSE crs_sold.rest END + Coalesce(e.valoare,0) -
      SUM(stingatori.valstins) over (PARTITION BY stingatori.codstinspif ORDER BY stingatori.codgeneral ROWS BETWEEN unbounded preceding AND CURRENT ROW )
      , 0
    ) SOLD_DOC,
    stingatori.DOCSTINGATOR, npart.den_part, ag.obs, stingatori.DATADECONT, stingatori.DATAV, stinsi.DATA_STINS, stingatori.codgeneral ORDINE, stinsi.TERMEN, mon.den_moneda,
    SubStinsi.den_subunit SUBUNITATEA, SubStingatori.den_subunit SUBUNITATEA_ST, stinsi.termen SCADENTA, trunc(stingatori.DataV - stinsi.data_stins::date) DIFZILE,
    stingatori.valstins INC_VAL,
    CASE WHEN trunc(stingatori.DataV - stinsi.data_stins::date) &lt;=               1 THEN stingatori.valstins ELSE 0 END INC_VAL1,
    CASE WHEN trunc(stingatori.DataV - stinsi.data_stins::date) BETWEEN  2 AND  30 THEN stingatori.valstins ELSE 0 END INC_VAL2,
    CASE WHEN trunc(stingatori.DataV - stinsi.data_stins::date) BETWEEN 31 AND  45 THEN stingatori.valstins ELSE 0 END INC_VAL3,
    CASE WHEN trunc(stingatori.DataV - stinsi.data_stins::date) BETWEEN 46 AND  60 THEN stingatori.valstins ELSE 0 END INC_VAL4,
    CASE WHEN trunc(stingatori.DataV - stinsi.data_stins::date) &gt;               60 THEN stingatori.valstins ELSE 0 END INC_VAL5,
    CASE WHEN trunc(stingatori.dataV - stinsi.termen::date) &gt; 0 then trunc(stingatori.dataV - stinsi.termen::date) else 0 end DEPZILE,
    agent.nume||'' ''||agent.prenume AGENT, agent_inc.nume||'' ''||agent_inc.prenume AGENT_INCASATOR,
    PKG_LIST_BASE_UTILS_decode_iCont(stinsi.icont, stinsi.codpart, stinsi.al, stinsi.semnificatie) AS cont, stinsi.tipdocstinsi,
    stingatori.tipdocstingatori, stingatori.nrdocstingatori,locS.den_localit, stinsi.TVAMediu '||gUserAlias||'
  FROM stingatori
    LEFT JOIN stinsi on stinsi.codobligpif = stingatori.codstinspif
    LEFT JOIN crs_sold on stinsi.codobligpif = crs_sold.codobligpif
    LEFT JOIN npers agent on agent.codpers = Coalesce(stinsi.agent,0)
    LEFT JOIN npers agent_inc on agent_inc.codpers = Coalesce(stingatori.agent,0)
    LEFT JOIN npart npart on npart.codpart = Coalesce(stinsi.codpart,stingatori.codpart)
    LEFT JOIN nclasep clsp on clsp.codclasep = Coalesce(npart.codclasa, 0)
    LEFT JOIN nagenda ag on ag.codagenda = Coalesce(stinsi.codlocatie,0)
    LEFT JOIN nmonede mon ON mon.codmoneda = Coalesce(stinsi.moneda,0)
    LEFT JOIN nsubunit SubStingatori ON stingatori.subunitatea = SubStingatori.codsubunit
    LEFT JOIN tmp_subunitdedicate tmps ON tmps.codsubunit = stingatori.subunitatea
    LEFT JOIN nsubunit SubStinsi ON stinsi.subunitatea = SubStinsi.codsubunit
    LEFT JOIN emulare e ON e.codies = stinsi.codies
    LEFT JOIN nlocalit locS on ag.codlocalit = locS.codlocalit
    LEFT JOIN njudet jud on locS.codjudet = jud.codjudet
    LEFT JOIN ntipsedii ts ON ts.codtipsediu = ag.codtipsediu'||
    gSuplJoins;

  sSelect_Ini := '
  WITH
  stingeri as (
    select stingere.*, general.codgeneral
    from stingere
      inner join obligpif on stingere.codstingatorpif = obligpif.codobligpif
      inner JOIN general ON obligpif.codgeneral = general.codgeneral
  ),
  stinsi as (
    SELECT
      i.codies coddoc, i.tipdoc, i.carnetdoc,
      obstins.codgeneral, ''sold initial ''||i.nrdoc||''/''||to_char(i.datadoc, ''DD.MM.YYYY'') docstins,
      i.datadoc data_stins, i.subunitatea, g.moneda, obstins.codobligpif, obstins.valoare, obstins.codpart, i.codlocatie, obstins.termen, i.agent,
      obstins.icont, i.an*12+i.luna al, obstins.semnificatie, i.prefixdoc tipdocstinsi,
      round(i.tvadoc/Coalesce(NULLIF(CASE i.tipdoc WHEN 22 THEN i.valdoc ELSE i.valdoc-i.tvadoc END, 0), 1)*100,2) TVAMediu
    FROM iesiri i
      INNER JOIN general g ON g.coddoc = i.codies and g.tipdoc = i.tipdoc and g.semnificatie &lt;&gt; 500
      INNER JOIN obligpif obstins ON g.codgeneral = obstins.codgeneral
    WHERE Coalesce(i.anulat, 0) = 0 and Coalesce(i.initializari, 0) = 1
      AND i.datadoc &lt;= TO_DATE('''||sDataF||''',''dd.mm.yyyy'')
  ),
  stingatori as (
    SELECT
      t.codtrezor, o.CodObligPIF, s.valoare valstins, o.Codgeneral, t.codtrezor CodDoc, t1.codtrezor1 CodDoc1, g.TipDoc, t1.carnetdoc,
      t1.doc||'' '' ||t1.nrdoc||''/''||to_char(t1.datadoc, ''dd.mm.yyyy'') DOCSTINGATOR, o.codpart,
      Coalesce(t1.DATADECONT,t.datadoc) DATADECONT, t1.datadoc AS DATAV, Coalesce(NULLIF(t1.agent,0),t.agent,0) agent, t.Subunitatea, O.Valoare, t1.doc tipdocstingatori, t1.nrdoc nrdocstingatori
    FROM trezor1 t1
      INNER JOIN trezor t ON t1.codtrezor = t.codtrezor
      INNER JOIN general g ON t1.codtrezor1 = g.coddoc and g.tipdoc = t.tipdoc
      INNER JOIN obligpif o ON o.codgeneral = g.codgeneral
      INNER JOIN stingere s ON s.codstingatorpif = o.codobligpif
    WHERE T.TIPDOC IN (29,30,31,33)
      AND g.semnificatie IN (400,420,750,751)
      AND Coalesce(t1.Initializari,0) = 1 '||
      CASE
        WHEN NOT (SELECT pkg_list_alegperioada_optiunea3.WME_RESULT FROM pkg_list_alegperioada_optiunea3(NULL,NULL))
        THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('T')
        ELSE ''
      END ||'
  )
  SELECT
    CASE WHEN tmps.codsubunit IS NOT NULL THEN stingatori.coddoc END NAV_CodDoc, CASE WHEN tmps.codsubunit IS NOT NULL THEN stingatori.coddoc1 END NAV_CodDoc1, CASE WHEN tmps.codsubunit IS NOT NULL THEN stingatori.tipdoc END NAV_TipDoc,
    stinsi.DOCSTINS,
    stinsi.valoare + SUM(stingatori.valoare) over (PARTITION BY stingeri.codstinspif ORDER BY stingeri.codgeneral ROWS BETWEEN unbounded preceding AND CURRENT ROW ) TOTAL_DOCUMENT,
    stinsi.valoare + SUM(stingatori.valoare) over (PARTITION BY stingeri.codstinspif ORDER BY stingeri.codgeneral ROWS BETWEEN unbounded preceding AND CURRENT ROW ) VAL_NESTINSA_DOCUMENT,
    stingatori.valoare VAL_STINGATOR,
    stinsi.valoare - stingatori.valoare + SUM(stingatori.valoare) over (PARTITION BY stingeri.codstinspif ORDER BY stingeri.codgeneral ROWS BETWEEN unbounded preceding AND CURRENT ROW ) SOLD_DOC,
    stingatori.DOCSTINGATOR, npart.den_part, ag.obs, stingatori.DATADECONT, stingatori.DATAV, stinsi.DATA_STINS, stingatori.codgeneral ORDINE, stinsi.TERMEN, mon.den_moneda,
    SubStinsi.den_subunit SUBUNITATEA, SubStingatori.den_subunit SUBUNITATEA_ST, stinsi.termen SCADENTA, trunc(stingatori.DataV - stinsi.data_stins::date) DIFZILE,
    stingatori.valstins INC_VAL,
    CASE WHEN trunc(stingatori.DataV - stinsi.data_stins::date) &lt;=              1 THEN stingatori.valstins ELSE 0 END INC_VAL1,
    CASE WHEN trunc(stingatori.DataV - stinsi.data_stins::date) BETWEEN  2 AND 30 THEN stingatori.valstins ELSE 0 END INC_VAL2,
    CASE WHEN trunc(stingatori.DataV - stinsi.data_stins::date) BETWEEN 31 AND 45 THEN stingatori.valstins ELSE 0 END INC_VAL3,
    CASE WHEN trunc(stingatori.DataV - stinsi.data_stins::date) BETWEEN 46 AND 60 THEN stingatori.valstins ELSE 0 END INC_VAL4,
    CASE WHEN trunc(stingatori.DataV - stinsi.data_stins::date) &gt;              60 THEN stingatori.valstins ELSE 0 END INC_VAL5,
    case when trunc(stingatori.dataV - stinsi.termen::date) &gt; 0 then trunc(stingatori.dataV - stinsi.termen::date) else 0 end DEPZILE,
    agent.nume||'' ''||agent.prenume AGENT, agent_inc.nume||'' ''||agent_inc.prenume AGENT_INCASATOR,
    PKG_LIST_BASE_UTILS_decode_iCont(stinsi.icont, stinsi.codpart, stinsi.al, stinsi.semnificatie) AS cont, stinsi.tipdocstinsi,
    stingatori.tipdocstingatori, stingatori.nrdocstingatori, locS.den_localit, stinsi.TVAMediu '||gUserAlias||'
  FROM stingatori
    LEFT JOIN stingeri on stingeri.codstingatorpif = stingatori.codobligpif
    LEFT JOIN stinsi on stingeri.codstinspif = stinsi.codobligpif
    LEFT JOIN npers agent on agent.codpers = Coalesce(stinsi.agent,0)
    LEFT JOIN npers agent_inc on agent_inc.codpers = Coalesce(stingatori.agent,0)
    LEFT JOIN npart npart on npart.codpart = Coalesce(stinsi.codpart,stingatori.codpart)
    LEFT JOIN nclasep clsp on clsp.codclasep = Coalesce(npart.codclasa, 0)
    LEFT JOIN nagenda ag on ag.codagenda = Coalesce(stinsi.codlocatie,0)
    LEFT JOIN nmonede mon ON mon.codmoneda = Coalesce(stinsi.moneda,0)
    LEFT JOIN nsubunit SubStingatori ON stingatori.subunitatea = SubStingatori.codsubunit
    LEFT JOIN nsubunit SubStinsi ON stinsi.subunitatea = SubStinsi.codsubunit
    LEFT JOIN tmp_subunitdedicate tmps ON tmps.codsubunit = stingatori.subunitatea
    LEFT JOIN nlocalit locS on ag.codlocalit = locS.codlocalit
    LEFT JOIN njudet jud on locS.codjudet = jud.codjudet
    LEFT JOIN ntipsedii ts ON ts.codtipsediu = ag.codtipsediu'||
    gSuplJoins;

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert||sSelect, aListID, aListVer);

  IF (SELECT pkg_list_alegperioada_optiunea1.WME_RESULT FROM pkg_list_alegperioada_optiunea1(NULL,NULL)) THEN
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert||sSelect_Ini, aListID, aListVer);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmbuget_processlist</obj_name>
  <obj_hashval>43f9fc4a46c702581bea5cf55dbe0c07</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmbuget_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplCols   VARCHAR := '';
  gSuplJoins  VARCHAR := '';

  sInsert varchar;
  sSelect varchar;
  sFiltru varchar;
begin
  --Bogdan 22.09.2020
  gSuplCols := 'NARTOBJ OBJ, NART ART, NARTOBJ IMB, comanda cmd, intrari intr';

  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config ('PKG_LIST_BASE_URMBUGET.gSuplCols',gSuplCols,false);

  sFiltru := '';
  IF Length (current_setting ('PKG_LIST_BASE_URMBUGET.pFiltru', true)) &gt; 0 THEN
    sFiltru := ' and mf.nrinventar in ('|| coalesce (current_setting ('PKG_LIST_BASE_URMBUGET.pFiltru', true) ,'')|| ') ';
  END IF;
  sInsert := 'INSERT INTO '|| TMPNAME
            || '(
            NAV_CodDoc,
            NAV_TipDoc,
            NrInventar,
            Articol,
            TipDocument,
            NrDoc,
            DataDoc,
            ValBuget,
            ValDoc,
            Rest_fake1,
            Obs,
            TipDocumentCmd,
            NrDocCmd,
            DataDocCmd,
            ValDocCmd,
            Rest_fake2,
            ObsCmd,
            Stadiu,
            IndexLocal,
            Imbunatatire,
            Partener '
            || coalesce (gUserFields ,'')
            || ')
          ';
  sSelect := '
          SELECT coalesce (NEST.codintr, NEST.CODCOMANDA) ,
            coalesce (NEST.TIPintr, NEST.TIPCOMANDA) ,
            MF.NrInventar,
            OBJ.DENUMIRE Articol,
            case when nest.nrdoc is null then '''' else ''Factura intrare'' end TipDocument,
            NEST.NrDoc,
            NEST.DataDoc,
            0 ValBuget,
            NEST.ValDoc,
            - NEST.ValDoc RestFake1,
            NEST.Obs,
            case when nest.nrdoccmd is null then '''' else ''Comanda furnizor'' end TipDocumentCmd,
            NEST.NrDocCmd,
            NEST.DataDocCmd,
            NEST.ValDocCmd,
            case when nest.codintr &gt; 0 then - NEST.ValDoc
                 else - coalesce (NEST.ValDocCmd, NEST.ValDoc)
            end RestFake2,
            NEST.ObsCmd,
            '' '' Stadiu,
            2     IndexLocal,
            NEST.IMBUNATATIRE,
            NEST.Partener '
              || coalesce (gUserAlias ,'')|| '
          FROM mifix                          mf
            inner join bugetmf                b   on b.codmifix    = mf.codmifix
            inner join mifix1                 mf1 on mf1.codmifix  = mf.codmifix
            inner join nirstoc                ns  on ns.codnirstoc = mf1.codnirstoc
            inner join nartobj                obj on obj.codobiect = ns.codobiect
            left join (select cmd.codmifix   codmfcmd,
                              cmd.nrdoc      nrdoccmd,
                              cmd.datadoc    datadoccmd,
                              cmd.valdoc     valdoccmd,
                              cmd.obs        obscmd,
                              coalesce (cmd.den_part,intr.den_part) partener,
                              intr.codmifix  codmfintr,
                              intr.nrdoc,
                              intr.datadoc,
                              intr.valdoc,
                              intr.obs,
                              coalesce (cmd.denumire,intr.denumire) imbunatatire,
                              cmd.codcomanda,
                              cmd.tipdoc   tipcomanda,
                              intr.codintr,
                              intr.tipdoc  tipintr
                       from (select c1.codcomanda1,
                                    c1.codmifix,
                                    l.codintr1,
                                    coalesce (l.cant, (c1.cantacceptat - coalesce (storno.cant,0))) * c1.pu * (case when coalesce (c.moneda,0) = 0 then 1
                                                                                                                    else coalesce (c.curs,1) end) valdoc,
                                    p.den_part,
                                    obj.denumire,
                                    c.obs,
                                    c.datadoc,
                                    c.nrdoc,
                                    c.codcomanda,
                                    c.tipdoc
                             from comanda1                           c1
                               inner join comanda                    c   on c.codcomanda      = c1.codcomanda
                               inner join npart                      p   on p.codpart         = c.partener
                               inner join nartobj                    obj on obj.codobiect     = c1.codobiect
                               inner join bugetmf                    b   on b.codmifix        = c1.codmifix
                               inner join mifix                      mf  on mf.codmifix       = b.codmifix
                               INNER JOIN (SELECT MIN (DATABUGET) DATABUGET, CODBUGETMF FROM BUGETMF1 GROUP BY CODBUGETMF) DATAREF ON DATAREF.CODBUGETMF = B.CODBUGETMF
                               left join intrlink                    l   on l.codliniecomanda = c1.codcomanda1
                               left join (select l.codliniecomanda, sum (l.cant) cant from cmdlivrlink l group by l.codliniecomanda) storno on storno.codliniecomanda = c1.codcomanda1
                             where
                               c.tipdoc = 8
                               and coalesce (c.anulat,0) = 0
                               and c.datadoc &gt;= dataref.databuget '
                               || coalesce (sFiltru,'')
                        || ') cmd
                            full join (select l.codliniecomanda codcomanda1,
                                              i1.codmifix,
                                              i1.codintr1,
                                              i1.cant * i1.pu * (case when coalesce (i.moneda,0) = 0 then 1 else coalesce (i.curs,1) end) valdoc,
                                              p.den_part,
                                              obj.denumire,
                                              i.obs,
                                              i.datadoc,
                                              i.nrdoc,
                                              i.codintr,
                                              i.tipdoc
                                       from intrari1                           i1
                                         inner join intrari                    i   on i.codintr     = i1.codintr
                                         inner join npart                      p   on i.partener    = p.codpart
                                         inner join nartobj                    obj on obj.codobiect = i1.codobiect
                                         inner join bugetmf                    b   on b.codmifix    = i1.codmifix
                                         INNER JOIN (SELECT MIN (DATABUGET) DATABUGET, CODBUGETMF FROM BUGETMF1 GROUP BY CODBUGETMF) DATAREF ON DATAREF.CODBUGETMF = B.CODBUGETMF
                                         inner join mifix        mf      on mf.codmifix    = b.codmifix
                                         left join intrlink      l       on i1.codintr1    = l.codintr1
                                         left join comanda1      c1      on c1.codcomanda1 = l.codliniecomanda
                                         left join comanda       c       on c1.codcomanda  = c.codcomanda
                                       where
                                         coalesce (i.anulat,0) = 0
                                         and i.datadoc &gt;= dataref.databuget '
                                         || coalesce (sFiltru,'')
                                  || ') intr on intr.codcomanda1 = cmd.codcomanda1
                                            and intr.codintr1    = cmd.codintr1
                                            and cmd.codmifix     = intr.codmifix
                      ) nest       on nest.codmfintr = mf.codmifix or nest.codmfcmd = mf.codmifix
            left join comanda cmd  on cmd.codcomanda = nest.codcomanda
            left join intrari intr on intr.codintr   = nest.codintr '
            || coalesce (gSuplJoins,'')|| '
          where
            mf1.anstart * 12 + mf1.lunastart = (select max (anstart * 12 + lunastart) from mifix1 where codmifix = mf1.codmifix) '
            || coalesce (sFiltru,'')|| '
          UNION ALL
          SELECT NEST.CODCOMANDA,
                 NEST.TIPCOMANDA,
                 MF.NrInventar,
                 OBJ.DENUMIRE Articol,
                 ''''         TipDocument,
                 NEST.NrDoc,
                 NEST.DataDoc,
                 0 ValBuget,
                 NEST.ValDoc,
                 - NEST.ValDoc RestFake1,
                 NEST.Obs,
                 case when nest.nrdoccmd is null then '''' else ''Comanda furnizor'' end TipDocumentCmd,
                 NEST.NrDocCmd,
                 NEST.DataDocCmd,
                 NEST.ValDocCmd,
                 case when nest.codintr &gt; 0 then - NEST.ValDoc
                       else - coalesce (NEST.ValDocCmd, NEST.ValDoc)
                 end RestFake2,
                 NEST.ObsCmd,
                 '' '' Stadiu,
                 2     IndexLocal,
                 NEST.IMBUNATATIRE,
                 NEST.Partener '
                 || coalesce (gUserAlias ,'')|| '
          FROM mifix                           mf
            inner join bugetmf                 b   on b.codmifix    = mf.codmifix
            inner join mifix1                  mf1 on mf1.codmifix  = mf.codmifix
            inner join nirstoc                 ns  on ns.codnirstoc = mf1.codnirstoc
            inner join nartobj                 obj on obj.codobiect = ns.codobiect
            inner join (select cmd.codmifix    codmfcmd,
                               cmd.nrdoc       nrdoccmd,
                               cmd.datadoc     datadoccmd,
                               cmd.valdoc      valdoccmd,
                               cmd.obs         obscmd,
                               cmd.den_part    partener,
                               NULL::numeric   codmfintr,
                               NULL::numeric   nrdoc,
                               NULL::date      datadoc,
                               NULL::numeric   valdoc,
                               NULL            obs,
                               cmd.denumire    imbunatatire,
                               cmd.codcomanda,
                               cmd.tipdoc      tipcomanda,
                               NULL::numeric   codintr,
                               NULL::numeric   tipintr
                        from (select c1.codcomanda1,
                                     c1.codmifix,
                                     null codintr1,
                                     (c1.cantacceptat - coalesce (storno.cant,0) - stinse.cant) * c1.pu * (case when coalesce (c.moneda,0) = 0 then 1
                                                                                                                else coalesce (c.curs,1) end) valdoc,
                                     p.den_part,
                                     obj.denumire,
                                     c.obs,
                                     c.datadoc,
                                     c.nrdoc,
                                     c.codcomanda,
                                     c.tipdoc
                              from comanda1         c1
                                inner join comanda  c   on c.codcomanda  = c1.codcomanda
                                inner join npart    p   on p.codpart     = c.partener
                                inner join nartobj  obj on obj.codobiect = c1.codobiect
                                inner join bugetmf  b   on b.codmifix    = c1.codmifix
                                inner join mifix    mf  on mf.codmifix   = b.codmifix
                                INNER JOIN (SELECT MIN (DATABUGET) DATABUGET, CODBUGETMF FROM BUGETMF1 GROUP BY CODBUGETMF) DATAREF ON DATAREF.CODBUGETMF = B.CODBUGETMF
                                inner join (select sum (l.cant) cant, l.codliniecomanda from intrlink l    group by l.codliniecomanda) stinse on stinse.codliniecomanda = c1.codcomanda1
                                left  join (select l.codliniecomanda, sum (l.cant) cant from cmdlivrlink l group by l.codliniecomanda) storno on storno.codliniecomanda = c1.codcomanda1
                              where
                                c.tipdoc = 8
                                and coalesce (c.anulat,0) = 0
                                and c.datadoc &gt;= dataref.databuget
                                and c1.cantacceptat - stinse.cant &gt; 0 '
                                || coalesce (sFiltru,'')
                         || ') cmd
                       ) nest on nest.codmfintr = mf.codmifix or nest.codmfcmd = mf.codmifix
            left join comanda cmd       on cmd.codcomanda = nest.codcomanda
            left join intrari intr      on intr.codintr   = nest.codintr '
            || coalesce (gSuplJoins ,'') || '
          where
            mf1.anstart * 12 + mf1.lunastart = (select max (anstart * 12 + lunastart) from mifix1 where codmifix = mf1.codmifix) '
            || coalesce (sFiltru,'')|| '
          UNION ALL
          SELECT
            BMF.CODBUGETMF,
            91,
            MF.NrInventar,
            OBJ.DENUMIRE   Articol,
            BMF1.DENUMIRE  TipDocument,
            0              NRDOC,
            BMF1.DataBuget DataDoc,
            BMF1.Valoare   ValBuget,
            0              ValDoc,
            CASE WHEN coalesce (bmf1.stadiu,0) IN (1,3) THEN BMF1.Valoare ELSE 0 END Rest_fake1,
            BMF1.Obs,
            ''''           TipDocumentCmd,
            0              NRDOCCMD,
            BMF1.DataBuget DataDocCmd,
            0              ValDocCmd,
            CASE WHEN coalesce (bmf1.stadiu,0) IN (1,3) THEN BMF1.Valoare ELSE 0 END      Rest_fake2,
            BMF1.Obs ObsCmd,
            case
              when coalesce (bmf1.stadiu,0) = 0 then ''...nedefinit...''
              when coalesce (bmf1.stadiu,0) = 1 then ''Aprobat''
              when coalesce (bmf1.stadiu,0) = 2 then ''Reanaliza''
              when coalesce (bmf1.stadiu,0) = 3 then ''Inchis''
            end  Stadiu,
            1    IndexLocal,
            '''' Imbunatatire,
            '''' Partener '
            || coalesce (gUserAlias ,'')|| '
          FROM BUGETMF1        BMF1
            INNER JOIN BUGETMF BMF  ON BMF.CODBUGETMF = BMF1.CODBUGETMF
            INNER JOIN MIFIX1  MF1  ON MF1.CODMIFIX   = BMF.CODMIFIX
            INNER JOIN MIFIX   MF   ON MF1.CODMIFIX   = MF.CODMIFIX
            INNER JOIN NIRSTOC NS   ON MF1.CODNIRSTOC = NS.CODNIRSTOC
            INNER JOIN NARTOBJ OBJ  ON OBJ.CODOBIECT  = NS.CODOBIECT
            INNER JOIN NART    ART  ON ART.CODARTICOL = OBJ.CODARTICOL
            LEFT JOIN NARTOBJ  IMB  ON IMB.CODOBIECT  = OBJ.CODOBIECT - OBJ.CODOBIECT
            left join comanda  cmd  on cmd.codcomanda = OBJ.CODOBIECT - OBJ.CODOBIECT
            left join intrari  intr on intr.codintr   = OBJ.CODOBIECT - OBJ.CODOBIECT '
              || coalesce (gSuplJoins ,'')|| '
          WHERE
            MF1.ANSTART * 12 + MF1.LUNASTART = (SELECT MAX (MF2.ANSTART * 12 + MF2.LUNASTART)
                                                FROM MIFIX1 MF2
                                                WHERE MF2.CODMIFIX = MF1.CODMIFIX AND MF2.ANSTART * 12 + MF2.LUNASTART &lt;= getAnLunaLucru()) '
            || coalesce (sFiltru,'');
  PERFORM LIST_EXECUTE_IMMEDIATE (coalesce (sInsert,'') || coalesce (sSelect,'') , aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmcomcli_processlist</obj_name>
  <obj_hashval>eded5d008fd3a0e5c3c29746e2ac4c0e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmcomcli_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplCols   VARCHAR := '';
  gSuplJoins  VARCHAR := '';

  sInsert        varchar;
  sSelect1       varchar;
  sSelect2       varchar;
  sSelect3       varchar;
  sJoinAux       varchar;
  sPer           varchar;
  sFiltruInchise varchar := '';
BEGIN
  --Florin14.12.2022 - fixat 56546
  --Florin 18.11.2022 - fixat 56301
  --Bogdan 01.09.2020
  gSuplCols :=
          'comanda c, comanda1 c1, nartobj o, nart art, num1 u, npart p, iesiri1 i1, iesiri i, comanda cst, comanda1 cst1, nclasea cla, nclasep clp, traseulivr t, '||
          'npart prod, ncarsupart cs, nparttr d, nagenda slvr, nlocalit llivr, njudet jlivr, ntari tlivr';

  call pkg_list_struct_startsuplcols();

  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDC'   , 'CV'   , 'CV.CODCOMANDA = C.CODCOMANDA'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDC1'  , 'CV1'  , 'CV1.CODCOMANDA1 = C1.CODCOMANDA1',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT' , 'OEXT.CODOBIECT = C1.CODOBIECT'   ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR' , 'OATR.CODOBIECT = C1.CODOBIECT'   ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CENTRECOST', 'CCOST', 'CCOST.CODCENTRU = coalesce(C1.CODCENTRU,0)');

  CALL pkg_list_struct_getsuplcols( aLISTID, aLISTVER, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config('PKG_LIST_BASE_URMCOMCLI.gSuplCols',gSuplCols,false);

  IF  (SELECT PKG_LIST_ALEGPERIOADA_getDataS.WME_RESULT FROM PKG_LIST_ALEGPERIOADA_getDataS(NULL,NULL))
      =
      (SELECT PKG_LIST_ALEGPERIOADA_getDataF.WME_RESULT FROM PKG_LIST_ALEGPERIOADA_getDataF(NULL,NULL))
  THEN
      sPer := '= TO_DATE(''' || coalesce(To_Char((SELECT PKG_LIST_ALEGPERIOADA_getDataS.WME_RESULT FROM PKG_LIST_ALEGPERIOADA_getDataS(NULL,NULL)), 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
  ELSE
      sPer := 'BETWEEN TO_DATE(''' || coalesce(To_Char((SELECT PKG_LIST_ALEGPERIOADA_getDataS.WME_RESULT FROM PKG_LIST_ALEGPERIOADA_getDataS(NULL,NULL)), 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')
                   AND TO_DATE(''' || coalesce(To_Char((SELECT PKG_LIST_ALEGPERIOADA_getDataF.WME_RESULT FROM PKG_LIST_ALEGPERIOADA_getDataF(NULL,NULL)), 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
  END IF;

  IF  NOT (SELECT PKG_LIST_ALEGPERIOADA_optiunea1.WME_RESULT FROM PKG_LIST_ALEGPERIOADA_optiunea1(NULL,NULL)) THEN
    sFiltruInchise := ' AND C.INCHISA = 0 ';
  END IF;

  sInsert := 'INSERT INTO ' || tmpName || '(
              NAV_CodDoc,NAV_TipDoc, Com, Doc, Part,
              Art, UM, Cant, CantCom, CantPrel, RestC, RestV,
              NrLinCom, Ordine,
              DenLaCli, CodLaCli,
              CodListat,
              SUBUNITATEA' || coalesce(gUserFields,'') || ')';
  sSelect1 := '
        SELECT
          c.codcomanda, c.tipdoc, c.PrefixDoc||c.NrDoc||''/''||c.Datadoc::date,c.PrefixDoc||c.NrDoc||''/''||c.Datadoc::date, p.Den_Part,
          o.denumire, u.den_um1, c1.cantacceptat/u.paritate, c1.cantacceptat/u.paritate, 0, c1.cantacceptat/u.paritate, c1.cantacceptat*coalesce(c1.pu,0),
          ROW_NUMBER() OVER (PARTITION BY C.CodComanda ORDER BY C1.CodComanda1 ASC), 0,
          COALESCE(ac.denumire,trad.denumiretrad,o.denumire), coalesce(ac.codextern,o.codextern),
          coalesce((CASE ac.tipcodafisat
                      WHEN 1 THEN gre.cod :: varchar
                      WHEN 2 THEN ac.codextern :: varchar
                      WHEN 3 THEN o.codextern :: varchar
                      WHEN 4 THEN o.codintern :: varchar
                      WHEN 5 THEN o.codvamal :: varchar
                      WHEN 6 THEN o.codplu :: varchar
                      WHEN 7 THEN o1.codextofe :: varchar
                    END),o.codextern),
          s.den_subunit ' || coalesce(gUserAlias,'') || '
        FROM comanda c
          INNER JOIN comanda1    c1    ON c1.codcomanda    = c.codcomanda
          INNER JOIN nartobj     o     ON o.codobiect      = c1.codobiect
          INNER JOIN nart        art   ON o.codarticol     = art.codarticol
          INNER JOIN num1        u     ON u.codum1         = c1.umsec
          INNER JOIN npart       p     ON p.codpart        = c.partener
          LEFT  JOIN nclasea     cla   on cla.codclasea    = art.clasa
          LEFT  JOIN nclasep     clp   on clp.codclasep    = p.codclasa
          LEFT  JOIN nagenda     slvr  on slvr.codagenda   = c.codlocatie
          LEFT  JOIN nlocalit    llivr ON llivr.codlocalit = slvr.codlocalit
          LEFT  JOIN njudet      jlivr ON jlivr.codjudet   = llivr.codjudet
          LEFT  JOIN ntari       tlivr ON tlivr.codtara    = llivr.codtara
          LEFT  JOIN traseulivr  t     on t.codtraseulivr  = slvr.codtraseu
          LEFT  JOIN npart       prod  ON prod.codpart     = o.codproducator
          LEFT  JOIN ncarsupart  cs    ON cs.codcarsupart  = o.codcaract
          LEFT  JOIN nparttr     d     ON d.codparttr      = c.delegat
          LEFT  JOIN nartcli     ac    ON ac.codobiect     = c1.codobiect AND ac.codpart = c.partener
          LEFT  JOIN nartobjtrad trad  ON trad.codlimba    = tlivr.codlimba and trad.codobiect = c1.codobiect
          LEFT  JOIN nechiv      e     ON e.codobiect      = c1.codobiect
          LEFT  JOIN grechiv     gre   ON gre.codgrechiv   = e.codgrupa
          LEFT  JOIN oferta1     o1    ON o1.codoferta1    = c1.codsursa
          LEFT  JOIN nsubunit    s     On s.codsubunit     = c.subunitatea
          -- joinuri false pt coloane suplimentare
          LEFT  JOIN iesiri      i     ON i.codies         = (c1.codcomanda-c1.codcomanda)
          LEFT  JOIN iesiri1     i1    ON i1.codies1       = (c1.codcomanda-c1.codcomanda)
          LEFT  JOIN comanda1    cst1  ON cst1.codcomanda1 = (c1.codcomanda-c1.codcomanda)
          LEFT  JOIN comanda     cst   ON cst.codcomanda   = (c1.codcomanda-c1.codcomanda)'
                || coalesce(gSuplJoins,'') || '
        WHERE c.tipdoc = 18 AND c.operat = 1 ' || coalesce(sFiltruInchise,'') || ' AND c.anulat = 0 '
              || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'C',NULL,NULL,NULL)),'') || '
            AND c.DataDoc ' || coalesce(sPer,'');
  sSelect2 := '
      SELECT
        cst.codcomanda, cst.tipdoc, c.PrefixDoc||c.NrDoc||''/''||c.Datadoc::date Com,cst.PrefixDoc||cst.NrDoc||''/''||cst.Datadoc::date, p.Den_Part,
        o.denumire, u.den_um1, cl.cant/u.paritate, -cl.cant/u.paritate, 0, -cl.cant/u.paritate, -cl.cant*coalesce(c1.pu,0),
        ROW_NUMBER() OVER (PARTITION BY C.CodComanda ORDER BY C1.CodComanda1 ASC), 1,
        COALESCE(ac.denumire,trad.denumiretrad,o.denumire), coalesce(ac.codextern,o.codextern),
        coalesce((CASE ac.tipcodafisat
                    WHEN 1 THEN gre.cod :: varchar
                    WHEN 2 THEN ac.codextern :: varchar
                    WHEN 3 THEN o.codextern :: varchar
                    WHEN 4 THEN o.codintern :: varchar
                    WHEN 5 THEN o.codvamal :: varchar
                    WHEN 6 THEN o.codplu :: varchar
                    WHEN 7 THEN o1.codextofe :: varchar
                  END),o.codextern),
        s.den_subunit ' || coalesce(gUserAlias,'') || '
      FROM comanda c
        INNER JOIN comanda1    c1    ON c1.codcomanda      = c.codcomanda
        INNER JOIN nartobj     o     ON o.codobiect        = c1.codobiect
        INNER JOIN nart        art   ON o.codarticol       = art.codarticol
        INNER JOIN num1        u     ON u.codum1           = c1.umsec
        INNER JOIN npart       p     ON p.codpart          = c.partener
        INNER JOIN cmdlivrlink cl    ON cl.codliniecomanda = c1.codcomanda1
        INNER JOIN comanda1    cst1  ON cst1.codcomanda1   = cl.codcomanda1
        INNER JOIN comanda     cst   ON cst.codcomanda     = cst1.codcomanda
        LEFT  JOIN nclasea     cla   on art.clasa          = cla.codclasea
        LEFT  JOIN nclasep     clp   on p.codclasa         = clp.codclasep
        LEFT  JOIN nagenda     slvr  on slvr.codagenda     = c.codlocatie
        LEFT  JOIN nlocalit    llivr ON llivr.codlocalit   = slvr.codlocalit
        LEFT  JOIN njudet      jlivr ON jlivr.codjudet     = llivr.codjudet
        LEFT  JOIN ntari       tlivr ON tlivr.codtara      = llivr.codtara
        LEFT  JOIN traseulivr  t     on slvr.codtraseu     = t.codtraseulivr
        LEFT  JOIN npart       prod  ON prod.codpart       = o.codproducator
        LEFT  JOIN ncarsupart  cs    ON cs.codcarsupart    = o.codcaract
        LEFT  JOIN nparttr     d     ON d.codparttr        = c.delegat
        LEFT  JOIN nartcli     ac    ON ac.codobiect       = c1.codobiect AND ac.codpart = c.partener
        LEFT  JOIN nartobjtrad trad  ON trad.codlimba      = tlivr.codlimba and trad.codobiect = c1.codobiect
        LEFT  JOIN nechiv      e     ON e.codobiect        = c1.codobiect
        LEFT  JOIN grechiv     gre   ON gre.codgrechiv     = e.codgrupa
        LEFT  JOIN oferta1     o1    ON o1.codoferta1      = c1.codsursa
        LEFT  JOIN nsubunit    s     On s.codsubunit       = c.subunitatea
        -- joinuri false pt coloane suplimentare
        LEFT  JOIN iesiri      i     ON i.codies           = (c1.codcomanda-c1.codcomanda)
        LEFT  JOIN iesiri1     i1    ON i1.codies1         = (c1.codcomanda-c1.codcomanda)' || coalesce(gSuplJoins,'') || '
      WHERE c.tipdoc = 18 AND c.operat = 1 '
            || coalesce(sFiltruInchise,'') || ' AND c.anulat = 0
        AND cl.cant &lt;&gt; 0 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'C',NULL,NULL,NULL)),'') || '
        AND cst.tipdoc = 65 AND cst.operat = 1 AND cst.anulat = 0
        AND c.DataDoc ' || coalesce(sPer,'');
  sSelect3 := '
      SELECT
        i.codies, i.tipdoc, c.PrefixDoc||c.NrDoc||''/''||c.Datadoc::date Com,i.PrefixDoc||i.NrDoc||''/''||i.Datadoc::date, p.Den_Part,
        o.denumire, u.den_um1, il.cant/u.paritate, 0, il.cant/u.paritate, -il.cant/u.paritate, -il.cant*coalesce(c1.pu,0),
        ROW_NUMBER() OVER (PARTITION BY C.CodComanda ORDER BY C1.CodComanda1 ASC), 2,
        COALESCE(ac.denumire,trad.denumiretrad,o.denumire), coalesce(ac.codextern,o.codextern),
        coalesce((CASE ac.tipcodafisat
                    WHEN 1 THEN gre.cod :: varchar
                    WHEN 3 THEN o.codextern :: varchar
                    WHEN 4 THEN o.codintern :: varchar
                    WHEN 5 THEN o.codvamal :: varchar
                    WHEN 6 THEN o.codplu :: varchar
                    WHEN 7 THEN o1.codextofe :: varchar
                  END),o.codextern),
        s.den_subunit ' || coalesce(gUserAlias,'') || '
      FROM comanda c
        INNER JOIN comanda1    c1 ON c1.codcomanda       = c.codcomanda
        INNER JOIN nartobj     o ON o.codobiect          = c1.codobiect
        INNER JOIN nart        art ON o.codarticol       = art.codarticol
        INNER JOIN num1        u ON u.codum1             = c1.umsec
        INNER JOIN npart       p ON p.codpart            = c.partener
        INNER JOIN ieslink     il ON il.codliniecomanda  = c1.codcomanda1
        INNER JOIN iesiri1     i1 ON i1.codies1          = il.codies1
        INNER JOIN iesiri      i ON i.codies             = i1.codies
        LEFT  JOIN nclasea     cla on art.clasa          = cla.codclasea
        LEFT  JOIN nclasep     clp on p.codclasa         = clp.codclasep
        LEFT  JOIN nagenda     slvr on slvr.codagenda    = c.codlocatie
        LEFT  JOIN nlocalit    llivr ON llivr.codlocalit = slvr.codlocalit
        LEFT  JOIN njudet      jlivr ON jlivr.codjudet   = llivr.codjudet
        LEFT  JOIN ntari       tlivr ON tlivr.codtara    = llivr.codtara
        LEFT  JOIN traseulivr  t on slvr.codtraseu       = t.codtraseulivr
        LEFT  JOIN npart       prod ON prod.codpart      = o.codproducator
        LEFT  JOIN ncarsupart  cs ON cs.codcarsupart     = o.codcaract
        LEFT  JOIN nparttr     d ON d.codparttr          = c.delegat
        LEFT  JOIN nartcli     ac ON ac.codobiect        = c1.codobiect AND ac.codpart = c.partener
        LEFT  JOIN nartobjtrad trad ON trad.codlimba     = tlivr.codlimba and trad.codobiect = c1.codobiect
        LEFT  JOIN nechiv      e ON e.codobiect          = c1.codobiect
        LEFT  JOIN grechiv     gre ON gre.codgrechiv     = e.codgrupa
        LEFT  JOIN oferta1     o1 ON o1.codoferta1       = c1.codsursa
        LEFT  JOIN nsubunit    s On s.codsubunit         = c.subunitatea
        -- joinuri false pt coloane suplimentare
        LEFT  JOIN comanda1    cst1 ON cst1.codcomanda1  = (c1.codcomanda-c1.codcomanda)
        LEFT  JOIN comanda     cst ON cst.codcomanda     = (c1.codcomanda-c1.codcomanda)'
              || coalesce(gSuplJoins,'') || '
      WHERE c.tipdoc = 18 AND c.operat = 1 ' || coalesce(sFiltruInchise,'')
        || ' AND c.anulat = 0 AND il.cant &lt;&gt; 0 '
        || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'C',NULL,NULL,NULL)),'') || '
        AND i.operat = 1 AND i.anulat = 0
        AND c.DataDoc ' || coalesce(sPer,'');

  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect1,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect2,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect3,''), aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmcomenzi_processlist</obj_name>
  <obj_hashval>4e00890370fe9ed072bc7eadb4db97c3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmcomenzi_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplCols   VARCHAR := '';
  gSuplJoins  VARCHAR := '';

  sInsert     varchar;
  sSelect1    varchar;
  sSelect2    varchar;
  sSelect3    varchar;
  sSelect4    varchar;
  sFiltru     varchar;
  sComInchise varchar := '0';
BEGIN
  --Florin 14.05.2021 - fixat 49670
  --Adina 13.05.2021 - sinc.Oracle din 12.05.2021 (add sComInchise)
  --Bogdan 01.09.2020
  --Bogdan 09.10.2020
  IF(PKG_LIST_SELCOMENZI_ComInchise()) THEN sComInchise := '1';
  END IF;

  gSuplCols :=
        'comanda c, comanda1 c1, nartobj o, nart art, num1 u, npart np, ngest ng, nsubunit ns, iesiri1 i1, iesiri i, comanda cst, comanda1 cst1, '||
        'nclasea cla, nclasep clp, traseulivr t, npart prod, ncarsupart cs, nparttr d, npers agent';

  call pkg_list_struct_startsuplcols();

  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDC'   , 'CVC'  , 'CVC.CODCOMANDA   = C.CODCOMANDA'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDC1'  , 'CVC1' , 'CVC1.CODCOMANDA1 = C1.CODCOMANDA1',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDI'   , 'CVI'  , 'CVI.CODCOMANDA   = C.CODCOMANDA'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDI1'  , 'CVI1' , 'CVI1.CODCOMANDA1 = C1.CODCOMANDA1',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT' , 'OEXT.CODOBIECT   = C1.CODOBIECT'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR' , 'OATR.CODOBIECT   = C1.CODOBIECT'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CENTRECOST', 'CCOST', 'CCOST.CODCENTRU  = coalesce(C1.CODCENTRU,0)');

  CALL pkg_list_struct_getsuplcols( aLISTID, aLISTVER, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config('PKG_LIST_BASE_URMCOMENZI.gSuplCols',gSuplCols,false);

  sFiltru := '
        AND c.tipdoc IN (SELECT VALOARE::NUMERIC FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''TIPDOC'') ';
  sFiltru := coalesce(sFiltru,'')
          || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT
                       FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'', '(case when C.TipDoc = 44 then c.subunitsursa else c.subunitatea end)', '    AND ', null))::varchar ,'');

  IF (PKG_LIST_SELCOMENZI_DupaData()) THEN
      sFiltru := coalesce(sFiltru,'') || '
                AND c.datadoc ' || coalesce(PKG_LIST_SELCOMENZI_Perioada(),'');
  ELSE
      sFiltru := coalesce(sFiltru,'') || '
                AND (c.luna + c.an * 12) ' || coalesce(PKG_LIST_SELCOMENZI_Perioada(),'');
  END IF;

  sInsert := 'INSERT INTO ' || coalesce(tmpName,'') || '(
            NAV_CodDoc,NAV_TipDoc, Com, Doc,
            Part,
            Art, UM, Cant, CantCom, CantPrel, RestC, RestV,
            NrLinCom, Ordine,
            DenLaCli, CodLaCli,
            CodListat,
            SUBUNITATEA' || coalesce(gUserFields,'') || ')';
  sSelect1 := '
      SELECT
          c.codcomanda, c.tipdoc, c.PrefixDoc||c.NrDoc||''/''||to_char(c.Datadoc,''dd.mm.yyyy'') ,c.PrefixDoc||c.NrDoc||''/''||to_char(c.Datadoc,''dd.mm.yyyy'') ,
          (case when C.TipDoc = 44 then NS.Den_Subunit when  C.TipDoc = 43 then NG.Den_Gest else NP.Den_Part end),
          o.denumire, u.den_um1, c1.cantacceptat/u.paritate, c1.cantacceptat/u.paritate, 0, c1.cantacceptat/u.paritate, c1.cantacceptat*coalesce(c1.pu,0),
          ROW_NUMBER() OVER (PARTITION BY C.CodComanda ORDER BY C1.CodComanda1 ASC), 0 ,
          COALESCE(ac.denumire,trad.denumiretrad,o.denumire), coalesce(ac.codextern,o.codextern),
          coalesce((CASE ac.tipcodafisat
                      WHEN 1 THEN gre.cod :: varchar
                      WHEN 2 THEN ac.codextern :: varchar
                      WHEN 3 THEN o.codextern :: varchar
                      WHEN 4 THEN o.codintern :: varchar
                      WHEN 5 THEN o.codvamal :: varchar
                      WHEN 6 THEN o.codplu :: varchar
                      WHEN 7 THEN o1.codextofe :: varchar
                    END),o.codextern),
          s.den_subunit ' || coalesce(gUserAlias,'') || '
        FROM comanda c
          INNER JOIN comanda1    c1    ON c1.codcomanda    = c.codcomanda
          INNER JOIN nartobj     o     ON o.codobiect      = c1.codobiect
          INNER JOIN nart        art   ON o.codarticol     = art.codarticol
          INNER JOIN num1        u     ON u.codum1         = c1.umsec
          LEFT  JOIN npart       np    ON np.codpart       = c.partener
          LEFT  JOIN ngest       ng    ON ng.codgest       = c.codgest
          LEFT  JOIN nsubunit    ns    ON ns.codsubunit    = c.subunitatea
          LEFT  JOIN nclasea     cla   on cla.codclasea    = art.clasa
          LEFT  JOIN nclasep     clp   on clp.codclasep    = np.codclasa
          LEFT  JOIN nagenda     ag    on ag.codagenda     = c.codlocatie
          LEFT  JOIN npers       agent ON agent.codpers    = ag.codagent
          LEFT  JOIN traseulivr  t     on t.codtraseulivr  = ag.codtraseu
          LEFT  JOIN npart       prod  ON prod.codpart     = o.codproducator
          LEFT  JOIN ncarsupart  cs    ON cs.codcarsupart  = o.codcaract
          LEFT  JOIN nparttr     d     ON d.codparttr      = c.delegat
          LEFT  JOIN nartcli     ac    ON ac.codobiect     = c1.codobiect AND ac.codpart = c.partener
          LEFT  JOIN nlocalit    loc   ON loc.codlocalit   = ag.codlocalit
          LEFT  JOIN ntari       tari  ON tari.codtara     = loc.codtara
          LEFT  JOIN nartobjtrad trad  ON trad.codlimba    = tari.codlimba and trad.codobiect = c1.codobiect
          LEFT  JOIN nechiv      e     ON e.codobiect      = c1.codobiect
          LEFT  JOIN grechiv     gre   ON gre.codgrechiv   = e.codgrupa
          LEFT  JOIN oferta1     o1    ON o1.codoferta1    = c1.codsursa
          LEFT  JOIN nsubunit    s     On s.codsubunit     = c.subunitatea
         -- joinuri false pt coloane suplimentare
          LEFT  JOIN iesiri      i     ON i.codies         = (c1.codcomanda-c1.codcomanda)
          LEFT  JOIN iesiri1     i1    ON i1.codies1       = (c1.codcomanda-c1.codcomanda)
          LEFT  JOIN comanda1    cst1  ON cst1.codcomanda1 = (c1.codcomanda-c1.codcomanda)
          LEFT  JOIN comanda     cst   ON cst.codcomanda   = (c1.codcomanda-c1.codcomanda)' || coalesce(gSuplJoins,'') || '
        WHERE c.anulat = 0 AND c.operat = 1 AND (coalesce(c.inchisa, 0) = 0 OR '||sComInchise||' &gt;0 ) ' || coalesce(sFiltru,'');

  sSelect2 := '
      SELECT
        cst.codcomanda, cst.tipdoc, c.PrefixDoc||c.NrDoc||''/''||to_char(c.Datadoc,''dd.mm.yyyy'') Com,cst.PrefixDoc||cst.NrDoc||''/''||to_char(cst.Datadoc,''dd.mm.yyyy''),
        (case when C.TipDoc = 44 then NS.Den_Subunit when  C.TipDoc = 43 then NG.Den_Gest else NP.Den_Part end),
        o.denumire, u.den_um1, cl.cant/u.paritate, 0, cl.cant/u.paritate, -cl.cant/u.paritate, -cl.cant*coalesce(c1.pu,0),
        ROW_NUMBER() OVER (PARTITION BY C.CodComanda ORDER BY C1.CodComanda1 ASC), 1,
        COALESCE(ac.denumire,trad.denumiretrad,o.denumire), coalesce(ac.codextern,o.codextern),
        coalesce((CASE ac.tipcodafisat
                    WHEN 1 THEN gre.cod :: varchar
                    WHEN 2 THEN ac.codextern :: varchar
                    WHEN 3 THEN o.codextern :: varchar
                    WHEN 4 THEN o.codintern :: varchar
                    WHEN 5 THEN o.codvamal :: varchar
                    WHEN 6 THEN o.codplu :: varchar
                    WHEN 7 THEN o1.codextofe :: varchar
                  END),o.codextern),
        s.den_subunit ' || coalesce(gUserAlias,'') || '
      FROM comanda c
        INNER JOIN comanda1    c1 ON c1.codcomanda      = c.codcomanda
        INNER JOIN nartobj     o ON o.codobiect         = c1.codobiect
        INNER JOIN nart        art ON o.codarticol      = art.codarticol
        INNER JOIN num1        u ON u.codum1            = c1.umsec
        INNER JOIN cmdlivrlink cl ON cl.codliniecomanda = c1.codcomanda1
        INNER JOIN comanda1    cst1 ON cst1.codcomanda1 = cl.codcomanda1
        INNER JOIN comanda     cst ON cst.codcomanda    = cst1.codcomanda
        LEFT  JOIN npart       np ON np.codpart         = c.partener
        LEFT  JOIN ngest       ng ON ng.codgest         = c.codgest
        LEFT  JOIN nsubunit    ns ON ns.codsubunit      = c.subunitatea
        LEFT  JOIN nclasea     cla on cla.codclasea     = art.clasa
        LEFT  JOIN nclasep     clp on clp.codclasep     = np.codclasa
        LEFT  JOIN nagenda     ag on c.codlocatie       = ag.codagenda
        LEFT  JOIN npers       agent ON agent.codpers   = ag.codagent
        LEFT  JOIN traseulivr  t on ag.codtraseu        = t.codtraseulivr
        LEFT  JOIN npart       prod ON prod.codpart     = o.codproducator
        LEFT  JOIN ncarsupart  cs ON cs.codcarsupart    = o.codcaract
        LEFT  JOIN nparttr     d ON d.codparttr         = c.delegat
        LEFT  JOIN nartcli     ac ON ac.codobiect       = c1.codobiect AND ac.codpart = c.partener
        LEFT  JOIN nlocalit    loc ON loc.codlocalit    = ag.codlocalit
        LEFT  JOIN ntari       tari ON tari.codtara     = loc.codtara
        LEFT  JOIN nartobjtrad trad ON trad.codlimba    = tari.codlimba and trad.codobiect = c1.codobiect
        LEFT  JOIN nechiv      e ON e.codobiect         = c1.codobiect
        LEFT  JOIN grechiv     gre ON gre.codgrechiv    = e.codgrupa
        LEFT  JOIN oferta1     o1 ON o1.codoferta1      = c1.codsursa
        LEFT  JOIN nsubunit    s On s.codsubunit        = c.subunitatea
        -- joinuri false pt coloane suplimentare
        LEFT  JOIN iesiri      i ON i.codies            = (c1.codcomanda-c1.codcomanda)
        LEFT  JOIN iesiri1     i1 ON i1.codies1         = (c1.codcomanda-c1.codcomanda)' || coalesce(gSuplJoins,'') || '
      WHERE c.anulat = 0 AND c.operat = 1 AND (coalesce(C.INCHISA, 0) = 0 OR '||sComInchise||' &gt;0 ) ' || coalesce(sFiltru,'') || '
        AND coalesce(cl.cant,0) &lt;&gt; 0 AND cst.tipdoc = 65 AND cst.operat = 1 AND cst.anulat = 0';

  sSelect3 := '
      SELECT
        i.codies, i.tipdoc, c.PrefixDoc||c.NrDoc||''/''||to_char(c.Datadoc,''dd.mm.yyyy'') Com,i.PrefixDoc||i.NrDoc||''/''||to_char(i.Datadoc,''dd.mm.yyyy'') ,
        (case when C.TipDoc = 44 then NS.Den_Subunit when  C.TipDoc = 43 then NG.Den_Gest else NP.Den_Part end),
        o.denumire, u.den_um1, il.cant/u.paritate, 0, il.cant/u.paritate, -il.cant/u.paritate, -il.cant*coalesce(c1.pu,0),
        ROW_NUMBER() OVER (PARTITION BY C.CodComanda ORDER BY C1.CodComanda1 ASC), 2,
        COALESCE(ac.denumire,trad.denumiretrad,o.denumire), coalesce(ac.codextern,o.codextern),
        coalesce((CASE ac.tipcodafisat
                    WHEN 1 THEN gre.cod :: varchar
                    WHEN 2 THEN ac.codextern :: varchar
                    WHEN 3 THEN o.codextern :: varchar
                    WHEN 4 THEN o.codintern :: varchar
                    WHEN 5 THEN o.codvamal :: varchar
                    WHEN 6 THEN o.codplu :: varchar
                    WHEN 7 THEN o1.codextofe :: varchar
                  END),o.codextern),
        s.den_subunit ' || coalesce(gUserAlias,'') || '
      FROM comanda c
        INNER JOIN comanda1    c1    ON c1.codcomanda      = c.codcomanda
        INNER JOIN nartobj     o     ON o.codobiect        = c1.codobiect
        INNER JOIN nart        art   ON o.codarticol       = art.codarticol
        INNER JOIN num1        u     ON u.codum1           = c1.umsec
        INNER JOIN ieslink     il    ON il.codliniecomanda = c1.codcomanda1
        INNER JOIN iesiri1     i1    ON i1.codies1         = il.codies1
        INNER JOIN iesiri      i     ON i.codies           = i1.codies
        LEFT  JOIN npart       np    ON np.codpart         = c.partener
        LEFT  JOIN ngest       ng    ON ng.codgest         = c.codgest
        LEFT  JOIN nsubunit    ns    ON ns.codsubunit      = c.subunitatea
        LEFT  JOIN nclasea     cla   on cla.codclasea      = art.clasa
        LEFT  JOIN nclasep     clp   on clp.codclasep      = np.codclasa
        LEFT  JOIN nagenda     ag    on c.codlocatie       = ag.codagenda
        LEFT  JOIN npers       agent ON agent.codpers      = ag.codagent
        LEFT  JOIN traseulivr  t     on ag.codtraseu       = t.codtraseulivr
        LEFT  JOIN npart       prod  ON prod.codpart       = o.codproducator
        LEFT  JOIN ncarsupart  cs    ON cs.codcarsupart    = o.codcaract
        LEFT  JOIN nparttr     d     ON d.codparttr        = c.delegat
        LEFT  JOIN nartcli     ac    ON ac.codobiect       = c1.codobiect AND ac.codpart = c.partener
        LEFT  JOIN nlocalit    loc   ON loc.codlocalit     = ag.codlocalit
        LEFT  JOIN ntari       tari  ON tari.codtara       = loc.codtara
        LEFT  JOIN nartobjtrad trad  ON trad.codlimba      = tari.codlimba and trad.codobiect = c1.codobiect
        LEFT  JOIN nechiv      e     ON e.codobiect        = c1.codobiect
        LEFT  JOIN grechiv     gre   ON gre.codgrechiv     = e.codgrupa
        LEFT  JOIN oferta1     o1    ON o1.codoferta1      = c1.codsursa
        LEFT JOIN nsubunit     s     On s.codsubunit       = c.subunitatea
        -- joinuri false pt coloane suplimentare
        LEFT  JOIN comanda1    cst1  ON cst1.codcomanda1   = (c1.codcomanda-c1.codcomanda)
        LEFT  JOIN comanda     cst   ON cst.codcomanda     = (c1.codcomanda-c1.codcomanda)' || coalesce(gSuplJoins,'') || '
      WHERE c.anulat = 0 AND c.operat = 1 AND (coalesce(c.inchisa, 0) = 0 OR '||sComInchise||' &gt;0 ) ' || coalesce(sFiltru,'') || '
        AND coalesce(il.cant,0) &lt;&gt; 0 AND i.operat = 1 AND i.anulat = 0';

  sSelect4 := '
    SELECT
      c.codcomanda, c.tipdoc, c.PrefixDoc||c.NrDoc||''/''||to_char(c.Datadoc,''dd.mm.yyyy'') ,TR.PrefixDoc||TR.NrDoc||''/''||to_char(TR.Datadoc,''dd.mm.yyyy'') ,
      (case when C.TipDoc = 44 then NS.Den_Subunit when  C.TipDoc = 43 then NG.Den_Gest else NP.Den_Part end),
      o.denumire, u.den_um1, L.cant/u.paritate, L.cant/u.paritate, 0, -L.cant/u.paritate, -L.cant/u.paritate*coalesce(c1.pu,0),
      ROW_NUMBER() OVER (PARTITION BY C.CodComanda ORDER BY C1.CodComanda1 ASC), 3 ,
      COALESCE(ac.denumire,trad.denumiretrad,o.denumire), coalesce(ac.codextern,o.codextern),
      coalesce((CASE ac.tipcodafisat
                  WHEN 1 THEN gre.cod :: varchar
                  WHEN 2 THEN ac.codextern :: varchar
                  WHEN 3 THEN o.codextern :: varchar
                  WHEN 4 THEN o.codintern :: varchar
                  WHEN 5 THEN o.codvamal :: varchar
                  WHEN 6 THEN o.codplu :: varchar
                  WHEN 7 THEN o1.codextofe :: varchar
                END),o.codextern),
      s.den_subunit ' || coalesce(gUserAlias,'') || '
    FROM comanda c
      INNER JOIN comanda1    c1    ON c1.codcomanda     = c.codcomanda
      INNER JOIN nartobj     o     ON o.codobiect       = c1.codobiect
      INNER JOIN nart        art   ON o.codarticol      = art.codarticol
      INNER JOIN num1        u     ON u.codum1          = c1.umsec
      INNER JOIN TRANSFLINK  L     ON L.CODLINIECOMANDA = C1.CODCOMANDA1
      INNER JOIN TRANSF1     T1    ON T1.CODTRANSF1     = L.CODTRANSF1
      INNER JOIN TRANSF      TR    ON TR.CODTRANSF      = T1.CODTRANSF
      LEFT  JOIN npart       np    ON np.codpart        = c.partener
      LEFT  JOIN ngest       ng    ON ng.codgest        = c.codgest
      LEFT  JOIN nsubunit    ns    ON ns.codsubunit     = c.subunitatea
      LEFT  JOIN nclasea     cla   on cla.codclasea     = art.clasa
      LEFT  JOIN nclasep     clp   on clp.codclasep     = np.codclasa
      LEFT  JOIN nagenda     ag    on ag.codagenda      = c.codlocatie
      LEFT  JOIN npers       agent ON agent.codpers     = ag.codagent
      LEFT  JOIN traseulivr  t     on t.codtraseulivr   = ag.codtraseu
      LEFT  JOIN npart       prod  ON prod.codpart      = o.codproducator
      LEFT  JOIN ncarsupart  cs    ON cs.codcarsupart   = o.codcaract
      LEFT  JOIN nparttr     d     ON d.codparttr       = c.delegat
      LEFT  JOIN nartcli     ac    ON ac.codobiect      = c1.codobiect AND ac.codpart = c.partener
      LEFT  JOIN nlocalit    loc   ON loc.codlocalit    = ag.codlocalit
      LEFT  JOIN ntari       tari  ON tari.codtara      = loc.codtara
      LEFT  JOIN nartobjtrad trad  ON trad.codlimba     = tari.codlimba and trad.codobiect = c1.codobiect
      LEFT  JOIN nechiv      e     ON e.codobiect       = c1.codobiect
      LEFT  JOIN grechiv     gre   ON gre.codgrechiv    = e.codgrupa
      LEFT  JOIN oferta1     o1    ON o1.codoferta1     = c1.codsursa
      LEFT  JOIN nsubunit    s     On s.codsubunit      = c.subunitatea
     -- joinuri false pt coloane suplimentare
      LEFT  JOIN iesiri      i     ON i.codies          = (c1.codcomanda-c1.codcomanda)
      LEFT  JOIN iesiri1     i1    ON i1.codies1        = (c1.codcomanda-c1.codcomanda)
      LEFT  JOIN comanda1    cst1  ON cst1.codcomanda1  = (c1.codcomanda-c1.codcomanda)
      LEFT  JOIN comanda     cst   ON cst.codcomanda    = (c1.codcomanda-c1.codcomanda)' || coalesce(gSuplJoins,'') || '
    WHERE c.anulat = 0 AND c.operat = 1 AND (coalesce(c.inchisa, 0) = 0 OR '||sComInchise||' &gt;0 ) ' || coalesce(sFiltru,'');


  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect1,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect2,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect3,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect4,''), aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_urmcontrleasing_processlist</obj_name>
  <obj_hashval>a16cb1e6a6747ccf7e8738b558f0c8eb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_urmcontrleasing_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert       VARCHAR := '';
  sSelect       VARCHAR := '';
  sDoc           VARCHAR := '';
  sCodDoc       VARCHAR := '';
  sCondCurs     VARCHAR := '';
  sCondContr     VARCHAR := '';
  sTipContr     VARCHAR := '';
  sALLimita     VARCHAR := '99999';
  sALLucru      VARCHAR := getAnLunaLucru()::varchar;
  vDataAux       date;
  gSuplCols     VARCHAR := 'contract c, npart p, nmonede mc, contract0 c0p';
   gUserFields   VARCHAR := '';
  gUserAlias     VARCHAR := '';
  gNullAlias     VARCHAR := '';
  gSuplJoins     VARCHAR := '';
BEGIN
  --Florin 26.02.2024 - fixat 61093
  --Stef 19.01.2024
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_URMCONTRLEASING.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  vDataAux := Last_Day(To_Date(getANLUCRU() || '.' || getLUNALUCRU(), 'YYYY.MM'));

  IF  current_setting('PKG_LIST_BASE_URMCONTRLEASING.vTipSold', true)::numeric = 1 THEN
    sALLimita := getAnLunaLucru()::varchar;
    sCondCurs  := ' AND c0.data &lt;= To_Date('''     || coalesce(To_Char(vDataAux, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
    sCondContr := ' AND c.datastart &lt;= To_Date(''' || coalesce(To_Char(vDataAux, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
  END IF;

  IF  aLISTID = 241 THEN
    sDoc       := 'intrari';
    sCodDoc   := 'codintr';
    sTipContr := '25';
  ELSE
    sDoc       := 'iesiri';
    sCodDoc   := 'codies';
    sTipContr := '25';
  END IF;

  sInsert := 'INSERT INTO ' || tmpName || '(
    NAV_CodDoc, NAV_TipDoc, CONTRNR, CONTRDATA, CONTRDATAI, CONTRDATAS, CONTRMoneda,
    PART,
    ART,
    CONTRVal, CONTRDob, CONTRTot, CONTRAsig,
    CONTRCurs,
    FACTRata, FACTDob, FACTVal, FACTAsig,
    LUNARata, LUNADob, LUNAVal, LUNAAsig,
    SOLDRata, SOLDDob, SOLDVal, SOLDAsig ' || gUserFields || ')';

  sSelect := '
  WITH
  tmp0 AS (
    SELECT
      c.codcontract, c2.suma, c2.dobanda, c2.asigurare,
      CASE
        WHEN i.'||sCodDoc||' IS NOT NULL THEN i.an*12+i.luna
        WHEN c2.datadoc IS NOT NULL THEN Extract(YEAR FROM c2.datadoc)*12+Extract(MONTH FROM c2.datadoc)
        WHEN c2.nrdoc   IS NOT NULL
         AND c2.data    IS NOT NULL THEN Extract(YEAR FROM c2.data)*12+Extract(MONTH FROM c2.data)
        ELSE 100000
      END ALDoc
    FROM contract c
      INNER JOIN contract2 c2 ON c2.codcontract = c.codcontract
      LEFT JOIN '||sDoc||' i ON i.'||sCodDoc||' = c2.coddoc AND i.tipdoc = c2.tipdoc
    WHERE c.tipdoc = '||sTipContr||' AND c.operat = 1 AND c.anulat = 0 '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('C')||sCondContr||'
  ),
  tmp AS (
    SELECT
      codcontract,
      Sum(CASE WHEN ALDoc &lt;= '||sALLimita||' THEN suma      ELSE 0 END) FactRata,
      Sum(CASE WHEN ALDoc &lt;= '||sALLimita||' THEN dobanda   ELSE 0 END) FactDob,
      Sum(CASE WHEN ALDoc &lt;= '||sALLimita||' THEN asigurare ELSE 0 END) FactAsig,
      Sum(CASE WHEN ALDoc  = '||sALLucru ||' THEN suma      ELSE 0 END) LunaRata,
      Sum(CASE WHEN ALDoc  = '||sALLucru ||' THEN dobanda   ELSE 0 END) LunaDob,
      Sum(CASE WHEN ALDoc  = '||sALLucru ||' THEN asigurare ELSE 0 END) LunaAsig,
      Sum(CASE WHEN ALDoc  &gt; '||sALLimita||' THEN suma      ELSE 0 END) SoldRata,
      Sum(CASE WHEN ALDoc  &gt; '||sALLimita||' THEN dobanda   ELSE 0 END) SoldDob,
      Sum(CASE WHEN ALDoc  &gt; '||sALLimita||' THEN asigurare ELSE 0 END) SoldAsig
    FROM tmp0
    GROUP BY codcontract
  )
  SELECT
    c.codcontract NAV_CodDoc, c.tipdoc NAV_TipDoc, c.NrDoc CONTRNR, c.Datadoc CONTRDATA, c.DataStart CONTRDATAI, c.DataStop CONTRDATAS, mc.den_moneda CONTRMoneda,
    p.den_part part,
    ( SELECT string_agg(DISTINCT o.denumire ,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||'''  ORDER BY o.denumire)
      FROM contract1 c1 INNER JOIN nartobj o ON o.codobiect = c1.codobiect
      WHERE c1.codcontract = tmp.codcontract
    ) art,
    tmp.FactRata + tmp.SoldRata CONTRVal, tmp.FactDob + tmp.SoldDob CONTRDob, tmp.FactRata + tmp.SoldRata + tmp.FactDob + tmp.SoldDob CONTRTot, c.asiganual CONTRAsig,
    CASE
      WHEN mc.codmoneda = 0 THEN 1
      ELSE
        COALESCE(
          ( SELECT Max(curs)
            FROM (SELECT c0.curs, dense_rank() over(ORDER BY c0.data desc) NR
                  FROM contract0 c0
                  WHERE c0.codcontract = tmp.codcontract AND c0.tiplinie = 2' || sCondCurs || ' ) aa
            WHERE NR=1
          ),
          ( SELECT Max(oldcurs)
            FROM (SELECT c0.oldcurs, dense_rank() over(ORDER BY c0.data asc) NR
                  FROM contract0 c0
                  WHERE c0.codcontract = tmp.codcontract AND c0.tiplinie = 2 ) bb
            WHERE NR=1
          ),
          Coalesce(NULLIF(coalesce(c.curs,0),0),1)
        )
    END CONTRCurs ,
    tmp.FactRata, tmp.FactDob, tmp.FactRata + tmp.FactDob FACTVal, tmp.FactAsig,
    tmp.LunaRata, tmp.LunaDob, tmp.LunaRata + tmp.LunaDob LUNAVal, tmp.LunaAsig,
    tmp.SoldRata, tmp.SoldDob, tmp.SoldRata + tmp.SoldDob SOLDVal, tmp.soldasig' || gUserAlias || '
  FROM tmp
    INNER JOIN contract  c   ON c.codcontract   = tmp.codcontract
    LEFT  JOIN npart     p   ON p.codpart       = c.partener
    LEFT  JOIN nmonede   mc  ON mc.codmoneda    = c.moneda
    LEFT  JOIN contract0 c0p ON c0p.codcontract = tmp.codcontract AND c0p.tiplinie = 2 AND c0p.data &lt;= To_Date(''01.' || coalesce(To_Char(vDataAux, 'mm.yyyy'),'') || ''',''dd.mm.yyyy'')' || gSuplJoins || '
  WHERE coalesce(c0p.codcontract0,0) =
      ( SELECT coalesce(Max(codcontract0),0)
        FROM (SELECT coalesce(x.codcontract0,0) codcontract0, dense_rank() over(ORDER BY x.data desc) NR
              FROM CONTRACT0 x
              WHERE x.codcontract = tmp.codcontract
                    AND x.tiplinie = 2 AND x.data &lt;= To_Date(''01.' || coalesce(To_Char(vDataAux, 'mm.yyyy'),'') || ''',''dd.mm.yyyy'') ) cc
        WHERE NR=1
      )';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_calculeazapmpliste</obj_name>
  <obj_hashval>388eb65b8452cd67e3435b27feb9dcec</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_calculeazapmpliste()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  --Adina iulie 2020
  FOR v_rec IN
  (
  SELECT AN, LUNA
  --  CASE WHEN  (  luna + nr)  &lt;= 12 THEN an ELSE an + 1 END  AN,
  --  CASE WHEN  (  luna + nr)  &lt;= 12 THEN (  luna + nr) ELSE (  luna + nr)  - 12 END  LUNA
  FROM
    (
      WITH RECURSIVE flr(an, luna, alm) AS
      (SELECT CAST(ancurent AS INTEGER) an ,CAST(lunacurenta AS INTEGER) luna, CAST(anmaxim*12+lunamaxima AS INTEGER) alm
        FROM firmaluni
       UNION ALL
       SELECT an + CASE WHEN luna = 12 THEN 1 ELSE 0 END, CASE WHEN luna = 12 THEN 1 ELSE luna + 1 END luna, flr.alm
        FROM flr WHERE (flr.an*12+flr.luna) &lt; flr.alm
     )
    SELECT an, luna FROM flr ORDER BY an, luna
    ) A_PG
  )
  LOOP
    PERFORM pkg_globals_SetLunaTemp( v_rec.an, v_rec.luna);
    PERFORM PKG_LIST_BASE_UTILS_MAKE_PMP_LUNA_LISTE();
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_decode_tipdoc_scurt</obj_name>
  <obj_hashval>a3a701a37ccfc8013f53a41bb218b267</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_decode_tipdoc_scurt(INOUT wme_result character varying, INOUT ptipdoc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult varchar;
begin
  --Bogdan 08.01.2021
  BEGIN
    SELECT NUMEPRESC INTO strict sResult FROM tmp_machete WHERE pTipDoc = CodMacheta;
  EXCEPTION WHEN others THEN
    sResult := '-';
  END;
  WME_Result :=  sResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_get_den_banca</obj_name>
  <obj_hashval>36e23d26d6a0d5dad0822bcbc6f0f3fd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_get_den_banca(INOUT wme_result character varying, INOUT acodbank numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  Den_Bank varchar;
begin
  BEGIN
    SELECT denumire INTO Den_Bank FROM nbank WHERE codbank = aCodBank;
  EXCEPTION WHEN OTHERS THEN
    Den_Bank := '';
  END;
  WME_Result :=  den_bank;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_get_denioart</obj_name>
  <obj_hashval>0174c2141aa85b026fb874dd5503b6e1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_get_denioart(INOUT wme_result character varying, INOUT v_codioart numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult varchar;
begin
  SELECT den_ioart INTO sResult FROM v_ioart_luna WHERE codioart = v_codioart;
  WME_Result :=  sResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_get_gest</obj_name>
  <obj_hashval>7d7582c7f7315fb1aa2a0f7412bc40a1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_get_gest(INOUT wme_result character varying, INOUT v_codgest numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_gest varchar;
begin
  SELECT Coalesce( den_gest, 'nedef.') INTO v_gest FROM ngest WHERE codgest = v_codgest;
  WME_Result :=  v_gest;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getcursreg</obj_name>
  <obj_hashval>0c7b3db2e0d63bd8cd931f40669f91bc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getcursreg(pcodgeneral numeric, pcont numeric, pan numeric, pluna numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
vCurs numeric;
begin
  --Bogdan 15.08.2020
  SELECT  DISTINCT LAST_VALUE( r.curs) OVER (  ORDER BY r.an , r.luna range between unbounded preceding and unbounded following)
  INTO vCurs
  FROM reg r
    INNER JOIN reg1 r1 ON  r.codreg = r1.codreg
  WHERE
    r.tipreg = 46
    AND  r.an * 12 + r.luna &lt; pAn * 12 + pLuna
    AND  r1.cont = pCont
    AND  r1.CodGeneral = pCodGeneral;

  IF  vCurs = 0   THEN
    vCurs := NULL;
  END IF;

  return  vCurs;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getcursreg</obj_name>
  <obj_hashval>bda32859edfcb3a1eab2aa23e01a9888</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getcursreg(INOUT wme_result numeric, INOUT pcodgeneral numeric, INOUT pcont numeric, INOUT pan numeric, INOUT pluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Stef   18.03.2022
  WME_Result :=  pkg_list_base_utils_getcursreg(pcodgeneral, pcont, pan, pluna);
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getscdmartexcl</obj_name>
  <obj_hashval>62a506ecc3ea79bdf2bc9b7e97554767</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getscdmartexcl(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_LIST_BASE_UTILS.sCDMArtExcl', true);
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_getsoldpart</obj_name>
  <obj_hashval>7c3e05dfa55c034d28681a87982c3487</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_getsoldpart(INOUT wme_result numeric, INOUT pcodpart numeric, INOUT pcodlocatie numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vSql  varchar;
  vSold numeric;
begin
  PERFORM PKG_NOMPART_SET_PART_CURENT( pCodPart);
  PERFORM PKG_MONEDE_SET_MONEDA_CURENTA( -1);
  vSql := '
    WITH OBLIG AS (
      SELECT
        V.CodLocatie, V.Subunitatea,
        -V.REST * Coalesce(NULLIF(coalesce(V.CURS,0),0),1) RESTREAL, -V.VALOARE * DECODE(V.CURS,NULL,1,0,1,V.CURS) VALREAL
      FROM ('||V_OBLIG_FURN||') V
      UNION ALL
      SELECT
        V.CodLocatie, V.Subunitatea,
        V.REST * Coalesce(NULLIF(coalesce(V.CURS,0),0),1)  RESTREAL, V.VALOARE * DECODE(V.CURS,NULL,1,0,1,V.CURS)  VALREAL
      FROM ('||V_INTRARI_ROSU_FURN||') V
      UNION ALL
      SELECT
        V.CodLocatie, V.Subunitatea,
        V.REST * Coalesce(NULLIF(coalesce(V.CURS,0),0),1)  RESTREAL, V.VALOARE * DECODE(V.CURS,NULL,1,0,1,V.CURS)  VALREAL
        FROM ('||V_AVANS_FURN_TREZOR||') V
      UNION ALL
      SELECT
        V.CodLocatie, V.Subunitatea,
        V.REST * Coalesce(NULLIF(coalesce(V.CURS,0),0),1)  RESTREAL, V.VALOARE * DECODE(V.CURS,NULL,1,0,1,V.CURS)  VALREAL
      FROM ('||V_AVANS_FURN_FACTURABILE||') V
      UNION ALL
      SELECT
        V.CodLocatie, V.Subunitatea,
        V.REST * Coalesce(NULLIF(coalesce(V.CURS,0),0),1)  RESTREAL, V.VALOARE * DECODE(V.CURS,NULL,1,0,1,V.CURS)  VALREAL
      FROM ('||V_OBLIG_CLIENT||') V
      UNION ALL
      SELECT
        V.CodLocatie, V.Subunitatea,
        -V.REST * Coalesce(NULLIF(coalesce(V.CURS,0),0),1) RESTREAL, -V.VALOARE * DECODE(V.CURS,NULL,1,0,1,V.CURS) VALREAL
      FROM ('||V_IESIRI_ROSU_CLIENT||') V
      UNION ALL
      SELECT
        V.CodLocatie, V.Subunitatea,
        -V.REST * Coalesce(NULLIF(coalesce(V.CURS,0),0),1) RESTREAL, -V.VALOARE * DECODE(V.CURS,NULL,1,0,1,V.CURS) VALREAL
      FROM ('||V_AVANS_CLIENT_TREZOR||') V
      UNION ALL
      SELECT
        V.CodLocatie, V.Subunitatea,
        -V.REST * Coalesce(NULLIF(coalesce(V.CURS,0),0),1) RESTREAL, -V.VALOARE * DECODE(V.CURS,NULL,1,0,1,V.CURS) VALREAL
      FROM ('||V_AVANS_CLIENT_FACTURABILE||') V
    )
    SELECT Sum (RESTREAL)
    FROM OBLIG ' || (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL, '', 'SUBUNITATEA', '
    WHERE',NULL)) || CASE WHEN  Coalesce( pCodLocatie, 0) &lt;&gt; 0 THEN ' AND CodLocatie = ' || pCodLocatie END ;
  EXECUTE vSql INTO vSold;
  vSold := Coalesce( vSold, 0);
  WME_Result :=  vSold;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_utils_lunascurta</obj_name>
  <obj_hashval>56092a319a86131b5038042ab843946d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_utils_lunascurta(INOUT wme_result character varying, INOUT pluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult varchar;
begin
  sResult := SubStr( (SELECT PKG_LIST_BASE_UTILS_decode_luna.WME_RESULT FROM PKG_LIST_BASE_UTILS_decode_luna(NULL, pLuna)), 1, 3);
  WME_Result :=  sResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzagent_campuri</obj_name>
  <obj_hashval>b61bf248abc8c2f6c05764d26e47723d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzagent_campuri(ptip character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  S         varchar;
  K         NUMERIC := 0;
   vLunaIni  NUMERIC := current_setting('PKG_LIST_BASE_VANZAGENT.vLunaIni', true)::numeric;
   vAnIni    NUMERIC := current_setting('PKG_LIST_BASE_VANZAGENT.vAnIni', TRUE)::NUMERIC;
   vLunaFin  NUMERIC := current_setting('PKG_LIST_BASE_VANZAGENT.vLunaFin', true)::numeric;
   vAnFin    NUMERIC := current_setting('PKG_LIST_BASE_VANZAGENT.vAnFin', TRUE)::NUMERIC;
BEGIN
  --Florin 24.08.2020
  S:= COALESCE(S, '') || PKG_LIST_BASE_VANZAGENT_CompleteazaS(0,'T_VV', ptip, 0);
  S:= COALESCE(S, '') || PKG_LIST_BASE_VANZAGENT_CompleteazaS(0,'T_VI', ptip, 0);
  S:= COALESCE(S, '') || PKG_LIST_BASE_VANZAGENT_CompleteazaS(0,'T_XV', ptip, 0);
  S:= COALESCE(S, '') || PKG_LIST_BASE_VANZAGENT_CompleteazaS(0,'T_NV', ptip, 0);
  FOR i IN (vAnIni*12+vLunaIni)..(vAnFin*12+vLunaFin) LOOP
    K := K + 1;
    S:= COALESCE(S, '') || PKG_LIST_BASE_VANZAGENT_CompleteazaS(i,'VV', ptip, k);
    S:= COALESCE(S, '') || PKG_LIST_BASE_VANZAGENT_CompleteazaS(i,'VI', ptip, k);
    S:= COALESCE(S, '') || PKG_LIST_BASE_VANZAGENT_CompleteazaS(i,'XV', ptip, k);
    S:= COALESCE(S, '') || PKG_LIST_BASE_VANZAGENT_CompleteazaS(i,'NV', ptip, k);
  END LOOP;
  RETURN S;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzagent_setjoinuri</obj_name>
  <obj_hashval>8852f0bcd884cbbfdfed6816a702901f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzagent_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 22.08.2020
  PERFORM Pkg_List_Struct_SetTableSpec('');
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzari_sint_setparams</obj_name>
  <obj_hashval>ff911884a17d9201f7ea4d865ad61739</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzari_sint_setparams(acodrestaurant numeric, adatastart character varying, adataend character varying, aid numeric, aver numeric, pcodjob1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni INTEGER;
  xLunaAnFin INTEGER;
BEGIN
  --Adina 19.10.2020
  PERFORM set_config('PKG_LIST_BASE_VANZARI_SINT.DATASTART'    , aDATASTART, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VANZARI_SINT.DATAEND'      , aDATAEND  , FALSE);

  IF COALESCE(pCodJob1,0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(pCodJob1,aDATASTART,aDATAEND,xLunaAnIni,xLunaAnFin);
  END IF;

  PERFORM set_config('PKG_LIST_BASE_VANZARI_SINT.CODRESTAURANT', aCODRESTAURANT::varchar, FALSE);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_vanzper_setjoinuri</obj_name>
  <obj_hashval>521ea63b12a30df4562f6960bd71063c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_vanzper_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 19.08.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_VANZPER.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_veniturirac_setparams</obj_name>
  <obj_hashval>9e21bf13a9351b170f16fd9ad6df8c8a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_veniturirac_setparams(zi1 date, zi2 date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 03.10.2020
  PERFORM set_config('PKG_LIST_BASE_VENITURIRAC.sZi1', Zi1::varchar, FALSE);
  PERFORM set_config('PKG_LIST_BASE_VENITURIRAC.sZi2', Zi2::varchar, FALSE);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_voucherdoc_setparams</obj_name>
  <obj_hashval>e86d7ad4b75003570c037d95312fc072</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_voucherdoc_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 05.10.2020
  PERFORM set_config('PKG_LIST_BASE_VOUCHERDOC.vCodDoc', pCodDoc::varchar, FALSE);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selectscad_modselectie</obj_name>
  <obj_hashval>438a414316914faa926b4a4291a657b0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selectscad_modselectie(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_LIST_SELECTSCAD.vMod', true)::numeric);
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selmoment_extra1</obj_name>
  <obj_hashval>aaaee40464320724db1cac0d838fab50</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selmoment_extra1()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 15.09.2020
  return current_setting ('PKG_LIST_SELMOMENT.vExtra1', true)::numeric = 1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_selpart_isallpart</obj_name>
  <obj_hashval>06d443b2bb172ddf9ab53e8d24b2200f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_selpart_isallpart()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  return current_setting('PKG_LIST_SELPART.gAllPart', true)::numeric = 1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_seltras_getdataini</obj_name>
  <obj_hashval>e76a57c8fe7d91b393c99a45876b91ce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_seltras_getdataini()
 RETURNS date
 LANGUAGE sql
AS $function$
  -- Stef 12.06.2023
  SELECT to_date(current_setting('PKG_LIST_SELTRAS.p_dataIni', true), 'dd.mm.yyyy');
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_seltras_getinterval</obj_name>
  <obj_hashval>d1eab103244be2e9ffc93e8016a1e952</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_seltras_getinterval()
 RETURNS character varying
 LANGUAGE sql
AS $function$
  -- Stef 12.06.2023
  SELECT ' to_date('''||current_setting('PKG_LIST_SELTRAS.p_dataIni', true)||''',''dd.mm.yyyy'') AND to_date('''||current_setting('PKG_LIST_SELTRAS.p_dataFin', true)||''',''dd.mm.yyyy'') ';
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_seltras_isallgest</obj_name>
  <obj_hashval>10ed18092b9ff03e200247d199cb9b65</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_seltras_isallgest()
 RETURNS boolean
 LANGUAGE sql
AS $function$
  -- Stef 12.06.2023
  SELECT current_setting('PKG_LIST_SELTRAS.p_flgGest', true)::BOOLEAN;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_struct_list_counter</obj_name>
  <obj_hashval>ac18c90efbaa484448b0f7d094219062</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_struct_list_counter(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult numeric;
begin
  SELECT NEXTVAL('SEQ_LIST_COUNTER') INTO sResult;
  WME_Result :=  sResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_locmunca_getdisponibilpezi</obj_name>
  <obj_hashval>ff384704cf1e3f820cd24c716c2949ca</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_locmunca_getdisponibilpezi(INOUT wme_result numeric, INOUT acodloc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vOre numeric;
begin
  BEGIN
    SELECT sum( lm1.ore) INTO vOre FROM locmunca1 lm1 WHERE lm1.codloc = aCodLoc;
  EXCEPTION WHEN others THEN
    vOre := 0;
  END;

  WME_Result :=  vOre;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_locmunca_sp_insertrecord</obj_name>
  <obj_hashval>c4f0ff5c73064798e3a34ca7200e825f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_locmunca_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 18.06.2025 - sinc. Oracle
  INSERT INTO TMP_LOCMUNCA (CodLoc) VALUES(0);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(524);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mail_utils_getdocumente</obj_name>
  <obj_hashval>3b7bf9668d5c980ff43306d6786c7830</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mail_utils_getdocumente(acoddoc numeric, atipdoc numeric, aowner character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TaskFirma numeric;
begin
  SELECT COALESCE(fnc_GetValConstantaLucru('TaskFirma'), '0') INTO TaskFirma;

  IF aTipDoc IN (1, 2, 3, 4, 5, 6, 7, 9) THEN
    PERFORM pkg_intrari_SP_LOCKRECORD( aCodDoc);
  ELSIF aTipDoc IN (14, 15, 16, 19, 20, 21, 22, 23, 24, 26) THEN
    PERFORM pkg_iesiri_SP_LOCKRECORD( aCodDoc);
  END IF;

  EXECUTE 'insert into tmp_documente(coddocument,coddoc,tipdoc,filename,doc,obs,incarcat,marime) '     ||
          'select coddocument,coddoc,tipdoc,filename,doc,obs,1,round(dbms_lob.getlength(doc)/1024,2) ' ||
          'from ' || aOwner || '.documente where coddoc = ' || aCodDoc || ' and tipdoc = ' || aTipDoc;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mail_utils_sendmailfromtrigger</obj_name>
  <obj_hashval>75173eaf3d8f4a6012fba42de0135d71</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mail_utils_sendmailfromtrigger(subject character varying, message character varying, toaddress character varying)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
declare
  gUserName     varchar(500);
  gPassword     varchar(500);
  gFromAddress  varchar(500);
  gSemnatura    varchar(500);
  gPort         NUMERIC;
  gServerMail   varchar(500);
  gDomain       varchar(500);
  gAuthType     NUMERIC;
  gUseTLS       NUMERIC;
  iret          NUMERIC;
  gClientID           varchar(200);
  gClientSecret       varchar(200);
  gAuthEndPoint       varchar(200);
  gAccesTokenEndPoint varchar(200);
  gRefreshToken       varchar(2000);
  gLogOutEndPoint     varchar(200);
  gScopes             varchar(300);
  gOAuth2             NUMERIC;
BEGIN
  --Florin 18.03.2025 - sinc. Oracle
  --Florin 17.03.2025 - sinc. Oracle
  PERFORM winmadmin.pkg_userfirme_GET_USER_CREDENTIAL_FULL_ext(pkg_globals.USERID, 0,
                                                   pkg_globals.CODFIRMA,
                                                   gUserName,
                                                   gPassword,
                                                   gFromAddress,
                                                   gSemnatura,
                                                   gPort,
                                                   gServerMail,
                                                   gDomain,
                                                   gAuthType,
                                                   gUseTLS,
                                                   gRefreshToken,
                                                   goAuth2,
                                                   gClientID,
                                                   gClientSecret,
                                                   gAuthEndPoint,
                                                   gAccesTokenEndPoint,
                                                   gLogOutEndPoint,
                                                   gScopes
                                                   );
   iret := pkg_mail_SENDMAIL_BY_SERVICE(gServerMail,
                            gPort,
                            gFromAddress,
                            gUserName,
                            gPassword,
                            Subject,
                            ToAddress,
                            Message);
  RETURN iret;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mifix_getnextnrinv</obj_name>
  <obj_hashval>98ddeb6917eb02ab648955f7521b3ab6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mifix_getnextnrinv(INOUT wme_result numeric, INOUT atip character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric := 0;
BEGIN
  --Florin 14.10.2024 - const varchar
  --Florin 11.10.2024 - sinc. Oracle
    if (fnc_getvalconstantalucru('Holding') = '1')
     and (fnc_getvalconstantalucru('HoldingNrInv') = '2') then
    SELECT COALESCE(MAX(LASTNR), 0) INTO TMP FROM
    (
      SELECT MAX(USEDNO) AS LASTNR FROM NRINVLOCK nl WHERE nl.TIP = aTIP and nl.subunitatea = GETSUBUNITATE_DOC()
      UNION ALL
      select COALESCE(max(mf.nrinventar),0) AS LASTNR
        from mifix mf
        join mifix1 mf1
            on mf1.codmifix = mf.codmifix
        join nirstoc ns
            on ns.codnirstoc = mf1.codnirstoc
        join nir n
            on n.codnir = ns.codnir
        join ngest ng
            on ng.codgest = n.gest
        where mf.TIP = aTIP
              and ng.codsubunit = GETSUBUNITATE_DOC()
     ) a_pg;

    WME_Result :=  TMP + 1;
    RETURN;
  else
    SELECT COALESCE( MAX( LASTNR), 0)
    INTO TMP
    FROM (SELECT MAX( USEDNO) AS LASTNR FROM NRINVLOCK WHERE TIP = aTIP
          union ALL
          SELECT MAX( NRINVENTAR) AS LASTNR FROM MIFIX WHERE TIP = aTIP
         ) A_PG;

    WME_Result :=  TMP + 1;
    RETURN;
 END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mifix_sp_gotorecord</obj_name>
  <obj_hashval>8a6008b974ff4d1b4c176d9711aa8cbd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mifix_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR         numeric;
  aCODCLASIF numeric := 0;
  aCODMIFIXVECHI numeric(20);
  v_rec record;
BEGIN
  --Florin 10.12.2025 - sinc. Oracle
  --Florin 04.12.2025 - sinc. Oracle
  --Florin 29.10.2025 - sinc. Oracle
  --Florin 28.11.2024 - sinc. Oracle
  --Adina 05.07.2021 - sinc.Oracle din 03.07.2021
  --Bogdan 08.10.2020
  --Florin 16.11.2021 - fixat 52001
  perform pkg_mifix_setct_monitor('MON_15');
  PERFORM PKG_STOC_GENERARE_FACTURI_MAKE_CONFIG_LUNA();

  SELECT COUNT(*) INTO NR FROM MASTERMIFIX WHERE CODNIRSTOC = RecId;

  IF RECID   &gt; 0 AND NR = 0 THEN
    INSERT INTO MASTERMIFIX (CODNIRSTOC) VALUES (RECID);
  END IF;

  INSERT INTO TMP_MASTERMIFIX
  SELECT * FROM MASTERMIFIX WHERE CODNIRSTOC = RECID;

  INSERT INTO TMP_MIFIX (CODTMPMIFIX, CODMIFIX,
      TIP,
      NRINVENTAR,
      ANINTRARE,
      LUNAINTRARE,
      CODMIFIX1,
      CODNIRSTOC,
      PRET,
      CANT,
      CODCLASIF,
      TIPAMO,
      STARE,
      DURATAN,
      GRADU,
      DURATAF,
      AMO,
      NEUTIL,
      DFBLOCAT,
      CODPERS,
      CODNIRSER,
      ANSTART,
      LUNASTART,
      CODIOART,
      CODGEST,
      SERIE,
      TIPREEVAL,
      DATAREEVAL,
      INCLUDRATA,
      AMOVECHI,
      PRETVECHI,
      NEUTILVECHI,
      SUBUNITATEA,
      DENUMIRE,
      CODPART,
      CODLOCATIE,
      CODAnalizaNod,
      CODSablon,
      CODCENTRU,
      OBS,
      DURATANF,
      DURATAFF,
      AMOF,
      DURATANG,
      DURATAFG,
      AMOG,
      ANINTRAREG,
      LUNAINTRAREG,
      DFBlocat_F,
      DFBlocat_G,
      REZERVA,
      REZERVABLOCAT,
      SERIEINV,
      AMOBLOCAT,
      CODMIFIXIMB,
      CENTRUBLOCAT,
      CODCLASIFBLOCAT,
      CODPERSBLOCAT,
      NODANALIZABLOCAT,
      CODAUTO,
      AMOREZERVA,
      AMORBLOCAT,
      AMOFBLOCAT,
      AMOGBLOCAT,
      PRETINIBLOCAT,
      PRETINITIAL_FBLOCAT,
      PRETINITIAL,
      PRETINITIAL_F,
      CODLOCATIESTOC,
      UTILAJ,
      CODUTILAJ,
      TIPSTORNO,
      AMOANPREC)
  SELECT row_number() over() , a_pg.*
  FROM (   SELECT MF. CODMIFIX,
        MF.TIP,
        MF.NRINVENTAR,
        ANINTRARE,
        LUNAINTRARE,
        CODMIFIX1,
        MF1.CODNIRSTOC,
        MF1.PRET,
        CANT,
        CODCLASIF,
        TIPAMO,
        MF1.STARE,
        DURATAN,
        GRADU,
        DURATAF,
        AMO,
        NEUTIL,
        DFBLOCAT,
        CODPERS,
        MF1.CODNIRSER,
        ANSTART,
        LUNASTART,
        NS.CODIOART,
        N.GEST,
        SER.SERIE,
        TIPREEVAL,
        DATAREEVAL,
        INCLUDRATA,
        AMOVECHI,
        PRETVECHI,
        NEUTILVECHI,
        G.CODSUBUNIT,
        O.DENUMIRE,
        MF1.CODPART,
        MF1.CODLOCATIE,
        MF1.CODAnalizaNod,
        MF1.CODSablon,
        MF1.CODCENTRU,
        MF.OBS,
        MF1.DURATANF,
        MF1.DURATAFF,
        MF1.AMOF,
        MF1.DURATANG,
        MF1.DURATAFG,
        MF1.AMOG,
        MF.ANINTRAREG,
        MF.LUNAINTRAREG,
        DFBLOCAT_F,
        DFBLOCAT_G,
        REZERVA,
        REZERVABLOCAT,
        MF.SERIEINV,
        MF1.AMOBLOCAT,
        MF.CODMIFIXIMB,
        MF1.CENTRUBLOCAT,
        MF1.CODCLASIFBLOCAT,
        MF1.CODPERSBLOCAT,
        MF1.NODANALIZABLOCAT,
        MF1.CODAUTO,
        MF1.AMOREZERVA,
        MF1.AMORBLOCAT,
        MF1.AMOFBLOCAT,
        MF1.AMOGBLOCAT,
        MF1.PRETINIBLOCAT,
        MF1.PRETINITIAL_FBLOCAT,
        MF1.PRETINITIAL,
        MF1.PRETINITIAL_F,
        NS.CODLOCATIE     CODLOCATIESTOC,
        U.ETICHETA||'/'||OU.DENUMIRE UTILAJ,
        U.CODUTILAJ,
        MF1.TIPSTORNO,
        MF1.AMOANPREC
      FROM MIFIX          MF
        LEFT JOIN UTILAJE U    ON U.NRINVENTAR   = MF.Nrinventar
        LEFT JOIN NARTOBJ OU   ON U.CODOBIECT    = OU.CODOBIECT,
        MIFIX1            MF1
        LEFT JOIN NIRSTOC NS   ON NS.CODNIRSTOC  = MF1.CODNIRSTOC
        LEFT JOIN NIR     N    ON N.CODNIR       = NS.CODNIR
        LEFT JOIN NGEST   G    ON G.CODGEST      = N.GEST
        LEFT JOIN NIRSER  NSER ON NSER.CODNIRSER = MF1.CODNIRSER
        LEFT JOIN NSERII  SER  ON SER.CODSERIE   = NSER.CODSERIE, NARTOBJ O
      WHERE
        MF.CODMIFIX = MF1.CODMIFIX
        AND MF1.CODNIRSTOC = RECID
        AND MF1.ANSTART * 12 + MF1.LUNASTART = current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric * 12 + current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric
        AND O.CODOBIECT = NS.CODOBIECT
      ORDER BY
        NRINVENTAR) A_PG;

  UPDATE TMP_MIFIX M
  SET
    DENLOCATIE = (SELECT OBS FROM NAGENDA WHERE CODAGENDA = M.CODLOCATIE) ,
    INFOMFIMB  = PKG_MIFIX_GetINFOMFIMB (M.CODMIFIXIMB);

  INSERT INTO TMP_JURNAL
  (SELECT * FROM JURNAL
   WHERE
        TIPDOC = 36
        AND CODDOC IN (SELECT  DISTINCT CODMIFIX FROM TMP_MIFIX)
        AND AN   = current_setting ('PKG_GLOBALS.ANLUCRU'  , true) ::numeric
        AND LUNA = current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric);

  INSERT INTO TMP_JURNAL1
  (SELECT * FROM JURNAL1
   WHERE
        TIPDOC = 36
        AND CODDOC IN (SELECT  DISTINCT CODMIFIX FROM TMP_MIFIX)
        AND AN   = current_setting ('PKG_GLOBALS.ANLUCRU'  , true) ::numeric
        AND LUNA = current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric);

  DELETE FROM TMP_RULAJ;
  DELETE FROM TMP_MIFIX_INITIAL;

  INSERT INTO TMP_MIFIX_INITIAL (CODMIFIX)
  SELECT CODMIFIX FROM TMP_MIFIX;

  SELECT COUNT(*) INTO NR FROM TMP_MASTERMIFIX WHERE CODCLASIF IS NOT NULL;

  IF NR = 0 THEN
    UPDATE TMP_MASTERMIFIX
    SET CODCLASIF = (SELECT MIN (CODCLASIF) FROM TMP_MIFIX);
  END IF;

  SELECT COUNT(*) INTO NR FROM TMP_MASTERMIFIX WHERE DURATAN IS NOT NULL;

  IF NR = 0 THEN
    UPDATE TMP_MASTERMIFIX
    SET
      (DURATAN, DURATANF, DURATANG) = (SELECT MIN (DURATAN) , MIN (DURATANF) , MIN (DURATANG) FROM TMP_MIFIX);
  END IF;

  UPDATE TMP_MASTERMIFIX
  SET CODCLASIFBLOCAT = (SELECT MIN (COALESCE (CODCLASIFBLOCAT, 0)) FROM TMP_MIFIX);

  INSERT INTO TMP_FISAMF (CODFISAMF,
      CODMIFIX,
      CODOPERATIE,
      DATAOPERATIE,
      GESTSURSA,
      GESTDEST,
      PRETI,
      PRETE,
      PREFIXDOC,
      NRDOC,
      CANT,
      OBS,
      INFOOPERATIE,
      DENGESTSURSA,
      DENGESTDEST,
      CODDOC1,
      TIPDOC)
  SELECT CODFISAMF,
    CODMIFIX,
    CODOPERATIE,
    DATAOPERATIE,
    GESTSURSA,
    GESTDEST,
    PRETI,
    PRETE,
    PREFIXDOC,
    NRDOC,
    CANT,
    OBS,
    (
      CASE
        WHEN CODOPERATIE =  1 THEN 'Creare mijloc fix'
        WHEN CODOPERATIE =  2 THEN 'Transfer intre gestiuni'
        WHEN CODOPERATIE =  3 THEN 'Modificare de pret'
        WHEN CODOPERATIE =  4 THEN 'Casare'
        WHEN CODOPERATIE =  5 THEN 'Vanzare'
        WHEN CODOPERATIE =  6 THEN 'Reevaluare - valoare MF'
        WHEN CODOPERATIE =  7 THEN 'Reevaluare - amortizare prec'
        WHEN CODOPERATIE =  8 THEN 'Marire de stoc'
        WHEN CODOPERATIE =  9 THEN 'Modificare gestiune'
        WHEN CODOPERATIE = 10 THEN 'Modificare centru de cost'
        WHEN CODOPERATIE = 11 THEN 'Modificare tip contabil'
        WHEN CODOPERATIE = 12 THEN 'Punere in functiune'
      END),
    (SELECT DEN_GEST FROM NGEST WHERE CODGEST = GESTSURSA) ,
    (SELECT DEN_GEST FROM NGEST WHERE CODGEST = GESTDEST) ,
    CODDOC1,
    TIPDOC
  FROM FISAMF WHERE CODMIFIX IN (SELECT CODMIFIX FROM TMP_MIFIX);

  DELETE FROM TMP_FISAMF_INI;

  INSERT INTO TMP_FISAMF_INI SELECT * FROM TMP_FISAMF;

  BEGIN
    SELECT CODCLASIF INTO aCODCLASIF FROM TMP_MIFIX limit 1;
  EXCEPTION
  WHEN OTHERS THEN
    aCODCLASIF := 0;
  END;

  IF aCODCLASIF &lt;&gt; 0 THEN
    UPDATE TMP_MASTERMIFIX SET CODCLASIF = aCODCLASIF;
  END IF;

 FOR v_rec in (SELECT M1.*
                FROM
                  TMP_MIFIX M1
                  INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = M1.CODNIRSTOC
                  INNER JOIN NIR N ON N.CODNIR = NS.CODNIR AND N.TIPNIR = 6
               )
  LOOP
  --  insert into x(view_name) values('1');
  SELECT MIN(CODMIFIX) INTO aCODMIFIXVECHI
    FROM MIFIX
    WHERE CODMIFIXNOU = V_REC.CODMIFIX and ANLUNAMIFIXNOU = getANLUCRU() * 12 + getLUNALUCRU();
  --  insert into x(view_name) values(aCODMIFIXVECHI);

    IF aCODMIFIXVECHI &gt; 0 THEN
      UPDATE TMP_MIFIX
      SET
        CODMIFIXVECHI = aCODMIFIXVECHI,
        NRINVENTARVECHI = (SELECT NRINVENTAR FROM MIFIX WHERE CODMIFIX = aCODMIFIXVECHI)
      WHERE
        CODMIFIX = V_REC.CODMIFIX;
    END IF;
  END LOOP;

  PERFORM PKG_CFGTABLES_EXT_GOTORECORD(36);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_mifix_updatemifixstruct</obj_name>
  <obj_hashval>d8489051d14831ebde9e8be41819e2f1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_mifix_updatemifixstruct(acodnirstocvechi numeric, acodnirstocnou numeric, acodmifix1 numeric, acodcentru numeric, aan numeric, aluna numeric, acodclasif numeric, astare numeric, atipoperatie numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCod             numeric;
  aCount           numeric;
  aCodMifix        numeric;
  aDurataF         numeric;
  aDurata          numeric;
  aDurataG         numeric;
  OldCodClasif     numeric;
  aCodClasifBlocat numeric;  --add 14.01.2021
BEGIN
  --Florin 28.07.2021 - fixat 50901
  --Adina 14.01.2021 sinc.Oracle - am comentat versiunea veche si am adus ce era pe martor
/*
  BEGIN
    SELECT DURATA, DURATAF, DURATAG INTO aDurata, aDURATAF, aDurataG FROM MFCLASIF WHERE CODCLASIF = aCODCLASIF;
  EXCEPTION WHEN others THEN
    aDurata := 0;
    aDurataF := 0;
    aDurataG := 0;
  END;

  BEGIN
    SELECT codmifix INTO aCodMifix FROM mifix1 WHERE codmifix1 = aCodMifix1;
  EXCEPTION WHEN others THEN
    aCodMifix := 0;
  END;

  IF  aCodMifix &gt; 0 THEN
    SELECT count( *) INTO aCount FROM mifix1 WHERE anstart = aAn and  lunastart = aLuna and  codmifix = aCodMifix;

    IF  aCount = 0 THEN
      SELECT NEXTVAL('SEQ_MIFIX1_CODMIFIX1') INTO aCod;
      SELECT codclasif INTO OldCodClasif FROM mifix1 WHERE codmifix1 = aCodMifix1;

      IF  OldCodClasif &lt;&gt; aCodClasif THEN
        INSERT INTO mifix1(codmifix1, codmifix, codnirstoc, pret, cant, codclasif, tipamo, stare, duratan, gradu, durataf,
                           amo, neutil, dfblocat, codpers, anstart, lunastart, codnirser, tipreeval, datareeval, includrata,
                           amovechi, pretvechi, neutilvechi, codpart, codlocatie, codanalizanod, codcentru, duratanf, durataff,
                           amof, duratang, duratafg, amog, dfblocat_f, dfblocat_g, pretinitial, rezerva, rezervablocat, codsablon, amoblocat
                          )
        SELECT aCod, codmifix, aCodNirStocNou, pret, cant, codclasif, tipamo, aStare, adurata, gradu, adurata * 12, amo, neutil,
               dfblocat, codpers, aAn, aLuna, codnirser, tipreeval, datareeval, includrata, amovechi, pretvechi, neutilvechi, codpart,
               codlocatie, codanalizanod, aCodCentru, durataf, adurataf * 12, amof, aduratag, aduratag * 12, amog, dfblocat_f,
               dfblocat_g, pretinitial, rezerva, rezervablocat, codsablon, amoblocat
        FROM mifix1
        WHERE codmifix1 = aCodMifix1;
      ELSE
        INSERT INTO mifix1(codmifix1, codmifix, codnirstoc, pret, cant, codclasif, tipamo, stare, duratan, gradu, durataf, amo,
                           neutil, dfblocat, codpers, anstart, lunastart, codnirser, tipreeval, datareeval, includrata, amovechi,
                           pretvechi, neutilvechi, codpart, codlocatie, codanalizanod, codcentru, duratanf, durataff, amof,
                           duratang, duratafg, amog, dfblocat_f, dfblocat_g, pretinitial, rezerva, rezervablocat, codsablon, amoblocat
                          )
        SELECT aCod, codmifix, aCodNirStocNou, pret, cant, codclasif, tipamo, aStare, duratan, gradu, durataf, amo, neutil, dfblocat,
               codpers, aAn, aLuna, codnirser, tipreeval, datareeval, includrata, amovechi, pretvechi, neutilvechi, codpart, codlocatie,
               codanalizanod, aCodCentru, duratanf, durataff, amof, duratang, duratafg, amog, dfblocat_f, dfblocat_g, pretinitial, rezerva,
               rezervablocat, codsablon, amoblocat
        FROM mifix1
        WHERE codmifix1 = aCodMifix1;
      END IF;
    ELSE
      SELECT codclasif INTO OldCodClasif FROM mifix1 WHERE anstart = aAn and  lunastart = aLuna and  codmifix = aCodMifix;

      IF  OldCodClasif &lt;&gt; aCodClasif THEN
        UPDATE mifix1
        SET
          codclasif = aCodClasif,
          codnirstoc = aCodNirStocNou,
          Stare = aStare,
          durataf = adurata * 12,
          durataff = adurataf * 12,
          duratafg = aduratag * 12,
          duratan = adurata,
          duratanf = adurataf,
          duratang = aduratag,
          CodCentru = aCodCentru
        WHERE anstart = aAn and  lunastart = aLuna and  codmifix = aCodMifix;
      ELSE
        UPDATE mifix1
        SET
          codclasif = aCodClasif,
          codnirstoc = aCodNirStocNou,
          Stare = aStare,
          CodCentru = aCodCentru
        WHERE anstart = aAn and  lunastart = aLuna and  codmifix = aCodMifix;
      END IF;
    END IF;

    SELECT count( *) INTO acount FROM mastermifix WHERE codnirstoc = acodnirstocnou;

    IF  acount &gt; 0 THEN
      UPDATE mastermifix
      SET
        codclasif = aCodClasif,
        codnirstoc = aCodNirStocNou,
        duratan = adurata,
        duratanf = adurataf,
        duratang = aduratag
      WHERE codnirstoc = aCodNirStocNou;
    ELSE
      INSERT INTO mastermifix(codnirstoc, codclasif, duratan, duratanf, duratang, codanaliza)
      SELECT aCodNirStocNou, acodclasif, adurata, adurataf, aduratag, codanaliza
      FROM mastermifix
      WHERE codnirstoc = acodnirstocvechi;
    END IF;
  END IF;
*/
  aCodClasifBlocat := 0;
  IF  aTipOperatie = 12 THEN  aCodClasifBlocat := 1; END IF;

  BEGIN
    SELECT DURATA, DURATAF, DURATAG INTO aDurata, aDURATAF, aDurataG FROM MFCLASIF WHERE CODCLASIF = aCODCLASIF;
  EXCEPTION WHEN others THEN
    aDurata  := 0;
    aDurataF := 0;
    aDurataG := 0;
  END;

  BEGIN
    SELECT codmifix INTO aCodMifix FROM mifix1 WHERE codmifix1 = aCodMifix1;
  EXCEPTION WHEN others THEN
    aCodMifix := 0;
  END;

  IF  aCodMifix &gt; 0 THEN
    SELECT count(*) INTO aCount FROM mifix1 WHERE anstart = aAn and  lunastart = aLuna and  codmifix = aCodMifix;

    IF  aCount = 0 THEN
      SELECT NEXTVAL('SEQ_MIFIX1_CODMIFIX1') INTO aCod;
      SELECT codclasif INTO OldCodClasif FROM mifix1 WHERE codmifix1 = aCodMifix1;

      IF  OldCodClasif &lt;&gt; aCodClasif THEN
        INSERT INTO mifix1(codmifix1, codmifix, codnirstoc, pret, cant, codclasif, tipamo, stare, duratan, gradu, durataf, amo,
                           neutil, dfblocat, codpers, anstart, lunastart, codnirser, tipreeval, datareeval, includrata, amovechi,
                           pretvechi, neutilvechi, codpart, codlocatie, codanalizanod, codcentru, duratanf, durataff, amof, duratang,
                           duratafg, amog, dfblocat_f, dfblocat_g, pretinitial, pretinitial_f, pretinitial_fblocat, rezerva,
                           rezervablocat, codsablon, amoblocat
                          )
        SELECT aCod, codmifix, aCodNirStocNou, pret, cant, codclasif, tipamo, aStare, adurata, gradu, adurata * 12, amo, neutil,
               dfblocat, codpers, aAn, aLuna, codnirser, tipreeval, datareeval, includrata, amovechi, pretvechi, neutilvechi,
               codpart, codlocatie, codanalizanod, aCodCentru, durataf, adurataf * 12, amof, aduratag, aduratag * 12, amog,
               dfblocat_f, dfblocat_g, pretinitial, pretinitial_f, pretinitial_fblocat, rezerva, rezervablocat, codsablon, amoblocat
        FROM mifix1
        WHERE codmifix1 = aCodMifix1;

        IF  aCodClasifBlocat = 1 THEN
          UPDATE mifix1 SET codclasifblocat = 1 WHERE codmifix1 = aCod;
        END IF;
      ELSE
        INSERT INTO mifix1(codmifix1, codmifix, codnirstoc, pret, cant, codclasif, tipamo, stare, duratan, gradu, durataf, amo,
                           neutil, dfblocat, codpers, anstart, lunastart, codnirser, tipreeval, datareeval, includrata, amovechi,
                           pretvechi, neutilvechi, codpart, codlocatie, codanalizanod, codcentru, duratanf, durataff, amof,
                           duratang, duratafg, amog, dfblocat_f, dfblocat_g, pretinitial, pretinitial_f, pretinitial_fblocat,
                           rezerva, rezervablocat, codsablon, amoblocat
                          )
        SELECT aCod, codmifix, aCodNirStocNou, pret, cant, codclasif, tipamo, aStare, duratan, gradu, durataf, amo, neutil, dfblocat,
               codpers, aAn, aLuna, codnirser, tipreeval, datareeval, includrata, amovechi, pretvechi, neutilvechi, codpart, codlocatie,
               codanalizanod, aCodCentru, duratanf, durataff, amof, duratang, duratafg, amog, dfblocat_f, dfblocat_g,
               pretinitial, pretinitial_f, pretinitial_fblocat, rezerva, rezervablocat, codsablon, amoblocat
        FROM mifix1
        WHERE  codmifix1 = aCodMifix1;
      END IF;
    ELSE
      SELECT codclasif INTO OldCodClasif FROM mifix1 WHERE anstart = aAn and  lunastart = aLuna and  codmifix = aCodMifix;

      IF  OldCodClasif &lt;&gt; aCodClasif THEN
        UPDATE mifix1
        SET
          codclasif  = aCodClasif,
          codnirstoc = aCodNirStocNou,
          Stare      = aStare,
          durataf    = adurata * 12,
          durataff   = adurataf * 12,
          duratafg   = aduratag * 12,
          duratan    = adurata,
          duratanf   = adurataf,
          duratang   = aduratag,
          CodCentru  = aCodCentru
        WHERE anstart = aAn and  lunastart = aLuna and  codmifix = aCodMifix;

        IF  aCodClasifBlocat = 1 THEN
          UPDATE mifix1
          SET
            codclasifblocat = 1
          WHERE anstart = aAn and  lunastart = aLuna and  codmifix = aCodMifix;
        END IF;
      ELSE
        UPDATE mifix1
        SET
          codclasif  = aCodClasif,
          codnirstoc = aCodNirStocNou,
          Stare      = aStare,
          CodCentru  = aCodCentru
        WHERE anstart = aAn and  lunastart = aLuna and  codmifix = aCodMifix;
      END IF;
    END IF;

    SELECT count(*) INTO acount FROM mastermifix WHERE codnirstoc = acodnirstocnou;

    IF  acount &gt; 0 THEN
      UPDATE mastermifix
      SET
        codclasif  = aCodClasif,
        codnirstoc = aCodNirStocNou,
        duratan    = adurata,
        duratanf   = adurataf,
        duratang   = aduratag
      WHERE codnirstoc = aCodNirStocNou;

      IF  OldCodClasif &lt;&gt; aCodClasif and  aCodClasifBlocat = 1 THEN
        UPDATE mastermifix
        SET
          codclasifblocat = 1
        WHERE codnirstoc = aCodNirStocNou;
      END IF;
    ELSE
      INSERT INTO mastermifix(codnirstoc, codclasif, duratan, duratanf, duratang, codanaliza)
      SELECT aCodNirStocNou, acodclasif, adurata, adurataf, aduratag, codanaliza
      FROM mastermifix
      WHERE codnirstoc = acodnirstocvechi;

      IF  OldCodClasif &lt;&gt; aCodClasif and  aCodClasifBlocat = 1 THEN
        UPDATE mastermifix
        SET
          codclasifblocat = 1
        WHERE codnirstoc = aCodNirStocNou;
      END IF;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_check_transf_mifix_seriebucata</obj_name>
  <obj_hashval>c966563ffe529f2a69da6758b7bbd80c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_check_transf_mifix_seriebucata(acodtransf numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  V_REC RECORD;

begin
  --Florin 04.12.2025 - sinc. Oracle
  --Florin 22.11.2023 - fixat 60148
  --Florin 14.11.2023 - sinc. Oracle
  --Florin 22.06.2022 - sinc. Oracle (21.06.2022)
  if current_setting('pkg_miscari_interne.vCodMifix', true)::NUMERIC &gt; 0 then
  for V_REC in (
  SELECT M1.CODMIFIX1, M1.CODMIFIX, MF_TRANSF.*, M.TIP, M1.ANSTART, M1.LUNASTART
    FROM
     MIFIX1 M1, MIFIX M,
    (
  select
    NSP.CODNIRSTOC CODNIRSTOPARINTE,
    NSP.CANTNIR as CANTNIRPARINTE,
    NSEP.CODNIRSER as CODNIRSSERPARINTE,
    NSD.CODNIRSTOC CODNIRSTOCDEST,
    NSED.CODNIRSER as CODNIRSERDEST,
    L1.CANT,
    L.DATALIVR,
    NP.GEST as GESTSURSA,
    ND.GEST as GESTDEST,
    NSP.PRET as PRETE,
    NSD.PRET as PRETI,
    NSD.CODTRANSF1,
    NSP.CODIOART AS CODIOARTP,
    NSD.CODIOART AS CODIOARTD,
    T.NRDOC
  from
    LIVR1 L1,
    LIVR L,
    TRANSF T,
    NIRSER NSEP,
    NIRSTOC NSD,
    NIRSER NSED,
    NIRSTOC NSP,
    NIR ND,
    NIR NP,
    TMP_IOART_LUNA IOA
  where
    L.CODTRANSF = aCODTRANSF
    and L1.CODLIVR = L.CODLIVR
    and NSEP.CODNIRSER = L1.CODNIRSER
    and NSD.CODLIVR1 = L1.CODLIVR1
    and IOA.CODIOART = NSD.CODIOART
    and (IOA.ESTEMIFIX = 1 or IOA.ESTEOBINV = 1)
    and NSED.CODNIRSTOC = NSD.CODNIRSTOC
    and NSP.CODNIRSTOC = L1.CODNIRSTOC
    and coalesce( NSP.TIPSERIE, 0) = 1
    and L1.CANT = 1
    and ND.CODNIR = NSD.CODNIR
    and NP.CODNIR = NSP.CODNIR
    and L.CODTRANSF = T.CODTRANSF ) MF_TRANSF
where
  M1.ANSTART * 12 + M1.LUNASTART &gt;= TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)), '999999999999999999') * 12 + TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)), '999999999999999999')
  and M1.CODNIRSTOC = MF_TRANSF.CODNIRSTOPARINTE
  and coalesce( M1.CODNIRSER, 0) = coalesce( MF_TRANSF.CODNIRSSERPARINTE, 0)
  AND M1.CODMIFIX = vCodMifix AND M.CODMIFIX = M1.CODMIFIX
    )
    LOOP
      IF V_REC.CODIOARTP &lt;&gt; V_REC.CODIOARTD   AND V_REC.TIP = 'MF' THEN
        perform pkg_miscari_interne_MAKE_MIFIX_NOU(V_REC.CODMIFIX, V_REC.CODMIFIX1, V_REC.ANSTART, V_REC.LUNASTART);
      END IF;
update
  MIFIX1
set
  CODNIRSTOC = V_REC.CODNIRSTOCDEST,
  CODNIRSER = V_REC.CODNIRSERDEST
where
  CODMIFIX1 = V_REC.CODMIFIX1;
if v_rec.ESTEMIFIX = 1 then
insert
  into
  FISAMF(CODFISAMF, CODMIFIX, CODOPERATIE, DATAOPERATIE, GESTSURSA, GESTDEST, PRETI, PRETE, PREFIXDOC, NRDOC, CANT, CODDOC1, TIPDOC)
values(NEXTVAL('SEQ_FISAMF_CODFISAMF'), V_REC.CODMIFIX, 2, V_REC.DATALIVR, V_REC.GESTSURSA, V_REC.GESTDEST, V_REC.PRETI, V_REC.PRETE, 'NT', V_REC.NRDOC, 1, V_REC.CODTRANSF1, 12);

update
  JURNAL1
set
  DIRTY = 1
where
  CODDOC = V_REC.CODMIFIX
  and TIPDOC = 36 AND AN * 12 + LUNA &gt;= getANLUCRU() * 12 + getLUNALUCRU();

end if;
end loop;
ELSE
  PERFORM pkg_miscari_interne_Solve_TRANSF_MIFIX_serie(aCODTRANSF, 1); --1 = cu legatura in TRANSF1
  PERFORM pkg_miscari_interne_Solve_TRANSF_MIFIX_serie(aCODTRANSF, 0); --0 = fara legatura in TRANSF1
END IF;
end;

$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_miscari_interne_set_session_livrdinreztransf</obj_name>
  <obj_hashval>b78c9cae02b5f5c8ac53c0c707d821b6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_miscari_interne_set_session_livrdinreztransf(aflag numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 16.10.2024 - sinc. Oracle
  perform set_config('pkg_miscari_interne.v$Session_LivrDinRezTransf', (aFlag)::varchar , false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_modif_centre_cost_x_doc_actualizarecentrecost</obj_name>
  <obj_hashval>8e3da0db9d41b7e5d28387b2f73ecb8e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_modif_centre_cost_x_doc_actualizarecentrecost(pdatastart character varying, pdataend character varying, centrucostini numeric, centrucostnew numeric, pcodgest numeric DEFAULT NULL::numeric, pcodanalizanod numeric DEFAULT NULL::numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  codCentruCostIni        NUMERIC(20);
    codCentruCostNew        NUMERIC(20);
    dataStartVar               Date;
    dataEndVar                 Date;
    listaTipDocDeModificat          NUMERIC array default array[1,2,3,4,5,6,7,8,9,14,15,16,18,19,20,21,24,26,28,29,30,31,35];
    listaTipDocDeModificatObligpif  NUMERIC array default array[6,7,14,15,16,18,28,29,30,31];
    vCodGest                NUMERIC(20);
    vCodAnalizaNod          NUMERIC(20);
    v_cnt numeric;
begin
    dataStartVar   := to_date(pDataStart, 'dd.mm.yyyy');
    dataEndVar     := to_date(pDataEnd, 'dd.mm.yyyy');
    vCodGest       := case when coalesce(pCodGest,0) = 0 then null else pCodGest end;
    vCodAnalizaNod := case when coalesce(pCodAnalizaNod,0) = 0 then null else pCodAnalizaNod end;
    BEGIN
      IF centruCostIni is not null AND centruCostIni &gt; 0 THEN
        SELECT cc.codcentru
          into strict codCentruCostIni
          FROM centrecost cc
         WHERE cc.codcentru = centruCostIni;
      ELSE
        RAISE EXCEPTION  'Centru de cost initial null!'
        USING ERRCODE = '22023',
              DETAIL = '',
              HINT = '';
      END IF;
    EXCEPTION
      WHEN NO_DATA_FOUND THEN
        RAISE EXCEPTION  'Centru de cost initial negasit!';
    END;
    BEGIN
      IF centruCostNew is not null AND centruCostNew &gt; 0 THEN
        SELECT cc.codcentru
          INTO STRICT codCentruCostNew
          FROM centrecost cc
         WHERE cc.codcentru = centruCostNew;
      ELSE
        RAISE EXCEPTION  'Centru de cost destinatie null!'
        USING ERRCODE = '22023',
              DETAIL = '',
              HINT = '';
      END IF;
    EXCEPTION
      WHEN NO_DATA_FOUND THEN
         RAISE EXCEPTION  'Centru de cost destinatie negasit!';
    END;
    -- pt tipdoc = 5 trebuie in loc de codintr1 coddvi1, indexlocal din juranal1 este completat cu coddvi1
    -- completez in temporar pe coloana codjurnal
    -- COD GESTIUNE =&gt; CONTD,  COD ANALIZA NOD =&gt; CONTC
    DELETE FROM TMP_JURNAL;
    insert into TMP_JURNAL
      (OBS, TIPDOC, CODDOC, INDEXLOCAL, CODJURNAL, CONTD, CONTC)
      select 'intrari1',
             intr.tipdoc,
             intr.codintr,
             intr1.codintr1,
             dv1.coddvi1,
             case when intr1.tiplinie = 'S' then intr1.gestact else nr.gest end as gest,
             intr1.codanalizanod
        from intrari intr
        join intrari1 intr1
          on intr1.codintr = intr.codintr
        left join dvi1 dv1
          on dv1.codintr1 = intr1.codintr1
        left join nirstoc nst on case when dv1.coddvi1 is null then nst.codintr1 else nst.coddvi1 end = coalesce(dv1.coddvi1,intr1.codintr1)
        left join nir nr on nr.codnir = nst.codnir
       where intr.datadoc between dataStartVar and dataEndVar
         and intr.tipdoc = ANY(listaTipDocDeModificat)
         and coalesce(intr1.codcentru, 0) = codCentruCostIni
      union all --iesiri
      select 'iesiri1',
       ies.TIPDOC,
       ies.CODIES,
       ies1.CODIES1,
       null,
       CASE
         WHEN ies1.TIPLINIE = 'S' THEN
          ies1.GESTACT
         ELSE
          (CASE
            WHEN lv.CODLIVR1 IS NULL THEN
             n.GEST
            ELSE
             lv.GEST
          END)
       end as gest,
       ies1.codanalizanod
        FROM IESIRI ies
        JOIN IESIRI1 ies1
          ON IES1.codies = IES.codies
        LEFT JOIN LIVR1 lvr1
          ON lvr1.CODIES1 = ies1.CODIES1
        LEFT JOIN NIRSTOC ns
          ON ns.CODNIRSTOC = lvr1.CODNIRSTOC
        LEFT JOIN LIVRVAL lv
          ON lv.CODLIVR1 = lvr1.CODLIVR1
        LEFT JOIN NIR n
          ON n.CODNIR = ns.CODNIR
       where ies.datadoc between dataStartVar and dataEndVar
         and ies.tipdoc = ANY(listaTipDocDeModificat)
         and coalesce(ies1.codcentru, 0) = codCentruCostIni
      union all --comanda
       select 'comanda1',
         cmd.tipdoc,
         cmd.codcomanda,
         cmd1.codcomanda1,
         null,
         cmd1.gestact,
         cmd1.codanalizanod
       from comanda cmd
       join comanda1 cmd1
          on cmd1.codcomanda = cmd.codcomanda
       where cmd.datadoc between dataStartVar and dataEndVar
         and cmd.tipdoc = ANY(listaTipDocDeModificat)
         and coalesce(cmd1.codcentru, 0) = codCentruCostIni
      union all -- trezor codcentru este in obligpif si coddoc din general este codtrezor1
      select 'trezor1', trz.tipdoc, trz.codtrezor, trz1.codtrezor1, null, opf.codgest, opf.codanalizanod
        from trezor trz
        join trezor1 trz1
          on trz1.codtrezor = trz.codtrezor
        join general gn
          on gn.coddoc = trz1.codtrezor1
         and gn.tipdoc = trz.tipdoc
        join obligpif opf
          on opf.codgeneral = gn.codgeneral
       where trz.datadoc between dataStartVar and dataEndVar
         and trz.tipdoc = ANY(listaTipDocDeModificat)
         and coalesce(opf.codcentru, 0) = codCentruCostIni
      union all -- compens
      select 'compens', 28, cmps.codcompens, cmps.codcompens, null, cmps.codgest, opf.codanalizanod
        from compens cmps
        join general gn
          on gn.coddoc = cmps.codcompens
         and gn.tipdoc = 28
        join obligpif opf
          on opf.codgeneral = gn.codgeneral
       where cmps.datadoc between dataStartVar and dataEndVar
         and coalesce(cmps.codcentru, 0) = codCentruCostIni
      union all -- nc
      select 'nc1', 35, nca.codnc, nca1.codnc1, null,nca1.codgest,nca1.codanalizanod
        from nc nca
        join nc1 nca1
          on nca1.codnc = nca.codnc
       where (nca.datadoc) between dataStartVar and dataEndVar
         and coalesce(nca1.codcentru, 0) = codCentruCostIni;

       GET DIAGNOSTICS v_cnt = ROW_COUNT;

    if v_cnt = 0 THEN
      raise exception 'Nu sunt randuri pentru update';
    end if;

    --- update detalii
    ---UPDATE INTRARI
    update intrari1 i1
       set codcentru = codCentruCostNew
     where i1.codintr1 IN (select tmc.INDEXLOCAL
                             from TMP_JURNAL tmc
                            where tmc.OBS = 'intrari1'
                             and coalesce(vCodGest,1) = case when vCodGest is null then 1 else tmc.contd end
                             and coalesce(vCodAnalizaNod,1) = case when vCodAnalizaNod is null then 1 else tmc.contc end);
    ---UPDATE IESIRI
    update iesiri1 i1
       set codcentru = codCentruCostNew
     where i1.codies1 IN (select tmc.INDEXLOCAL
                            from TMP_JURNAL tmc
                           where tmc.OBS = 'iesiri1'
                           and coalesce(vCodGest,1) = case when vCodGest is null then 1 else tmc.contd end
                           and coalesce(vCodAnalizaNod,1) = case when vCodAnalizaNod is null then 1 else tmc.contc end);
    ---UPDATE COMANDA
    update comanda1 i1
       set codcentru = codCentruCostNew
     where i1.codcomanda1 IN
           (select tmc.INDEXLOCAL
              from TMP_JURNAL tmc
             where tmc.OBS = 'comanda1'
             and coalesce(vCodGest,1) = case when vCodGest is null then 1 else tmc.contd end
             and coalesce(vCodAnalizaNod,1) = case when vCodAnalizaNod is null then 1 else tmc.contc end);
    ---UPDATE COMPENS
    update compens i1
       set codcentru = codCentruCostNew
     where i1.codcompens IN (select tmc.INDEXLOCAL
                               from TMP_JURNAL tmc
                              where tmc.OBS = 'compens'
                              and coalesce(vCodGest,1) = case when vCodGest is null then 1 else tmc.contd end
                              and coalesce(vCodAnalizaNod,1) = case when vCodAnalizaNod is null then 1 else tmc.contc end);
    ---UPDATE NC
    update nc1 i1
       set codcentru = codCentruCostNew
     where i1.codnc1 IN
           (select tmc.INDEXLOCAL from TMP_JURNAL tmc where tmc.OBS = 'nc1'
           and coalesce(vCodGest,1) = case when vCodGest is null then 1 else tmc.contd end
           and coalesce(vCodAnalizaNod,1) = case when vCodAnalizaNod is null then 1 else tmc.contc end);
    ----update detalii term
    --- UPDATE OBLIGPIF
    update obligpif opf
       set codcentru = codCentruCostNew
     where opf.codgeneral in
           (SELECT g.codgeneral
              FROM GENERAL g
             WHERE (g.TIPDOC, g.CODDOC) IN
                   (SELECT tmcc.TIPDOC,
                           case
                             when tmcc.TIPDOC in (29, 30, 31) then
                              tmcc.INDEXLOCAL
                             else
                              tmcc.CODDOC
                           end
                      FROM TMP_JURNAL tmcc
                      where tmcc.TIPDOC = ANY(listaTipDocDeModificatObligpif)
                          and coalesce(vCodGest,1) = case when vCodGest is null then 1 else tmcc.contd end
                          and coalesce(vCodAnalizaNod,1) = case when vCodAnalizaNod is null then 1 else tmcc.contc end))
       and coalesce(opf.codcentru, 0) = codCentruCostIni
       and coalesce(vCodGest,1) = case when vCodGest is null then 1 else opf.codgest end
       and coalesce(vCodAnalizaNod,1) = case when vCodAnalizaNod is null then 1 else opf.codanalizanod end;
    ---UPDATE JURNAL
   update JURNAL JRN
        set codcentru = codCentruCostNew
     WHERE (JRN.CODDOC, JRN.TIPDOC, case when JRN.TIPDOC IN (29,30,31,35) then JRN.INDEXLOCAL ELSE -1 END ) IN
           (SELECT tmcc.CODDOC, tmcc.TIPDOC, case when tmcc.TIPDOC IN (29,30,31,35) then tmcc.INDEXLOCAL ELSE -1 END
              FROM TMP_JURNAL tmcc
              WHERE coalesce(vCodGest,1) = case when vCodGest is null then 1 else tmcc.contd end
                  and coalesce(vCodAnalizaNod,1) = case when vCodAnalizaNod is null then 1 else tmcc.contc end)
       AND coalesce(JRN.codcentru, 0) = codCentruCostIni
       and coalesce(vCodGest,1) = case when vCodGest is null then 1 else JRN.gest end
       and coalesce(vCodAnalizaNod,1) = case when vCodAnalizaNod is null then 1 else JRN.codanalizanod end;
    ---UPDATE JURNAL1
    update JURNAL1 JRN1
       set codcentru = codCentruCostNew
     WHERE (JRN1.CODDOC, JRN1.TIPDOC, JRN1.INDEXLOCAL) IN
           (SELECT tmcc.CODDOC,
                   tmcc.TIPDOC,
                   case
                     when tmcc.tipdoc = 5 then
                      tmcc.codjurnal
                     else
                      tmcc.INDEXLOCAL
                   end
              FROM TMP_JURNAL tmcc
              where coalesce(vCodGest,1) = case when vCodGest is null then 1 else tmcc.contd end
                and coalesce(vCodAnalizaNod,1) = case when vCodAnalizaNod is null then 1 else tmcc.contc end)
       AND coalesce(JRN1.codcentru, 0) = codCentruCostIni
       and coalesce(vCodGest,1) = case when vCodGest is null then 1 else JRN1.gest end
       and coalesce(vCodAnalizaNod,1) = case when vCodAnalizaNod is null then 1 else JRN1.codanalizanod end;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_monede_get_moneda_curenta</obj_name>
  <obj_hashval>d982904574119bf1d72070f9d65727f2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_monede_get_moneda_curenta(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER((current_setting('PKG_MONEDE.MONEDACURENTA',true)),'999999999999999999');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_monede_get_simbol_moneda</obj_name>
  <obj_hashval>6ff6a3132f2c7656150898e2e0243f83</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_monede_get_simbol_moneda(INOUT wme_result character varying, INOUT acodmoneda numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aSimbol varchar := '???';
begin
  BEGIN
    SELECT SIMBOL INTO aSimbol FROM NMONEDE WHERE CODMONEDA = aCodMoneda;
  EXCEPTION WHEN OTHERS THEN
    WME_Result :=  '???';
    RETURN;
  END;
  WME_Result :=  aSimbol;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_monede_testunicitatesimbol</obj_name>
  <obj_hashval>e5b590aa3f15df30a7d9f574d58a5ca7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_monede_testunicitatesimbol(INOUT wme_result numeric, INOUT asimbol character varying, INOUT acodmoneda numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCount numeric;
begin
  SELECT COUNT( CodMoneda) INTO aCount FROM NMONEDE WHERE UPPER( aSimbol) = UPPER( Simbol) AND  CodMoneda &lt;&gt; aCODMONEDA;
  WME_Result :=  aCount;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nc_genereazamodificaredepretmifix</obj_name>
  <obj_hashval>84df2bf7dffe8302a4eea106f5c0040e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nc_genereazamodificaredepretmifix(adatadoc date, aan numeric, aluna numeric, asubunitatea numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_M           RECORD;
  V_REC         RECORD;
  V_XXX         RECORD;
  aCount        numeric;
  aCodNIR       numeric;
  aCarnetTransf numeric;
  aCarnetLivr   numeric;
  aSerieTransf  varchar;
  aSimbolTransf varchar;
  aSerieLivr    varchar;
  aSimbolLivr   varchar;
  aNrTransf     numeric;
  aNrLivr       numeric;
  aCodTransf1   numeric;
  aCodLivr1     numeric;
  aCodTransf    numeric;
BEGIN
  --Florin 07.12.2022 - sinc. Oracle
  --Adina 14.08.2021 - sinc.Oracle din 13.08.2021 si 14.08.2021
  aCarnetTransf := current_setting('PKG_CARNETEDOC.CARNETTRANSF', true)::numeric;
  aCarnetLivr   := current_setting('PKG_CARNETEDOC.CARNETLIVR'  , true)::numeric;

  IF  aCarnetTransf = 0 or  aCarnetLivr = 0 THEN RETURN; END IF;

  FOR v_m IN (SELECT tmp.codintr1, tmp.pretpredare FROM tmp_manevra_intr1 tmp) LOOP
    FOR v_rec IN (SELECT NS.CODOBIECT, NS.PRET, 1 REST, NS.RESTUM1, NS.RESTUM2, NS.TIPDOCACHIZ, NS.TIPSERIE, NS.UMSEC, NS.DATAACHIZ, NS.FURN, NS.TVA AS TVANEEX,
                         NS.PUMAXIMAL, NS.CODNIRSTOC, NS.PROVIZION, NS.PUVAL, NS.D1, NS.D2, NS.D3, NS.CODGESTPROD, NS.CODLOCATIE, NS.ROTLEI, NS.ROTVALUTA,
                         NS.CANTFURN, NS.CANTNIR, O.DENUMIRE, N.GEST, IO.CODIOART, IO.DIFERENTE, IO.PUSTANDARD, IO.DIFPRET, IO.MG, IO.ARETVANEEX,
                         NC1.CONTD CONTSERV, NC1.CODMIFIX, 1 CANT, NS.PRET - NS.ADAOS AS PRETACHIZ, TL.CODTVA, TL.PROCENT AS PROCTVA,
                         NSE.CODNIRSER, NSE.CODSERIE, NSE.CODCERTIF, NSE.STARE, NSE.DATAPROD, NSE.OBS, COALESCE(NSE.TG, NS.TG) TG, O.ROTUNJIRE,
                         v_m.CODINTR1, v_m.PRETPREDARE, NUM1.PARITATE, MFIX.NRINVENTAR
                  FROM MIFIX1           MFIX1,
                       MIFIX            MFIX,
                       NIRSTOC          NS
                       LEFT JOIN NIRSER NSE ON  NSE.CODNIRSTOC = NS.CODNIRSTOC,
                       NARTOBJ          O,
                       TMP_NART_LUNA    AL,
                       TMP_NTVA_LUNA    TL,
                       TMP_IOART_LUNA   IO,
                       NIR              N,
                       NGEST            G,
                       NC1,
                       NUM1
                  WHERE
                         NC1.CODNC1       = v_m.CODINTR1
                    AND  MFIX1.CODNIRSTOC = NS.CODNIRSTOC
                    AND  MFIX.CODMIFIX    = NC1.CODMIFIX
                    AND  NC1.CODMIFIX     = MFIX1.CODMIFIX
                    AND  NS.CODOBIECT     = O.CODOBIECT
                    AND  O.CODARTICOL     = AL.CODARTICOL
                    AND  AL.CODTVA        = TL.CODTVA
                    AND  NS.CODNIR        = N.CODNIr
                    AND  NS.CODIOART      = IO.CODIOART
                    AND  N.GEST           = G.CODGEST
                    AND  NUM1.CODUM1      = NS.UMSEC
                    AND  MFIX1.ANSTART    = aAN
                    AND  MFIX1.LUNASTART  = aLUNA
                  ORDER BY CODOBIECT
                 )
    LOOP
      aCodTransf  := 0;
      aCodNir     := 0;
      aCodTransf1 := 0;
      aCodLivr1   := 0;

      DELETE FROM tmp_transf;
      DELETE FROM tmp_transf1;
      DELETE FROM tmp_nir;
      DELETE FROM tmp_livr;
      DELETE FROM tmp_nirstoc;
      DELETE FROM tmp_livr1;
      DELETE FROM TMP_NIRSTOC_RECOD;
      DELETE FROM TMP_IMBMIFIXLINK;
      DELETE FROM tmp_jurnal;
      DELETE FROM tmp_jurnal1;

      aNrTransf := (SELECT pkg_carnetedoc_GETNEXTNRDOC.WME_RESULT FROM pkg_carnetedoc_GETNEXTNRDOC(NULL,aCarnetTransf, aSerieTransf, aSimbolTransf));
      aNrLivr   := (SELECT pkg_carnetedoc_GETNEXTNRDOC.WME_RESULT FROM pkg_carnetedoc_GETNEXTNRDOC(NULL,aCarnetLivr, aSerieLivr, aSimbolLivr));

      INSERT INTO tmp_transf(codtransf, tipdoc, anulat, blocat, operat, prefixdoc, carnetdoc, nrdoc, datadoc, valdoc, tvadoc, an, luna,
                             tiprepsuplim, subunitatea, tipmodifpret, obs)
      VALUES(0, 13, 0, 0, 1, 'PV', aCarnetTransf, aNrTransf, aDataDoc, (V_REC.PRET + V_REC.PRETPREDARE)  * v_rec.rest, 0, aAn, aLuna,
             0, aSubunitatea, 4, 'Nr. inventar: ' || coalesce(V_REC.NRINVENTAR::varchar ,'') || ' - ' || coalesce(V_REC.DENUMIRE,''));

      INSERT INTO tmp_livr(codlivr, codtransf, carnetlivr, nrlivr, datalivr, tiplivr, anulat, blocat, operat)
      VALUES(-1, 0, aCarnetLivr, aNrLivr, aDataDoc, 13, 0, 0, 1);

      BEGIN
        SELECT count(*) INTO aCount FROM tmp_nir WHERE gest = v_rec.gest;
      EXCEPTION WHEN others THEN
        aCount := 0;
      END;

      IF  aCount = 0 THEN
        aCodNIR := aCodNIR - 1;
        INSERT INTO tmp_nir(codnir, codtransf, datanir, gest, tipnir, anulat, blocat, operat)
        VALUES(aCodNIR, 0, aDataDoc, v_rec.Gest, 13, 0, 0, 1);
      ELSE
        BEGIN
          SELECT codnir INTO aCodNIR FROM tmp_nir WHERE gest = v_rec.gest;
        EXCEPTION WHEN others THEN
          aCodNIR := aCodNIR - 1;
          INSERT INTO tmp_nir(codnir, codtransf, datanir, gest, tipnir, anulat, blocat, operat)
          VALUES(aCodNIR, 0, aDataDoc, v_rec.Gest, 13, 0, 0, 1);
        END;
      END IF;

      aCodTransf1 := aCodTransf1 - 1;
      INSERT INTO tmp_transf1(codtransf1, codtransf, indexlocal, tiplinie, umsec, codobiect, pu, cant, tva, codcont, pumaximal, codmifix, paritate)
       VALUES(aCodTransf1, 0, aCodTransf1, '=', V_REC.UMSEC, V_REC.CODOBIECT, V_REC.PRET + V_REC.PRETPREDARE, v_rec.rest, 0, V_REC.CONTSERV, V_REC.PUMAXIMAL, V_REC.CODMIFIX, V_REC.PARITATE);

      INSERT INTO tmp_imbmifixlink(codtransf1, codnc1, codmifix, cant)
      VALUES(aCodTransf1, v_rec.codintr1, v_rec.codmifix, V_REC.PRETPREDARE);

      aCodLivr1 := aCodLivr1 - 1;
      INSERT INTO tmp_livr1(codlivr1, codlivr, codies1, codnirstoc, cant, codnirser, pmp, umsec, cantrezervat, codcertif, pmpvaluta, pmpdoc, pmpvalutadoc, contintermed, PARITATE)
      VALUES(aCodLivr1, -1, aCodTransf1, v_rec.codnirstoc, 1, v_rec.codnirser, 0, v_rec.umsec, 0, 0, 0, 0, 0, 0, V_REC.PARITATE);

      INSERT INTO tmp_nirstoc(codnir, codtransf1, codnirstocparinte, cantnir, umsec, codobiect, codioart, pret, adaos, tva, tipserie,
                              codlivr1, rest, procentadaos, supliment, cantfurn, rotlei, rotvaluta, codlocatie, tg, pumaximal,
                              furn, dataachiz, tipdocachiz, codgestprod, subunitatea, d1, d2, d3, puval, provizion, PARITATE)
      VALUES(aCodNIR, aCodTransf1, v_rec.codnirstoc, v_rec.rest, v_rec.umsec, v_rec.codobiect, v_rec.codioart, V_REC.PRET + V_REC.PRETPREDARE,
             V_REC.PRET + V_REC.PRETPREDARE, 0, v_rec.tipserie, aCodLivr1, v_rec.rest, 0, 0, v_rec.rest, v_rec.rotlei, v_rec.rotvaluta,
             v_rec.codlocatie, v_rec.tg, v_rec.pumaximal, v_rec.furn, v_rec.dataachiz, v_rec.tipdocachiz, v_rec.codgestprod, aSubunitatea,
             v_rec.d1, v_rec.d2, v_rec.d3, v_rec.puval, v_rec.provizion, V_REC.PARITATE);

      INSERT INTO tmp_JURNAL1(CODJURNAL1, CODDOC, TIPDOC, INDEXLOCAL, AN, LUNA, DIRTY, SUBUNITATEA)
      VALUES(-1, 0, 13, 1, aan, aluna, 1, aSubunitatea);

      INSERT INTO tmp_JURNAL(CODJURNAL, CODDOC, TIPDOC, INDEXLOCAL, AN, LUNA, SUBUNITATEA)
      VALUES(-1, 0, 13, aCodTransf1, aAN, aLUNA, aSUBUNITATEa);

      BEGIN
        PERFORM pkg_miscari_interne_SetSkipMifix(True);
        PERFORM pkg_miscari_interne_SP_POSTRECORDS(-1, aCodTransf);

        UPDATE intrari1
        SET
        RestIMBMF = CASE WHEN TIPLINIE IN ('S', '=') AND  COALESCE(CODMIFIX, 0) &lt;&gt; 0
                         THEN Cant * PU - (SELECT COALESCE(SUM(IL.CANT), 0)
                                           FROM IMBMIFIXLINK IL
                                                LEFT JOIN TRANSF1 T1 ON  T1.CODTRANSF1 = IL.CODTRANSF1
                                                LEFT JOIN TRANSF  T  ON  T.CODTRANSF   = T1.CODTRANSF
                                           WHERE IL.CODINTR1 = v_m.CodINTR1 AND  T.OPERAT = 1 AND  T.ANULAT = 0
                                          )
                         ELSE 0
                    END
        WHERE codintr1 = v_m.codintr1;

        PERFORM pkg_miscari_interne_SetSkipMifix(False);
      EXCEPTION WHEN others THEN
        PERFORM pkg_miscari_interne_SetSkipMifix(False);
      END;

      UPDATE jurnal1 SET dirty = 1 WHERE coddoc = aCodTransf and  TipDoc = 13;
      UPDATE jurnal1 SET dirty = 1 WHERE coddoc = v_rec.codmifix and  tipdoc = 36 and  an * 12 + luna &gt;= aAn * 12 + aLuna;

      FOR v_xxx IN (SELECT * FROM TMP_NIRSTOC_RECOD) LOOP
        UPDATE mifix1
        SET
        codnirstoc = v_xxx.codnou,
        pret       = pret + V_REC.PRETPREDARE
        WHERE
         codnirstoc = v_rec.codnirstoc and  anstart * 12 + lunastart &gt;= aAn * 12 + aLuna and  codmifix = v_rec.codmifix;

        INSERT INTO mastermifix(codnirstoc, codclasif, duratan, duratanf, duratang, codanaliza)
        SELECT v_xxx.codnou, m.codclasif, m.duratan, m.duratanf, m.duratang, m.codanaliza
        FROM mastermifix m
        WHERE m.codnirstoc = v_rec.codnirstoc;
      END LOOP;

      UPDATE intrari1 SET restimbmf = 0 WHERE codintr1 = v_m.codintr1;

      FOR V_xxx IN (SELECT M.CODMIFIX, M1.PRET AS VALOARE
                    FROM MIFIX M, MIFIX1 M1
                    WHERE
                      EXISTS (SELECT CODMIFIX FROM TMP_IMBMIFIXLINK WHERE CODMIFIX = M.CODMIFIX)
                      AND  M1.CODMIFIX = M.CODMIFIX
                      AND  M1.ANSTART * 12 + M1.LUNASTART &lt;= (SELECT PKG_GLOBALS_AnLunaLucru.WME_RESULT FROM PKG_GLOBALS_AnLunaLucru(NULL,NULL))
                      AND M1.ANSTART * 12 + M1.LUNASTART = (SELECT MAX(ANSTART * 12 + LUNASTART) FROM MIFIX1 M2 WHERE M2.CODMIFIX = M.CODMIFIX AND M2.ANSTART * 12 + M2.LUNASTART &lt;=  getAnLunaLucru() )
                   )
      LOOP
        UPDATE MIFIX N1
        SET
        RESTIMBMF = V_xxx.VALOARE - (SELECT COALESCE(SUM(IL.CANT), 0)
                                     FROM IMBMIFIXLINK IL
                                          LEFT JOIN TRANSF1 T1 ON  T1.CODTRANSF1 = IL.CODTRANSF1
                                          LEFT JOIN TRANSF  T  ON  T.CODTRANSF   = T1.CODTRANSF
                                     WHERE IL.CODMIFIX = N1.CODMIFIX AND  T.T.OPERAT = 1 AND  T.ANULAT = 0
                                    )
        WHERE CODMIFIX = V_xxx.CODMIFIX;
      END LOOP;

      FOR v_xxx IN (SELECT t.codtransf, t.prefixdoc, t.datadoc, t.nrdoc, t.tipdoc, ns.pret PRET_VECHI, ns_nou.pret PRET_NOU, nir.gest GEST_VECHI, nir_nou.gest GEST_NOU, t1.cant, t1.codtransf1, t.obs
                    FROM transf t
                        INNER JOIN transf1      t1      ON  t.codtransf       = t1.codtransf
                        INNER JOIN imbmifixlink l       ON  t1.codtransf1     = l.codtransf1
                        INNER JOIN livr1        l1      ON  t1.codtransf1     = l1.codies1
                        INNER JOIN livr         lv      ON  lv.codlivr        = l1.codlivr and  lv.codtransf = t.codtransf
                        INNER JOIN nirstoc      ns      ON  l1.codnirstoc     = ns.codnirstoc
                        INNER JOIN nir                  ON  nir.codnir        = ns.codnir
                        INNER JOIN nirstoc      ns_nou  ON  ns_nou.codtransf1 = t1.codtransf1
                        INNER JOIN nir          nir_nou ON  ns_nou.codnir     = nir_nou.codnir
                    WHERE t.codtransf = aCodTransf and  l.codnc1 = v_rec.codintr1
                   )
      LOOP
        BEGIN
          SELECT count(*) INTO aCount FROM fisamf WHERE codmifix = v_rec.codmifix;
        EXCEPTION WHEN others THEN
          aCount := 0;
        END;

        IF  aCount &gt; 0 THEN
          INSERT INTO fisamf(codfisamf, codmifix, codoperatie, dataoperatie, gestsursa, gestdest, preti, prete, prefixdoc, nrdoc, cant, coddoc1, tipdoc)
          VALUES(NEXTVAL('SEQ_FISAMF_CODFISAMF'), v_rec.codmifix, 3, v_xxx.datadoc, v_xxx.gest_vechi, v_xxx.gest_nou, v_xxx.pret_vechi, v_xxx.pret_nou,
                 v_xxx.prefixdoc, v_xxx.nrdoc, v_xxx.cant, v_xxx.codtransf1, v_xxx.tipdoc);
        ELSE
          INSERT INTO fisamf(codfisamf, codmifix, codoperatie, dataoperatie, gestsursa, gestdest, preti, prete, prefixdoc, nrdoc, cant, coddoc1, tipdoc)
          VALUES(NEXTVAL('SEQ_FISAMF_CODFISAMF'), v_rec.codmifix, 1, v_xxx.datadoc, v_xxx.gest_vechi, v_xxx.gest_nou, v_xxx.pret_vechi,
                 v_xxx.pret_nou, v_xxx.prefixdoc, v_xxx.nrdoc, v_xxx.cant, v_xxx.codtransf1, v_xxx.tipdoc);
        END IF;
      END LOOP;
    END LOOP;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nc_sp_deleterecord</obj_name>
  <obj_hashval>c5d4a82e5b87803c1ce2dc5e630c87ee</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nc_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  V_REC          RECORD;
  V_REC_JURN_SUB RECORD;
  V_RECAV        RECORD;
  V_RECJURN      RECORD;
  ACARNETDOC     numeric;
  ANRDOC         numeric;
  aCodSubunit    numeric;
  aDataDoc       date;
  aDoc           varchar;
BEGIN
  --Florin 01.06.2023 - monitor
  --Florin 20.04.2023 - sinc. Oracle
  --Florin 02.03.2023 - sinc. Oracle
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_nc_setct_monitor('MON_62');
  perform PKG_GLOBALS_MarkDirtyJurnal();
  perform PKG_NC_SP_LOCKRECORD(RecId);
  PERFORM PKG_CFGTABLES_EXT_DELETERECORD(recId, 35);

  SELECT SUBUNITATEA, datadoc, 'NC' || coalesce(nrdoc::varchar, '') || '/' || coalesce(to_char(datadoc, 'dd.mm.yyyy'), '')
  INTO aCodSubunit, aDataDoc, aDoc
  FROM nc WHERE CODNC = RECID;

  if (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT
      FROM   PKG_USERFIRME_ValidPostLog(null, to_number(current_setting('PKG_GLOBALS.USERID', true), '999999999999999999'),
                                        current_setting('PKG_NC.CT_MONITOR', true)))
  then
    perform pkg_userfirme_postlogcucommit('NC',
                                         current_setting('PKG_GLOBALS.USERNAME', true), 'S', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true),
                                         aCodSubunit, aDataDoc, aDoc, null,
                                         (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(null, null)));
  end if;

  DELETE FROM OBLIGPIF
  WHERE SEMNIFICATIE in (1200, 1201)
    and CODGENERAL in (SELECT CODGENERAL FROM GENERAL WHERE CODDOC in (SELECT CODNC1 FROM NC1 WHERE CODNC = RecID ) );

  DELETE FROM GENERAL WHERE TIPDOC = 35 and CODDOC in (SELECT CODNC1 FROM NC1 WHERE CODNC = RecID );

  for V_REC in (SELECT * FROM JURNAL WHERE CODDOC = RecID and TIPDOC = 35 ) loop
    UPDATE NCONTRUL
    SET
      RULAJCD      = RULAJCD  - V_REC.VALOARE,
      RULAJVCD     = RULAJVCD - V_REC.VALOAREV,
      RULAJC_IFRS  = coalesce( RULAJC_IFRS , 0) - coalesce( V_REC.VALOARE_IFRS , 0),
      RULAJVC_IFRS = coalesce( RULAJVC_IFRS, 0) - coalesce( V_REC.VALOAREV_IFRS, 0),
      RULAJC_GRUP  = coalesce( RULAJC_GRUP , 0) - coalesce( V_REC.VALOAREGRUP  , 0),
      RULAJVC_GRUP = coalesce( RULAJVC_GRUP, 0) - (SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(null, coalesce( V_REC.VALOAREGRUP, 0), coalesce( V_REC.VALOARE, 0), coalesce( V_REC.VALOAREV, 0)))
    where
      CODCONT = V_REC.CONTD
      and AN   = to_number(current_setting('PKG_GLOBALS.ANLUCRU'  , true), '999999999999999999')
      and LUNA = to_number(current_setting('PKG_GLOBALS.LUNALUCRU', true), '999999999999999999') ;

    for V_REC_JURN_SUB in (SELECT * FROM NCONTRUL WHERE CODCONT = V_REC.CONTD and AN = V_REC.AN and LUNA = V_REC.LUNA ) loop
      UPDATE NCONTRULSUB
      SET
        RULAJCD      = RULAJCD  - V_REC.VALOARE,
        RULAJVCD     = RULAJVCD - V_REC.VALOAREV,
        RULAJC_IFRS  = coalesce( RULAJC_IFRS , 0) - coalesce( V_REC.VALOARE_IFRS , 0),
        RULAJVC_IFRS = coalesce( RULAJVC_IFRS, 0) - coalesce( V_REC.VALOAREV_IFRS, 0),
        RULAJC_GRUP  = coalesce( RULAJC_GRUP , 0) - coalesce( V_REC.VALOAREGRUP  , 0),
        RULAJVC_GRUP = coalesce( RULAJVC_GRUP, 0) - (SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(null, coalesce( V_REC.VALOAREGRUP, 0), coalesce( V_REC.VALOARE, 0), coalesce( V_REC.VALOAREV, 0)))
      WHERE
        CODCONTRUL = V_REC_JURN_SUB.CODCONTRUL
        and SUBUNITATEA = V_REC.SUBUNITATEA ;
    end loop;

    UPDATE NCONTRUL
    SET
      RULAJCC      = RULAJCC  - V_REC.VALOARE,
      RULAJVCC     = RULAJVCC - V_REC.VALOAREV,
      RULAJC_IFRS  = coalesce( RULAJC_IFRS , 0) - coalesce( V_REC.VALOARE_IFRS , 0),
      RULAJVC_IFRS = coalesce( RULAJVC_IFRS, 0) - coalesce( V_REC.VALOAREV_IFRS, 0),
      RULAJC_GRUP  = coalesce( RULAJC_GRUP , 0) - coalesce( V_REC.VALOAREGRUP  , 0),
      RULAJVC_GRUP = coalesce( RULAJVC_GRUP, 0) - (SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(null, coalesce( V_REC.VALOAREGRUP, 0), coalesce( V_REC.VALOARE, 0), coalesce( V_REC.VALOAREV, 0)))
    WHERE
      CODCONT = V_REC.CONTC
      and AN   = to_number(current_setting('PKG_GLOBALS.ANLUCRU'  , true), '999999999999999999')
      and LUNA = to_number(current_setting('PKG_GLOBALS.LUNALUCRU', true), '999999999999999999') ;

    for V_REC_JURN_SUB in (SELECT * FROM NCONTRUL WHERE CODCONT = V_REC.CONTC and AN = V_REC.AN and LUNA = V_REC.LUNA ) loop
      UPDATE NCONTRULSUB
      SET
        RULAJCC      = RULAJCC  - V_REC.VALOARE,
        RULAJVCC     = RULAJVCC - V_REC.VALOAREV,
        RULAJC_IFRS  = coalesce( RULAJC_IFRS , 0) - coalesce( V_REC.VALOARE_IFRS , 0),
        RULAJVC_IFRS = coalesce( RULAJVC_IFRS, 0) - coalesce( V_REC.VALOAREV_IFRS, 0),
        RULAJC_GRUP  = coalesce( RULAJC_GRUP , 0) - coalesce( V_REC.VALOAREGRUP  , 0),
        RULAJVC_GRUP = coalesce( RULAJVC_GRUP, 0) - (SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(null, coalesce( V_REC.VALOAREGRUP, 0), coalesce( V_REC.VALOARE, 0), coalesce( V_REC.VALOAREV, 0)))
      WHERE
        CODCONTRUL = V_REC_JURN_SUB.CODCONTRUL
        and SUBUNITATEA = V_REC.SUBUNITATEA ;
    end loop;
  end loop;

  DELETE FROM JURNAL  WHERE CODDOC = RecID and TIPDOC = 35;
  DELETE FROM JURNAL1 WHERE CODDOC = RecID and TIPDOC = 35;

  for V_REC in (SELECT * FROM NC1 N1 WHERE CODNC = RECID ) loop
    for V_RECAV in (SELECT * FROM CHELTAVANS WHERE CODNC1 = V_REC.CODNC1 ) loop
      for V_RECJURN in (SELECT * FROM JURNAL WHERE CODDOC = V_RECAV.CODCHELTAVANS and TIPDOC in (52, 106) ) loop
        UPDATE NCONTRUL
        SET
          RULAJCD  = RULAJCD  - V_RECJURN.VALOARE,
          RULAJVCD = RULAJVCD - V_RECJURN.VALOAREV
        where
          CODCONT = V_RECJURN.CONTD
          and AN = V_RECJURN.AN
          and LUNA = V_RECJURN.LUNA ;

        for V_REC_JURN_SUB in (SELECT * FROM NCONTRUL WHERE CODCONT = V_RECJURN.CONTD and AN = V_RECJURN.AN and LUNA = V_RECJURN.LUNA ) loop
          UPDATE NCONTRULSUB
          SET
            RULAJCD  = RULAJCD  - V_RECJURN.VALOARE,
            RULAJVCD = RULAJVCD - V_RECJURN.VALOAREV
          WHERE
            CODCONTRUL = V_REC_JURN_SUB.CODCONTRUL
            and SUBUNITATEA = V_RECJURN.SUBUNITATEA ;
        end loop;

        UPDATE NCONTRUL
        SET
          RULAJCC  = RULAJCC  - V_RECJURN.VALOARE,
          RULAJVCC = RULAJVCC - V_RECJURN.VALOAREV
        where
          CODCONT = V_RECJURN.CONTC
          and AN = V_RECJURN.AN
          and LUNA = V_RECJURN.LUNA ;

        for V_REC_JURN_SUB in (SELECT * FROM NCONTRUL WHERE CODCONT = V_RECJURN.CONTC and AN = V_RECJURN.AN and LUNA = V_RECJURN.LUNA ) loop
          UPDATE NCONTRULSUB
          SET
            RULAJCC  = RULAJCC  - V_RECJURN.VALOARE,
            RULAJVCC = RULAJVCC - V_RECJURN.VALOAREV
          WHERE
            CODCONTRUL = V_REC_JURN_SUB.CODCONTRUL
            and SUBUNITATEA = V_RECJURN.SUBUNITATEA ;
        end loop;
      end loop;

      DELETE FROM JURNAL1 WHERE CODDOC = V_RECAV.CODCHELTAVANS and TIPDOC in (52, 106);
      DELETE FROM JURNAL  WHERE CODDOC = V_RECAV.CODCHELTAVANS and TIPDOC in (52, 106);

      DELETE FROM CHELTAVANS1 WHERE CODCHELTAVANS = V_RECAV.CODCHELTAVANS;
      DELETE FROM CHELTAVANS  WHERE CODCHELTAVANS = V_RECAV.CODCHELTAVANS;

--      if (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'NC1EXT')) = 1 then
--        execute 'DELETE FROM NC1EXT WHERE CODNC1 = ' || coalesce(V_REC.CODNC1::varchar, '');
--      end if;
    end loop;

    DELETE FROM MASTERCHELTAVANS WHERE CODNC1 = V_REC.CODNC1;
    DELETE FROM NC1              WHERE CODNC1 = V_REC.CODNC1;
  end loop;

  begin
    SELECT NRDOC, CARNETDOC INTO aNRDOC, aCARNETDOC FROM NC WHERE CODNC = RECID;
  EXCEPTION when others then
    begin
      aNRDOC := 0;
      aCARNETDOC := 0;
    end;
  end;

  DELETE FROM EXPERT1 WHERE CODEXPERT = (SELECT CODEXPERT FROM EXPERT WHERE CODDOC = RecID and TIPDOC = 35 );
  DELETE FROM EXPERT  WHERE CODDOC = RecID and TIPDOC = 35;
  DELETE FROM TAXDECL WHERE CODDOC = RECID AND TIPDOC = 35;

--  if (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'NCEXT')) = 1 then
--    execute 'DELETE FROM NCEXT WHERE CODNC = ' || coalesce(RECID::varchar, '');
--  end if;

  DELETE FROM NC WHERE CodNC = RecId;

  if aCARNETDOC &lt;&gt; 0 then
    perform PKG_CARNETEDOC_RELEASENUMARDOC( ACARNETDOC, ANRDOC);
    perform PKG_CARNETEDOC_COMPACTEAZAINTERVALE(ACARNETDOC);
  end if;

  perform NotifyModif( 2, RECID, 'NC');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nc_sp_gotorecord</obj_name>
  <obj_hashval>42f21446bf690f7fb9a1b5fa96b361e5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nc_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC    RECORD;
  aCODPART numeric := 0;
BEGIN
  --Florin 22.10.2025 - sinc. Oracle
  --Florin 27.11.2023 - fixat 60185
  --Florin 22.11.2023 - sinc. Oracle
  --Florin 20.04.2023 - sinc. Oracle
  --Laura 06.12.2021 - sinc Oracle (06.12.2021)
  --Laura 03.12.2021 - sinc Oracle (03.12.2021)
  --Bogdan 09.10.2020
  --Florin 16.11.2021 - fixat 52001
  perform pkg_nc_setct_monitor('MON_62');
  PERFORM PKG_CFGTABLES_CHECK_STRUCT_EXTENSIE_X_TIPDOC(35);
  PERFORM PKG_STOC_GENERARE_FACTURI_MAKE_CONFIG_LUNA();

  INSERT INTO TMP_NC (Part,
      JurnalTVA,
      TIPTRANZ,
      TIPTVA,
      Valoare,
      Moneda,
      Curs,
      Obs,
      CodNC,
      NrDoc,
      DataDoc,
      AN,
      LUNA,
      SUBUNITATEA,
      sablon,
      CARNETDOC,
      Valoarelei,
      CodAnaliza,
      Aprobat)
  (SELECT Part,
        JurnalTVA,
        TIPTRANZ,
        TIPTVA,
        Valoare,
        Moneda,
        Curs,
        Obs,
        CodNC,
        NrDoc,
        DataDoc,
        AN,
        LUNA,
        SUBUNITATEA,
        sablon,
        CARNETDOC,
        CASE WHEN Moneda = 0 THEN COALESCE (Valoare, 0) ELSE COALESCE (curs, 1) * COALESCE (Valoare, 0) END ,
        CodAnaliza,
        Aprobat
      FROM NC WHERE CodNC = RecId);

  IF RECID &gt; 0 THEN
    BEGIN
      SELECT COALESCE (PART, 0) INTO aCODPART FROM TMP_NC;
    EXCEPTION
    WHEN OTHERS THEN
      aCODPART := 0;
    END;
  END IF;

  INSERT INTO TMP_NC1 (IndexLocal,
      PartD,
      PersD,
      PartC,
      PersC,
      CODPART,
      CODMIFIX,
      CODCMDINT1,
      CodNC1,
      CodNC,
      ContD,
      ContC,
      ICONTD,
      ICONTC,
      TIPLINIETVA,
      Valoare,
      Obs,
      CodGest,
      CODFORMATIE,
      SimbolContD,
      SimbolContC,
      CODCENTRU,
      CODAUTO,
      AGENT,
      Codanalizanod,
      Den_gest,
      SimbolCC,
      DenNod,
      DenAgent,
      Den_Part,
      NrInreg,
      Den_formatie
      )
  SELECT       NC1.IndexLocal,
    NC1.PartD,
    NC1.PersD,
    NC1.PartC,
    NC1.PersC,
    NC1.CODPART,
    NC1.CODMIFIX,
    NC1.CODCMDINT1,
    NC1.CodNC1,
    NC1.CodNC,
    NC1.ContD,
    NC1.ContC,
    NC1.ICONTD,
    NC1.ICONTC,
    NC1.TIPLINIETVA,
    NC1.Valoare,
    NC1.Obs,
    NC1.CodGest,
    NC1.CODFORMATIE,
    CASE
      WHEN NC1.PartD = 1 THEN (SELECT PKG_PLANCONTURI_GETSIMBOLCONT.WME_RESULT
                           FROM   PKG_PLANCONTURI_GETSIMBOLCONT (NULL, (SELECT PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG.WME_RESULT
                                                                        FROM   PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG (NULL,1200, NC1.ICONTD, (SELECT PKG_NOMPART_GET_PART_COD_CARACT_LUNA.WME_RESULT
                                                                                                                                        FROM   PKG_NOMPART_GET_PART_COD_CARACT_LUNA (NULL, (CASE WHEN COALESCE (NC1.CODPART, 0) &lt;&gt; 0 THEN NC1.CODPART ELSE aCODPART END), current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric, current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric))))))
      ELSE
        CASE
          WHEN PersD = 1 THEN (SELECT PKG_PLANCONTURI_GETSIMBOLCONT.WME_RESULT
                               FROM   PKG_PLANCONTURI_GETSIMBOLCONT (NULL, (SELECT PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG.WME_RESULT
                                                                            FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG (NULL,1100, NC1.ICONTD, (SELECT PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA.WME_RESULT
                                                                                                                                          FROM   PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA (NULL,NC1.AGENT, current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric, current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric))))))
          ELSE (SELECT PKG_PLANCONTURI_GETSIMBOLCONT.WME_RESULT FROM PKG_PLANCONTURI_GETSIMBOLCONT (NULL,NC1.CONTD))
        END
    END ,
    CASE
      WHEN NC1.PartC = 1 THEN (SELECT PKG_PLANCONTURI_GETSIMBOLCONT.WME_RESULT
                           FROM   PKG_PLANCONTURI_GETSIMBOLCONT (NULL, (SELECT PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG.WME_RESULT
                                                                        FROM   PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG (NULL,1201, NC1.ICONTC, (SELECT PKG_NOMPART_GET_PART_COD_CARACT_LUNA.WME_RESULT
                                                                                                                                        FROM   PKG_NOMPART_GET_PART_COD_CARACT_LUNA (NULL, (CASE WHEN COALESCE (NC1.CODPART, 0) &lt;&gt; 0 THEN NC1.CODPART ELSE aCODPART END), current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric, current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric))))))
      ELSE
        CASE
          WHEN NC1.PersC = 1 THEN (SELECT PKG_PLANCONTURI_GETSIMBOLCONT.WME_RESULT
                               FROM   PKG_PLANCONTURI_GETSIMBOLCONT (NULL, (SELECT PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG.WME_RESULT
                                                                            FROM   PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG (NULL,1101, NC1.ICONTC, (SELECT PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA.WME_RESULT
                                                                                                                                            FROM   PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA (NULL,NC1.AGENT, current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric, current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric))))))
          ELSE (SELECT PKG_PLANCONTURI_GETSIMBOLCONT.WME_RESULT FROM PKG_PLANCONTURI_GETSIMBOLCONT (NULL,NC1.CONTC))
        END
    END ,
    NC1.CODCENTRU,
    NC1.CODAUTO,
    NC1.AGENT,
    NC1.CODANALIZANOD,
    G.DEN_GEST,
    CC.SIMBOL,
    V.DENUMIRE,
    AG.NUME||' '||AG.PRENUME,
    P.DEN_PART,
    AUT.NRINREG,
    F.DEN_FORMATIE
    FROM NC1 NC1
     LEFT JOIN NGEST G ON G.CODGEST = NC1.CODGEST
     LEFT JOIN CENTRECOST CC ON CC.CODCENTRU = NC1.CODCENTRU
     LEFT JOIN V_NoduriAnaliza V ON V.CODANALIZANOD = NC1.CODANALIZANOD
     LEFT JOIN NPERS AG ON AG.CODPERS = NC1.AGENT
     LEFT JOIN NPART P ON P.CODPART = NC1.CODPART
     LEFT JOIN NPARCAUT AUT ON AUT.CODNPARCAUT = NC1.CODAUTO
     LEFT JOIN FORMATII F ON F.CODFORMATIE = NC1.CODFORMATIE
  WHERE NC1.CodNC = RecId ORDER BY INDEXLOCAL;

  UPDATE tmp_nc1
  SET
  IdentifLinie = coalesce (SimbolContD,'') || ' = ' || coalesce (SimbolContC,'') || ' - Valoare : ' || coalesce (Valoare::varchar,'');

  INSERT INTO TMP_CMDAPROBARI
  SELECT * FROM CMDAPROBARI WHERE CODDOC = RECID AND TIPDOC = 35;

  INSERT INTO TMP_GENERAL (CODGENERAL,
      TIPDOC,
      CODDOC,
      MONEDA,
      CURS,
      TVA,
      SEMNIFICATIE,
      FARAREG)
  (SELECT CODGENERAL,
        TIPDOC,
        CODDOC,
        MONEDA,
        CURS,
        TVA,
        SEMNIFICATIE,
        FARAREG
   FROM GENERAL WHERE TIPDOC = 35 AND CODDOC IN (SELECT CODNC1 FROM TMP_NC1));
--
  INSERT INTO TMP_OBLIGPIF (CODOBLIGPIF,
      CODGENERAL,
      TERMEN,
      VALOARE,
      REST,
      CODPART,
      ICONT,
      TIPPLATA,
      MAJORARI,
      SEMNIFICATIE,
      TIP,
      CONTBANKTRANZACTIE,
      CODOBLIGASOCIAT,
      CODCENTRU,
      CODANALIZANOD)
  (SELECT CODOBLIGPIF,
        CODGENERAL,
        TERMEN,
        VALOARE,
        REST,
        CODPART,
        ICONT,
        TIPPLATA,
        MAJORARI,
        SEMNIFICATIE,
        TIP,
        CONTBANKTRANZACTIE,
        CODOBLIGASOCIAT,
        CODCENTRU,
        CODANALIZANOD
   FROM OBLIGPIF WHERE CODGENERAL IN (SELECT CODGENERAL FROM TMP_GENERAL));

  UPDATE TMP_OBLIGPIF OB SET CODTREZOR1 = (SELECT CODDOC FROM TMP_GENERAL G WHERE G.CODGENERAL = OB.CODGENERAL);

  INSERT INTO TMP_JURNAL  (SELECT * FROM JURNAL  WHERE TIPDOC = 35 AND CODDOC = RECID);
  INSERT INTO TMP_JURNAL1 (SELECT * FROM JURNAL1 WHERE TIPDOC = 35 AND CODDOC = RECID);

  DELETE FROM TMP_RULAJ;

  UPDATE TMP_NC1 N1 SET FARAREG = (SELECT FARAREG FROM TMP_GENERAL WHERE CODDOC = N1.CODNC1 limit 1);

  FOR V_REC IN (SELECT * FROM TMP_OBLIGPIF) LOOP
    UPDATE TMP_NC1 SET TERMEN = V_REC.TERMEN WHERE CODNC1 = V_REC.CODTREZOR1;
  END LOOP;

  DELETE FROM TMP_OBLIGPIF_INITIAL;

  INSERT INTO TMP_OBLIGPIF_INITIAL SELECT * FROM TMP_OBLIGPIF;

  UPDATE TMP_NC1 I1
  SET
  INFOMF =
    CASE
      WHEN COALESCE (I1.CODMIFIX, 0) &lt;&gt; 0 THEN (SELECT coalesce (MF.NRINVENTAR::varchar,'') || '/' || coalesce (O.DENUMIRE,'')
                                                FROM MIFIX  MF,
                                                  MIFIX1  MF1,
                                                  NIRSTOC NS,
                                                  NARTOBJ O
                                                WHERE
                                                  MF.CODMIFIX = I1.CODMIFIX
                                                  AND MF.CODMIFIX = MF1.CODMIFIX
                                                  AND MF1.ANSTART * 12 + MF1.LUNASTART = current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric * 12 + current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric
                                                  AND NS.CODNIRSTOC = MF1.CODNIRSTOC
                                                  AND O.CODOBIECT = NS.CODOBIECT)
      ELSE NULL
    END
  WHERE
    COALESCE (CODMIFIX, 0) &lt;&gt; 0;

  UPDATE TMP_NC1 N1 SET CMDINT = (SELECT NRDOC FROM COMANDA C, COMANDA1 C1 WHERE C1.CODCOMANDA1 = N1.CODCMDINT1 AND C.CODCOMANDA = C1.CODCOMANDA);

  DELETE FROM NC1_MAN;
  INSERT INTO NC1_MAN (CODNC1) SELECT CODNC1 FROM TMP_NC1;

  PERFORM PKG_CFGTABLES_EXT_GOTORECORD(35);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_necesar_updatelinieobj</obj_name>
  <obj_hashval>ecdf6616c446454d840504b164af0246</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_necesar_updatelinieobj(acodnecesar numeric, acodobiect numeric, aacceptat numeric, aacceptatum1 numeric, aplanifper numeric, aplanifprec numeric, astoc numeric, astocmin numeric, astocoptim numeric, astocmax numeric, arezervat numeric, acc numeric, acf numeric, aciies numeric, accpanala numeric, aciiespanala numeric, apmp numeric, avalpmp numeric, acfper numeric, anecesar numeric, acfnext numeric, aplanif numeric, aconsum numeric, aconsumprec numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCount numeric;
begin
  SELECT count( *) INTO acount FROM necesarobj WHERE codobiect = acodobiect and  codnecesar = acodnecesar;

  IF  acount &gt; 0 THEN
    UPDATE necesarobj
    SET
    Acceptat    = aAcceptat,
    Acceptatum1 = aAcceptatum1,
    PLANIFPER   = aPLANIFPER,
    PLANIFPREC  = aPLANIFPREC,
    Stoc        = aStoc,
    Stocmin     = aStocmin,
    Stocoptim   = aStocoptim,
    Stocmax     = aStocmax,
    REZERVAT    = aREZERVAT,
    CC          = aCC,
    CF          = aCF,
    CFPER       = aCFPER,
    CIIES       = aCIIES,
    CCPANALA    = aCCPANALA,
    CIIESPANALA = aCIIESPANALA,
    PMP         = aPMP,
    ValPMP      = aValPMP,
    Necesar     = aNecesar,
    CFNEXT      = aCFNext,
    PLANIF      = aPlanif,
    CONSUM      = aConsum,
    CONSUMPREC  = aConsumPrec
    WHERE
     codnecesar = aCodNecesar and  codobiect = aCodObiect;
  ELSE
    INSERT INTO necesarobj(codnecesar, codobiect, acceptat, acceptatum1, planifper, planifprec, stoc, stocmin, stocoptim, stocmax, rezervat, cc, cf, ciies, ccpanala, ciiespanala, PMP, ValPMP, cfper, necesar, CFNext, planif, consum, consumprec)
    VALUES(aCodNecesar, aCodobiect, aacceptat, aacceptatum1, aplanifper, aplanifprec, astoc, astocmin, astocoptim, astocmax, arezervat, acc, acf, aciies, accpanala, aciiespanala, aPMP, aValPMP, acfper, anecesar, aCFNext, aPlanif, aConsum, aConsumPrec);
  END IF;

  UPDATE necesar n
  SET
  valPMP = (SELECT sum( COALESCE( nobj.valpmp, 0)) FROM necesarobj nobj WHERE nobj.codnecesar = aCodNecesar)
  WHERE
   n.codnecesar = aCodnecesar;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nimob_sp_deleterecord</obj_name>
  <obj_hashval>23b2ccab13a37c219ab9f83a39e3fa3b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nimob_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_NIMOB_SP_LOCKRECORD( RecId);
  DELETE FROM NIMOB WHERE CODNIMOB = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_get_codobiect_analizat</obj_name>
  <obj_hashval>c4adb352762c2f66102cdab150e96b5e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_get_codobiect_analizat(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER((current_setting('PKG_NOM_ARTICOL.gCodObiect', true)),'999999999999999999');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_sp_lockrecord</obj_name>
  <obj_hashval>594114f7b061a1962b080e24b5ab974b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodArticol INTO Tmp FROM NART WHERE CodArticol = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_articol_updatenartobj1double</obj_name>
  <obj_hashval>c5a788b2b704d896ec9d472826be443e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_articol_updatenartobj1double(camp character varying, pvaloare numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 12.03.2021 - sinc.Oracle
  PERFORM pkg_nom_articol_updatenartobj1string(camp, replace(pvaloare::varchar, ',', '.'));
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nom_parcaut_sp_gotorecord</obj_name>
  <obj_hashval>530cbc2fb4d4f6c4eda2aa45b842d5d6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nom_parcaut_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aNr   numeric;
  aGest numeric;
BEGIN
  --Florin 31.10.2023 - sinc. Oracle
  --Florin 21.11.2022 - fixat 56318
  --Bogdan 04.01.2021
  --Florin 16.11.2021 - fixat 52001
  perform pkg_nom_parcaut_setct_monitor('MON_72');
  INSERT INTO TMP_NPARCAUT (CodNParcAut, CodArt, NrInv, NrInreg,
      Sofer, KmPornire, Tip, DataInreg,
      Marca, Model, AnF, SerieC,
      Culoare, Lung, Lat, Inalt,
      TipMotor, SerieM, Motor, Cilindree,
      Putere, CmM, CmU, CmE,
      TipIncarc, Greutate, MasaM, MasaU,
      MasaURDF, MasaURFDF, LocT, LocF,
      LocS, LocP, AnvRecomF, AnvRecomS,
      AnvOpt1F, AnvOpt1S, AnvOpt2F, AnvOpt2S,
      Kg, Kgr, Sarcina, CodPutere,
      GrupAuto, TipRem, InstSp, Aer,
      Rezervor, VolumU, CuloareC, Den_Obiect,
      SursaE, TipUlei, TipVehicul, CodDealer,
      LimitaKM, Dotari, CodRadio, Transmisie,
      Tractiune, GPS, CodPartGPS, Frigo,
      GPL, NumeDealer, Extern, Partener,
      codgest, nrcontr, PartLeas, moneda,
      rataleas, ratarca, ratacasco, dataachiz,
      dataendleas, partutiliz, persutiliz, obs,
      Inactiv, Gr_obiect, CodExtern, CodArtComb,
      ConsStatH)
  SELECT P.CodNParcAut, P.CodArt, P.NrInv, P.NrInreg,
    P.Sofer, P.KmPornire, P.Tip, P.DataInreg,
    P.Marca, P.Model, P.AnF, P.SerieC,
    P.Culoare, P.Lung, P.Lat, P.Inalt,
    P.TipMotor, P.SerieM, P.Motor, P.Cilindree,
    P.Putere, P.CmM, P.CmU, P.CmE,
    COALESCE (P.TipIncarc, 1) , P.Greutate, P.MasaM, P.MasaU,
    P.MasaURDF, P.MasaURFDF, P.LocT, P.LocF,
    P.LocS, P.LocP, P.AnvRecomF, P.AnvRecomS,
    P.AnvOpt1F, P.AnvOpt1S, P.AnvOpt2F, P.AnvOpt2S,
    P.Kg, P.Kgr, P.Sarcina, P.CodPutere,
    P.GrupAuto, P.TipRem, P.InstSp, P.Aer,
    P.Rezervor, P.VolumU, P.CuloareC, OBJ.Denumire,
    P.SursaE, P.TipUlei, P.TipVehicul, P.CodDealer,
    P.LimitaKM, P.Dotari, P.CodRadio, P.Transmisie,
    P.Tractiune, P.GPS, CodPartGPS, Frigo,
    P.GPL, Np.Den_Part NUMEDEALER, COALESCE (P.Extern, 0) , P.Partener,
    P.codgest, P.nrcontr, PartLeas, P.moneda,
    P.rataleas, P.ratarca, P.ratacasco, P.dataachiz,
    P.dataendleas, P.partutiliz, P.persutiliz, P.obs,
    COALESCE (P.Inactiv, 0) , Gr.Denumire, P.CodExtern, P.CodArtComb,
    P.ConsStatH
  FROM NPARCAUT       P
    LEFT JOIN NARTOBJ OBJ ON P.CODART      = OBJ.CODOBIECT
    LEFT JOIN NECHIV  E   ON E.CODOBIECT   = OBJ.CODOBIECT
    LEFT JOIN GRECHIV Gr  ON Gr.Codgrechiv = E.CODGRUPA
    LEFT JOIN NPART   NP  ON NP.Codpart    = P.CodDealer
  WHERE
    CodNParcAut = RecId;

  BEGIN
    SELECT COALESCE (NrInv, 0) , COALESCE (codgest, 0) INTO aNR, aGest FROM TMP_NPARCAUT;

    IF aGest = 0 THEN
      SELECT N.GEST INTO aGest
      FROM MIFIX MX, MIFIX1 MX1, NIRSTOC NS, NIR N
      WHERE
        MX.TIP = 'MF'
        AND MX1.CODMIFIX = MX.CODMIFIX
        AND MX1.ANSTART * 12 + MX1.LUNASTART = (SELECT MAX (ANSTART * 12 + LUNASTART) FROM MIFIX1 MX2 WHERE MX2.CODMIFIX = MX.CODMIFIX)
        AND MX1.CODNIRSTOC = NS.CODNIRSTOC
        AND N.CODNIR       = NS.CODNIR
        AND MX.NRINVENTAR  = aNR;

      UPDATE TMP_NPARCAUT SET codgest = aGEST;
    END IF;
  EXCEPTION
  WHEN others THEN
    aGest := 0;
  END;

  INSERT INTO TMP_NParcG (CODNParcG, CODNPARCAUT, CodGestIni, CodGest, CodCmd, Status, Data, CMD)
  (SELECT CODNParcG, CODNPARCAUT, CodGestIni, PG.CodGest, CodCmd, Status, Data,
          coalesce (C.PREFIXDOC,'') || ' ' || coalesce (C.SERIADOC,'') || coalesce (C.NRDOC::varchar ,'')
   FROM NParcG PG LEFT JOIN COMANDA C ON C.CodComanda = PG.CodCmd
   WHERE PG.CodNPARCAUT = RecId);

  INSERT INTO TMP_NPARC0 (CODNPARC0, CODNPARCAUT, DATABord, KMBord, AN, LUNA, OBS, CODPERS, CodFAZ, Comb, CodCmd, SOFER, FAZ, CMD)
  ( SELECT P0.CODNPARC0, P0.CODNPARCAUT, P0.DATABord, P0.KMBord, P0.AN, P0.LUNA, P0.OBS, P0.CODPERS, P0.CodFAZ, Comb, P0.CodCmd,
           coalesce (S.NUME,'')        || ' ' || coalesce (S.PRENUME,'') ,
           coalesce (FAZ.PREFIXDOC,'') || ' ' || coalesce (FAZ.NRDOC::varchar ,'') || '/' || coalesce (TO_CHAR (FAZ.DATADOC, 'DD.MM.YYYY')  ,'') ,
           coalesce (CMD.PREFIXDOC,'') || ' ' || coalesce (CMD.NRDOC::varchar ,'') || '/' || coalesce (TO_CHAR (CMD.DATADOC, 'DD.MM.YYYY')  ,'')
    FROM NPARC0         P0
        LEFT JOIN NPERS S     ON S.CODPERS      = P0.CODPERS
        LEFT JOIN FAZ         ON FAZ.CodFAZ     = P0.CodFAZ
        LEFT JOIN COMANDA CMD ON CMD.CodComanda = P0.CodCmd
    WHERE
        P0.CodNPARCAUT = RecId);

  INSERT INTO TMP_NPARC1 (CodNParc1, Cod, IndexLocal, Art, Cant, Pozitie, BordInstal, atentie, codpart, Montat, Anotimp, ADANCIME,
                          LATIME, INALTIME, DIAMETRU, GAMA, RUNFLAT, SUV, OFFROAD, XL, Ms, Obs, Seria, DOT, DenObiect, DenUm, BordDem, CodNirStoc,
                          CodNirSer, Serie)
  ( SELECT p1.CodNParc1, p1.Cod, p1.IndexLocal, p1.Art, p1.Cant, p1.Pozitie, p1.BordInstal, p1.atentie, codpart, Montat, Anotimp,
           P1.ADANCIME, P1.LATIME, P1.INALTIME, P1.DIAMETRU, P1.GAMA, P1.RUNFLAT, P1.SUV, P1.OFFROAD, P1.XL, COALESCE (P1.Ms, 0) , P1.OBS, P1.Seria,
           P1.DOT, obj.denumire, um.den_um, P1.Borddem, P1.CodNirStoc, P1.CodNirSer, SER.Serie
    FROM NPARC1           p1
        LEFT JOIN NARTOBJ obj  ON p1.Art          = obj.codobiect
        LEFT JOIN NART    nart ON nart.codarticol = obj.codarticol
        LEFT JOIN NIRSER  NSE  ON NSE.CODNIRSER   = P1.CODNIRSER
        LEFT JOIN NSERII  SER  ON SER.CODSERIE    = NSE.CODSERIE
        INNER JOIN num    um   ON um.codum        = nart.um
    WHERE
        p1.Cod = RecId ORDER BY indexlocal);

  INSERT INTO TMP_NPARC2 (CodNParc2, Cod, IndexLocal, Doc, SN, Eliberat, Expira, atentie, Obs, Valoare, CodIntr1, Denumire, Document)
  ( SELECT P2.CodNParc2, P2.Cod, P2.IndexLocal, P2.Doc, P2.SN, P2.Eliberat, P2.Expira, P2.atentie, P2.Obs, P2.Valoare, P2.CodIntr1, P2.Denumire,
           CASE WHEN A.CODAUTORIZATII &gt; 0 THEN A.DENUMIRE ELSE coalesce (I.PREFIXDOC,'') || ' ' || coalesce (I.NRDOC::varchar ,'') END
    FROM NPARC2                    P2
        LEFT JOIN NAUTORIZATIIAUTO A  ON P2.DOC      = A.CODAUTORIZATII
        LEFT JOIN INTRARI1         I1 ON I1.CODINTR1 = P2.CODINTR1
        LEFT JOIN INTRARI          I  ON I1.CODINTR  = I.CODINTR
    WHERE
        Cod = RecId ORDER BY indexlocal);

  INSERT INTO TMP_NPARC3 (CodNParc3, Cod, Interventie, DataU, KmU, DataV, KmV, DataA, KMA, CodCMD, Valoare, Denumire)
  ( SELECT p3.CodNParc3, p3.Cod, p3.Interventie, p3.DataU, p3.KmU, p3.DataV, p3.KmV, p3.DataA, p3.KMA, CodCMD, Valoare, i.denumire
    FROM NPARC3 P3 INNER JOIN ninterventiiauto i ON p3.interventie = i.codinterventiiauto
    WHERE Cod = RecId);

  INSERT INTO TMP_NPARCCOM (codnparccom, codcomanda, codnparcaut, kmbord,
      TipComSa, partcom, DataInchiderii, InmatrRom,
      Inspectie, PieseClient, ProbaDrum, Spalare,
      DZ, NivRezervor, NrDosarDaune, NrAutRep,
      DataAutRep, datacom, obs, obscom,
      ParcPropriu, Inmatriculare, SerieAuto, Marca,
      Model, Culoare, Energie, TipRAC,
      Document, DataFabr)
  SELECT PC.codnparccom, PC.codcomanda, PC.codnparcaut, PC.kmbord,
    PC.TipComSa, P.Den_Part, COALESCE (R.DataStop, PC.DataInchiderii) , PC.InmatrRom,
    PC.Inspectie, PC.PieseClient, PC.ProbaDrum, PC.Spalare,
    PC.DZ, PC.NivRezervor, PC.NrDosarDaune, PC.NrAutRep,
    PC.DataAutRep, COALESCE (R.DataStart, C.DATADOC) , C.Obs, PC.Obs,
    A.Extern, A.DATAINREG, A.Seriec, A.Marca,
    A.Model, A.Culoare, A.Sursae, R.TipRezervare,
    coalesce (C.PREFIXDOC,'') || coalesce (C.SERIADOC,'') || coalesce (C.NRDOC::varchar ,'') , A.Anf
  FROM NPARCCOM          PC
    INNER JOIN COMANDA C ON C.CodComanda  = PC.CODCOMANDA
    LEFT JOIN RAC_REZ  R ON R.CodComanda  = PC.CODCOMANDA
    LEFT JOIN NPART    P ON P.CodPart     = C.Partener
    LEFT JOIN NPARCAUT A ON A.CODNPARCAUT = PC.CODNPARCAUT
    LEFT JOIN NMonede  M ON M.CodMoNeda   = C.Moneda
  WHERE
    PC.CodNParcAut = RecId;

  INSERT INTO TMP_NPARCCOM1 (CODCOMANDA3, CODCOMANDA2, Comanda, DataStart, Data, CANT, PRET, TIP, EXECUTAT, operatie, lucrare, garantie,
                             CODLUCRARE, CODOPERATIE, CODREZERVARE, CodIntr1_1, CodIntr1_2, CodIntr1_3, DocIntr_1, DocIntr_2, DocIntr_3)
  SELECT CODCOMANDA3, c2.CODCOMANDA2, Document, C3.DataStart, C3.Data, CANT, PRET, C3.TIP, EXECUTAT, O.Denumire, Tl.Denumire, garantie,
         CODLUCRARE, CODOPERATIE, c3.CODREZERVARE, C3.CodIntr1_1, C3.CodIntr1_2, C3.CodIntr1_3,
         (SELECT coalesce (i1_1.prefixdoc,'') || ' ' || coalesce (i1_1.SeriaDoc,'') || coalesce (i1_1.NrDoc::varchar ,'') || '/' || coalesce (To_Char (i1_1.datadoc,'dd.mm.yyyy') ,'')
          FROM intrari1  i1 INNER JOIN intrari i1_1 ON i1_1.codintr = i1.codintr
          WHERE i1.codintr1 = CodIntr1_1
         ) DOCINTR_1,
         (SELECT coalesce (i1_2.prefixdoc,'') || ' ' || coalesce (i1_2.SeriaDoc,'') || coalesce (i1_2.NrDoc::varchar ,'') || '/' || coalesce (To_Char (i1_2.datadoc,'dd.mm.yyyy') ,'')
          FROM intrari1 i1 INNER JOIN intrari i1_2 ON i1_2.codintr = i1.codintr
          WHERE i1.codintr1 = CodIntr1_2
         ) DOCINTR_2,
         (SELECT coalesce (i1_3.prefixdoc,'') || ' ' || coalesce (i1_3.SeriaDoc,'') || coalesce (i1_3.NrDoc::varchar ,'') || '/' || coalesce (To_Char (i1_3.datadoc,'dd.mm.yyyy') ,'')
          FROM intrari1 i1 INNER JOIN intrari i1_3 ON i1_3.codintr = i1.codintr
          WHERE i1.codintr1 = CodIntr1_3
         ) DOCINTR_3
  FROM COMANDA2              c2
    LEFT  JOIN TMP_NPARCCOM  x  ON x.CodComanda     = c2.codcomanda
    INNER JOIN COMANDA3      C3 ON C2.CodComanda2   = C3.CodComanda2
    LEFT  JOIN NPart         P  ON P.CodPart        = COALESCE (C2.CodPart, 0)
    INNER JOIN Tiplucrarisa  TL ON TL.CODTIPLUCRARE = C2.CODLUCRARE
    INNER JOIN NOper         O  ON O.CodOp          = C3.CODOPERATIE
  WHERE c2.codNParcAut = RecID
  ORDER BY Datacom;

  PERFORM  PKG_CFGTABLES_EXT_GOTORECORD(505);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomactivit_setct_monitor</obj_name>
  <obj_hashval>0a76396b0e256523da886a0b2045d63c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomactivit_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOMACTIVIT.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomatribute_sp_insertrecord</obj_name>
  <obj_hashval>c5bbef6c6f8eda9ac74cdeda80cf5624</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomatribute_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NATRIB(CodAtribut) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomatribute_sp_lockrecord</obj_name>
  <obj_hashval>f21e0f6448c2edf69556c6114cdb3e83</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomatribute_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodAtribut INTO Tmp FROM NATRIB WHERE CodAtribut = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomcarsupart_baga_dci</obj_name>
  <obj_hashval>a7a94ba0f2a9b6b618c3cf60c0ec7185</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomcarsupart_baga_dci(INOUT adci character varying, OUT acod numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  cod numeric;
BEGIN
  --Florin 16.08.2024 - fixat 63042
  SELECT NextVal('seq_NCARSUPART_codcarsupart') INTO aCod;
  insert into NCARSUPART (CODCARSUPART, den_carsupart)
  values (acod, substr(aDCI, 0, 80));
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomelemaeroauto_sp_insertrecord</obj_name>
  <obj_hashval>434147d1252fcae6bbc3a5bfc687d5df</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomelemaeroauto_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NELEMAEROAUTO(CodElemAeroAuto) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgest_get_subunit_gest</obj_name>
  <obj_hashval>66a311550ac5a297084e72094d65784a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgest_get_subunit_gest(INOUT wme_result numeric, INOUT acodgest numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODSUBUNIT numeric := 0;
begin
  BEGIN
    SELECT CODSUBUNIT INTO ACODSUBUNIT FROM NGEST WHERE CODGEST = aCODGEST;
  EXCEPTION WHEN OTHERS THEN
    aCODSUBUNIT := 0;
  END;

  WME_Result :=  aCODSUBUNIT;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomgest_sp_insertrecord</obj_name>
  <obj_hashval>9d5dc3c719330ae4cfe50bedef985332</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomgest_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 12.04.2023 - sinc. Oracle
  INSERT INTO TMP_NGEST(codgest) VALUES(0);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(506);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nominstauto_sp_postrecords</obj_name>
  <obj_hashval>2049806eb2fe88bcc86acf930bb3d2e4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nominstauto_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    SELECT CodInstAuto INTO RecId FROM TMP_NINSTAUTO;

    UPDATE NINSTAUTO
    SET
    (Instalatie, Prestatie, Spor) = (SELECT Instalatie, Prestatie, Spor FROM TMP_NINSTAUTO)
    WHERE
     CodInstAuto = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_NINSTAUTO_CODINSTAUTO') INTO RecId;

    INSERT INTO NINSTAUTO(CodInstAuto, Instalatie, Prestatie, Spor)
    (SELECT RecId, Instalatie, Prestatie, Spor FROM TMP_NINSTAUTO);
  END IF;

  PERFORM NotifyModif( OPERATION, RECID, 'NINSTAUTO');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomlocatii_sp_insertrecord</obj_name>
  <obj_hashval>3a32441a11b79dcf14107af426e9f01e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomlocatii_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NLOCATII(CodLocatie) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_sp_lockrecord</obj_name>
  <obj_hashval>b36bd95ae012bec1b695ae1fb2cfbf41</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CODPART INTO Tmp FROM NPART WHERE CodPart = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompart_sp_postrecords</obj_name>
  <obj_hashval>b09079d7c0122ab452d0cfa753761fa7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompart_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC      RECORD;
  vRecNo     numeric := 0;
  vAn        numeric := 0;
  vLuna      numeric := 0;
  vCod       numeric;
  aDoc       varchar;
  aOldBlocat numeric;
  aNewBlocat numeric;
  sObs       varchar;
  vTVAI      numeric;
  sCUI       varchar;
BEGIN
  --Florin 09.12.2025 - sinc. Oracle
  --Florin 11.09.2025 - sinc. Oracle
  --Florin 07.02.2025 - sinc. Oracle
  --Florin 09.09.2024 - sinc. Oracle
  --Florin 26.06.2024 - sinc. Oracle
  --Florin 14.05.2024 - sinc. Oracle
  --Florin 12.04.2024 - sinc. Oracle
  --Florin 17.11.2023 - sinc. Oracle
  --Florin 03.11.2023 - sinc. Oracle
  --Florin 19.10.2023 - sinc. Oracle
  --Florin 01.06.2023 - monitor
  --Florin 12.04.2023 - sinc. Oracle (11.03.2023)
  --Florin 02.03.2023 - sinc. Oracle
  --Florin 16.02.2023 - sinc. Oracle
  --Florin 14.02.2023 - sinc. Oracle (13.02.2023)
  --Florin 06.12.2022 - sinc. Oracle (05.12.2022)
  --Bogdan 29.09.2022 - 55428 : Oferte furnizori - data/termen
  --Florin 16.06.2022 - sinc.  Oracle
  --Florin 21.02.2022 - sinc. Oracle (18.02.2022)
  --Laura 13.10.2021 - sinc Oracle (08.10.2021)
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  --Adina 11.03.2021 - add prc_al_refresh
  --Adina 08.01.2021 sinc.Oracle
  perform pkg_nompart_setct_monitor('MON_4');
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT (500);
  if Operation = 0 then
    SELECT CodPart INTO RecId FROM TMP_NPART;

    sObs := '';

    BEGIN
      SELECT coalesce( blocat, 0) INTO aOldBlocat FROM npart WHERE codpart = RecID;
      SELECT coalesce( blocat, 0) INTO aNewBlocat FROM tmp_npart;

      if aOldBlocat = 0 and aNewBlocat = 1 then
        sObs := '(blocare partener)';
      else
        if aOldBlocat = 1 and aNewBlocat = 0 then
          sObs := '(deblocare partener)';
        end if;
      end if;
    EXCEPTION WHEN OTHERS THEN sObs := '';
    END;

    UPDATE NPART SET
    (Den_part, CodExtern, CodMoneda, RegCom, EXPIRAREAUTORIZ, CODSTATISTICBNR, Autorizatie, CodIntern, CodClasa, CodCategPret, TipPart,
     ScadentaC, ScadentaV, Discount, CodCategDisc, Blocat, TIPPARTENER, DATAADAUGARII, OBS, POZA, PERSOANAFIZICA, VERFACT, VERDISPLIVR,
     COLDISCOUNT, INFOBLOCAT, MusaiColet, STRATEGIC, CifraAfaceri, DomeniuActiv, NrAngajati,
     SursaLead, lead, TVALAINCASARE,
     MODAPLICPROCDISC,
     PROCCURSTRANSF, VERPROFORMA, FIDELIZARE, Majorari, TipBlocaj, SPLITTVA, POPRIRE_ANAF, codresponsabil, CodDomeniuAct, DocDefOnorCom,
     ModPromoFactCom, ValidarePretOferta, IESCUCOMANDA, VERFACTAVIZ, ZIAPROVIZ, PERAPROVIZ, CODCONTRACTCadru,
     EF_Item, EF_Party,
     DATANASTERE, GDPR, ZILELIVRARE, SAFT_EXPORT,
     FaraPenalizari, INACTIV, preOfeFurnVar, Tipanalizapret, VerAvizIes, ef_ImpArtGen, EF_CUSTOM, EF_PROIECT, EF_Taxe, CategTarif, ZileAchiz, Culoare
    ) =
    (
      SELECT
        Den_part, CodExtern, CodMoneda, RegCom, EXPIRAREAUTORIZ, CODSTATISTICBNR, Autorizatie, CodIntern, CodClasa, CodCategPret, TipPart,
        ScadentaC, ScadentaV, Discount, CodCategDisc, Blocat, TIPPARTENER, DATAADAUGARII, OBS, POZA, PERSOANAFIZICA, VERFACT, VERDISPLIVR,
        COLDISCOUNT, INFOBLOCAT, MusaiColet, STRATEGIC, CifraAfaceri, DomeniuActiv, NrAngajati,
        SursaLead, lead, TVALAINCASARE,
        0, --MODAPLICPROCDISC,
        PROCCURSTRANSF, VERPROFORMA, FIDELIZARE, Majorari, TipBlocaj, SPLITTVA, POPRIRE_ANAF, codresponsabil, CodDomeniuAct, DocDefOnorCom,
        ModPromoFactCom, ValidarePretOferta, IESCUCOMANDA, VERFACTAVIZ, ZIAPROVIZ, PERAPROVIZ, CODCONTRACTCadru,
        EF_Item, EF_Party,
        DATANASTERE, GDPR, ZILELIVRARE, SAFT_EXPORT,
        FaraPenalizari, INACTIV, preOfeFurnVar, Tipanalizapret, VerAvizIes, ef_ImpArtGen, EF_CUSTOM, EF_PROIECT, EF_Taxe, CategTarif, ZileAchiz, Culoare
      FROM TMP_NPART
    )
    WHERE npart.CodPart = RecId ;

    if (select  PKG_USERFIRME_ValidPostLog.WME_RESULT from  PKG_USERFIRME_ValidPostLog(null,to_number(current_setting('PKG_GLOBALS.USERID', true), '999999999999999999'),current_setting('PKG_NOMPART.CT_MONITOR', true))) then
      SELECT 'Partener "' || coalesce(den_part, '') || '"' INTO aDoc FROM npart WHERE codpart = recid;

      perform pkg_userfirme_postlogcucommit('NPART',current_setting('PKG_GLOBALS.USERNAME', true),'M',RECID,current_setting('PKG_GLOBALS.FIRMANAME', true),
                                    to_number(current_setting('PKG_GLOBALS.SUBUNITATE', true), '999999999999999999'),null,aDoc,sObs,
                                    (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(null,null))
                                   );
    end if;

    DELETE FROM NPART1 WHERE CODPART = RECID AND CODPART1 NOT IN (SELECT CODPART1 FROM TMP_NPART1 );

    INSERT INTO NPART1 (CodPart, CodIOPART, CodPart1, CreditFurn, VolumTranzC, SCADENTAV, SCADENTAC, CASSBAZAMIN, SimbolCASS,
                        GDPR, DISCOUNT, CreditClient, VolumTranzF, anstart, lunastart )
    (SELECT RecId, CodIOPART, nextval('SEQ_NPART1_CODPART1'), CreditFurn, VolumTranzC, SCADENTAV, SCADENTAC, CASSBAZAMIN, SimbolCASS,
            GDPR, DISCOUNT, CreditClient, VolumTranzF, anstart, lunastart FROM TMP_NPART1 WHERE CODPART1 &lt; 0 );

    FOR v_rec IN (SELECT * FROM TMP_NPART1 WHERE coalesce( CodPart1, 0) &gt; 0 ORDER BY CodPart1 ) LOOP
      SELECT CASE WHEN CodIOPART = v_rec.CodIOPART       THEN 0 ELSE 1 END +
             CASE WHEN CreditFurn = v_rec.CreditFurn     THEN 0 ELSE 1 END +
             CASE WHEN VolumTranzC = v_rec.VolumTranzC   THEN 0 ELSE 1 END +
             CASE WHEN CreditClient = v_rec.CreditClient THEN 0 ELSE 1 END +
             CASE WHEN SCADENTAV = v_rec.SCADENTAV       THEN 0 ELSE 1 END +
             CASE WHEN SCADENTAC = v_rec.SCADENTAC       THEN 0 ELSE 1 END +
             CASE WHEN CASSBAZAMIN = v_rec.CASSBAZAMIN   THEN 0 ELSE 1 END +
             CASE WHEN DISCOUNT = v_rec.DISCOUNT         THEN 0 ELSE 1 END +
             CASE WHEN SimbolCASS = v_rec.SimbolCASS     THEN 0 ELSE 1 END +
             CASE WHEN GDPR = v_rec.GDPR                 THEN 0 ELSE 1 END +
             CASE WHEN VolumTranzF = v_rec.VolumTranzF   THEN 0 ELSE 1 END ,
            anstart, lunastart
      INTO vRecNo, vAn, vLuna
      FROM NPART1
      WHERE CodPart1 = coalesce( v_rec.CodPart1, 0);

      if ( vRecNo &gt; 0) then
        if ( v_rec.anstart = vAn) and ( v_rec.lunastart = vLuna) then
          UPDATE NPART1
          SET
              CodIOPART    = v_rec.CodIOPART,
              CreditFurn   = v_rec.CreditFurn,
              VolumTranzC  = v_rec.VolumTranzC,
              CreditClient = v_rec.CreditClient,
              VolumTranzF  = v_rec.VolumTranzF,
              SCADENTAV    = v_rec.SCADENTAV,
              SCADENTAC    = v_rec.SCADENTAC,
              CASSBAZAMIN  = v_rec.CASSBAZAMIN,
              SimbolCASS   = v_rec.SimbolCASS,
              GDPR         = v_rec.GDPR,
              DISCOUNT     = v_rec.DISCOUNT
          WHERE CodPart1   = v_rec.CodPart1 ;
        else
          INSERT INTO NPART1 (CodPart, CodIOPART, CodPart1, CreditFurn, VolumTranzC, SCADENTAV, SCADENTAC, CASSBAZAMIN,
                              SimbolCASS, GDPR, DISCOUNT, CreditClient, VolumTranzF, anstart, lunastart )
          VALUES (RecId, v_rec.CodIOPART, nextval('SEQ_NPART1_CODPART1'), v_rec.CreditFurn, v_rec.VolumTranzC, v_rec.SCADENTAV, v_rec.SCADENTAC, v_rec.CASSBAZAMIN,
                v_rec.SimbolCASS, v_rec.GDPR, v_rec.DISCOUNT, v_rec.CreditClient, v_rec.VolumTranzF, v_rec.anstart, v_rec.lunastart );
        end if;
      end if;
    END LOOP;

    DELETE FROM NPARTB WHERE (CodPart = RecId and CodPartB not in (SELECT CodPartB FROM TMP_NPARTB WHERE coalesce( CodPartB, 0) &lt;&gt; 0 )) ;

    INSERT INTO NPARTB (CodPartB, CodPart, CodBank, implicit, CodLocalit, ContBanca, Sucursala, CODSWIFT, TIPCOMISION, CONTTVA, OBS, CODMONEDA )
    SELECT nextval('SEQ_NPARTB_CODPARTB'), RecId, CodBank, implicit, CodLocalit, ContBanca, Sucursala, CODSWIFT, TIPCOMISION, CONTTVA, OBS, CODMONEDA
    FROM TMP_NPARTB WHERE CodPartB &lt; 0;

    FOR v_rec IN (SELECT * FROM TMP_NPARTB WHERE coalesce( CodPartB, 0) &gt; 0 ORDER BY CodPartB ) LOOP
      SELECT count(*) INTO vRecNo FROM NPARTB WHERE CodPartB = coalesce( v_rec.CodPartB, 0);

      if ( vRecNo = 1) then
        UPDATE NPARTB
        SET
            CodPart     = RecId,
            CodBank     = v_rec.CodBank,
            implicit    = v_rec.Implicit,
            CodLocalit  = v_rec.CodLocalit,
            ContBanca   = v_rec.ContBanca,
            Sucursala   = v_rec.Sucursala,
            CODSWIFT    = v_rec.CODSWIFT,
            TIPCOMISION = V_REC.TIPCOMISION,
            CONTTVA     = V_REC.CONTTVA,
            OBS         = V_REC.OBS,
            CODMONEDA   = V_REC.CODMONEDA
        WHERE CodPartB = v_rec.CodPartB ;
      end if;
    END LOOP;

    DELETE FROM NPARTCODFISC WHERE CodPart = RecId and COD_CODFISCAL not in (SELECT COD_CODFISCAL FROM TMP_NPARTCODFISC );

    FOR V_REC IN (SELECT * FROM TMP_NPARTCODFISC WHERE COD_CODFISCAL &lt; 0 ) LOOP
      SELECT nextval('SEQ_NPARTCODFISC_COD_CODFISCAL') INTO VCOD;

      UPDATE TMP_NAGENDA
      SET COD_CODFISCAL = VCOD
      WHERE COD_CODFISCAL = V_REC.COD_CODFISCAL ;

      INSERT INTO NPARTCODFISC (COD_CODFISCAL, CODPART, CODFISCAL, PRINCIPAL)
      VALUES (VCOD, RecId, trim(V_REC.CODFISCAL), V_REC.PRINCIPAL);
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_NPARTCODFISC WHERE coalesce( COD_CODFISCAL, 0) &gt; 0 ORDER BY COD_CODFISCAL ) LOOP
      UPDATE NPARTCODFISC
      SET
          CodPart = RecId,
          CODFISCAL = trim(V_REC.CODFISCAL),
          PRINCIPAL = V_REC.PRINCIPAL
      WHERE COD_CODFISCAL = V_REC.COD_CODFISCAL ;
    END LOOP;

    DELETE FROM NPARTLSTCLASE WHERE CodPart = RecId and CODNPARTLSTCLASE not in (SELECT CODNPARTLSTCLASE FROM TMP_NPARTLSTCLASE );

    INSERT INTO NPARTLSTCLASE ( CODNPARTLSTCLASE, CODPART, CODCLASA )
    SELECT nextval('SEQ_NPARTLC_CODNPARTLC'), RecId, CODCLASA
    FROM TMP_NPARTLSTCLASE WHERE CODNPARTLSTCLASE &lt; 0;

    FOR V_REC IN (SELECT * FROM TMP_NPARTLSTCLASE WHERE coalesce( CODNPARTLSTCLASE, 0) &gt; 0 ORDER BY CODNPARTLSTCLASE ) LOOP
      UPDATE NPARTLSTCLASE
      SET
          CodPart = RecId,
          CODCLASA = V_REC.CODCLASA
      WHERE CODNPARTLSTCLASE = V_REC.CODNPARTLSTCLASE ;
    END LOOP;

    FOR V_REC IN (SELECT * FROM NAGENDA WHERE ( codpart = RecId and codagenda not in (SELECT codagenda FROM TMP_NAGENDA WHERE coalesce( codagenda, 0) &lt;&gt; 0 )) ) LOOP
      DELETE FROM NPARTTR_LNK1 WHERE CODAGENDA = V_REC.CODAGENDA;
      DELETE FROM NAGENDA1     WHERE CODAGENDA = V_REC.CODAGENDA;
      DELETE FROM NAGENDA      WHERE CODAGENDA = V_REC.CODAGENDA;
    END LOOP;

    FOR V_REC IN (SELECT A1.CODAGENDA1, A1.CODAGENDA
                  FROM NAGENDA1 A1, NAGENDA A
                  WHERE A.codpart = RecId
                        and A.CODAGENDA = A1.CODAGENDA
                        and A1.codagenda1 not in (SELECT codagenda1 FROM TMP_NAGENDA1 ) )
    LOOP
      DELETE FROM NAGENDA1 WHERE CODAGENDA1 = V_REC.CODAGENDA1;
      CALL PRC_AL_REFRESH('nagenda1', V_REC.CODAGENDA);
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_NAGENDA WHERE codagenda &lt; 0 ) LOOP
      SELECT nextval('SEQ_NAGENDA_CODAGENDA') INTO VCOD;
      PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('NAGENDA', VCOD, V_REC.CODAGENDA);

      UPDATE TMP_NPERSCONTACT SET CODLOCATIE = VCOD WHERE CODLOCATIE = V_REC.CODAGENDA ;

      UPDATE TMP_NPARTTR_LNK1 SET CODAGENDA = VCOD  WHERE CODAGENDA = V_REC.CODAGENDA ;

      UPDATE TMP_NAGENDA1     SET CODAGENDA = VCOD  WHERE CODAGENDA = V_REC.CODAGENDA ;

      UPDATE TMP_NAGENDA      SET CODAGENDA = VCOD,
                                  CODPART = RECID,
                                  ADRESA = '(NEW)(RECORD)(FROM)(INSERT)'
                                                    WHERE CODAGENDA = V_REC.CODAGENDA ;

      UPDATE TMP_NAGENDA      SET CODCORESP = VCOD  WHERE CODCORESP = V_REC.CODAGENDA ;
    END LOOP;

    INSERT INTO NAGENDA (obs, codagenda, tip, codlocalit, sediusocial, telefon, fax, email, sector, strada, nr1, nr2, bloc, scara, etaj, apart, codpostal,
                         km, codbankcont, codpart, codgest, codsubunit, CODTIPSEDIU, CODFISCAL, CODAGENT, Codclient, COEFUTILAJE, SUPRAFATA, MODSERVIRE,
                         IDSEDIU, COD_CODFISCAL, CODTRASEU, POZTRASEU, CODTRASEU1, POZTRASEU1, Inactiv, Codcoresp, TranspClient, EDI_EXPTIP, EDI_PARTTIP,
                         EDI_PARTID, EDI_OBJTIP, GLN, GESTLIVRARE, LONGITUDINE, LATITUDINE, OBS2, CODANTREPOZIT, ZileTransport,
                         VERFACT, VERDISPLIVR, VERPROFORMA, VERFACTAVIZ, VERAVIZIES)
    SELECT obs, codagenda, tip, codlocalit, sediusocial, telefon, fax, email, sector, strada, nr1, nr2, bloc, scara, etaj, apart, codpostal,
           km, codbankcont, codpart, codgest, codsubunit, CODTIPSEDIU, CODFISCAL, CODAGENT, Codclient, COEFUTILAJE, SUPRAFATA, MODSERVIRE,
           IDSEDIU, COD_CODFISCAL, CODTRASEU, POZTRASEU, CODTRASEU1, POZTRASEU1, Inactiv, Codcoresp, TranspClient, EDI_EXPTIP, EDI_PARTTIP,
           EDI_PARTID, EDI_OBJTIP, GLN, GESTLIVRARE, LONGITUDINE, LATITUDINE, OBS2, CODANTREPOZIT, ZileTransport,
           VERFACT, VERDISPLIVR, VERPROFORMA, VERFACTAVIZ, VERAVIZIES
    FROM TMP_NAGENDA WHERE ADRESA = '(NEW)(RECORD)(FROM)(INSERT)';

    FOR v_rec IN (SELECT * FROM TMP_NAGENDA WHERE coalesce( codagenda, 0) &gt; 0 ORDER BY codagenda ) LOOP
      SELECT count(*) INTO vRecNo FROM NAGENDA WHERE codagenda = coalesce( v_rec.codagenda, 0);

      if ( vRecNo = 1) then
        UPDATE NAGENDA
        SET
            obs           = v_rec.obs,
            tip           = v_rec.tip,
            codlocalit    = v_rec.codlocalit,
            sediusocial   = v_rec.sediusocial,
            telefon       = v_rec.telefon,
            fax           = v_rec.fax,
            email         = v_rec.email,
            sector        = v_rec.sector,
            strada        = v_rec.strada,
            nr1           = v_rec.nr1,
            nr2           = v_rec.nr2,
            bloc          = v_rec.bloc,
            scara         = v_rec.scara,
            etaj          = v_rec.etaj,
            apart         = v_rec.apart,
            codpostal     = v_rec.codpostal,
            km            = v_rec.km,
            codbankcont   = v_rec.codbankcont,
            codpart       = RecId,
            codgest       = v_rec.codgest,
            codsubunit    = v_rec.codsubunit,
            CODTIPSEDIU   = V_REC.CODTIPSEDIU,
            CODFISCAL     = V_REC.CODFISCAL,
            CODAGENT      = V_REC.CODAGENT,
            CODCLIENT     = V_REC.CODCLIENT,
            COEFUTILAJE   = V_REC.COEFUTILAJE,
            SUPRAFATA     = V_REC.SUPRAFATA,
            MODSERVIRE    = V_REC.MODSERVIRE,
            IDSEDIU       = V_REC.IDSEDIU,
            COD_CODFISCAL = V_REC.COD_CODFISCAL,
            codtraseu     = v_rec.codtraseu,
            poztraseu     = v_rec.poztraseu,
            codtraseu1    = v_rec.codtraseu1,
            poztraseu1    = v_rec.poztraseu1,
            Inactiv       = v_rec.Inactiv,
            codCoresp     = v_rec.codCoresp,
            TranspClient  = v_rec.TranspClient,
            EDI_EXPTIP    = v_rec.EDI_EXPTIP,
            EDI_PARTTIP   = v_rec.EDI_PARTTIP,
            EDI_PARTID    = v_rec.EDI_PARTID,
            EDI_OBJTIP    = v_rec.EDI_OBJTIP,
            GLN           = v_rec.GLN,
            GESTLIVRARE   = V_REC.GESTLIVRARE,
            LONGITUDINE   = V_REC.LONGITUDINE,
            LATITUDINE    = V_REC.LATITUDINE,
            OBS2          = V_REC.OBS2,
            CODANTREPOZIT = V_REC.CODANTREPOZIT,
            ZileTransport = V_REC.ZileTransport,
            VERFACT       = v_rec.VERFACT,
            VERDISPLIVR   = v_rec.VERDISPLIVR,
            VERPROFORMA   = v_rec.VERPROFORMA,
            VERFACTAVIZ   = v_rec.VERFACTAVIZ,
            VERAVIZIES    = v_rec.VERAVIZIES
        WHERE codagenda   = v_rec.codagenda;
      end if;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_NAGENDA1 ) LOOP
      if V_REC.CODAGENDA1 &lt; 0 then
        INSERT INTO NAGENDA1 (CODAGENDA1, CODAGENDA, ANSTART, LUNASTART, CREDITCLIENT, ZILEDEPASIRE, NRFACTSOLD, SCADENTAV )
        VALUES ( nextval('SEQ_NAGENDA1_CODAGENDA1'), V_REC.CODAGENDA, V_REC.ANSTART, V_REC.LUNASTART, V_REC.CREDITCLIENT, V_REC.ZILEDEPASIRE, V_REC.NRFACTSOLD, V_REC.SCADENTAV );
      else
        UPDATE NAGENDA1
        SET
          ANSTART        = V_REC.ANSTART,
          LUNASTART      = V_REC.LUNASTART,
          CREDITCLIENT   = V_REC.CREDITCLIENT,
          ZILEDEPASIRE   = V_REC.ZILEDEPASIRE,
          NRFACTSOLD     = V_REC.NRFACTSOLD,
          SCADENTAV      = V_REC.SCADENTAV
        WHERE CODAGENDA1 = V_REC.CODAGENDA1 ;
      end if;
      CALL PRC_AL_REFRESH('nagenda1', V_REC.CODAGENDA);
    END LOOP;

    DELETE FROM NPARTTR WHERE (CodPart = RecId and CodPartTr not in (SELECT CodPartTr FROM TMP_NPARTTR WHERE coalesce( CodPartTr, 0) &lt;&gt; 0 )) ;

    INSERT INTO NPARTTR (CodPartTr, CodPart, Delegat, cnp, doc, SerieDoc, NrDoc, Eliberat, MijlTransp, NrTransp, ACTIV, DATADOC, implicit, OBS,
                         PERMIS, NRPASS, CODTARA, ADRESA, CODLOCALIT, TELEFON, EMAIL )
    SELECT nextval('SEQ_NPARTTR_CODPARTTR'), RecId, Delegat, cnp, doc, SerieDoc, NrDoc, Eliberat, MijlTransp, NrTransp, ACTIV, DATADOC, implicit, OBS,
           PERMIS, NRPASS, CODTARA, ADRESA, CODLOCALIT, TELEFON, EMAIL
    FROM TMP_NPARTTR WHERE CodPartTr &lt; 0;

    FOR v_rec IN (SELECT * FROM TMP_NPARTTR WHERE coalesce( CodPartTr, 0) &gt; 0 ORDER BY CodPartTr ) LOOP
      SELECT count(*) INTO vRecNo FROM NPARTTR WHERE CodPartTr = coalesce( v_rec.CodPartTr, 0);

      if ( vRecNo = 1) then
        UPDATE NPARTTR
        SET
          CodPart    = RecId,
          Delegat    = v_rec.Delegat,
          cnp        = v_rec.cnp,
          doc        = v_rec.doc,
          SerieDoc   = v_rec.SerieDoc,
          NrDoc      = v_rec.NrDoc,
          Eliberat   = v_rec.Eliberat,
          MijlTransp = v_rec.MijlTransp,
          NrTransp   = v_rec.NrTransp,
          ACTIV      = V_REC.ACTIV,
          implicit   = V_REC.IMPLICIT,
          DATADOC    = V_REC.DATADOC,
          OBS        = V_REC.OBS,
          PERMIS     = V_REC.PERMIS,
          NRPASS     = V_REC.NRPASS,
          CODTARA    = V_REC.CodTara,
          ADRESA     = V_REC.Adresa,
          CODLOCALIT = V_REC.CodLocalit,
          TELEFON    = V_REC.Telefon
        WHERE CodPartTr = v_rec.CodPartTr ;
      end if;
    END LOOP;

    FOR V_REC IN (SELECT * FROM NPARTTR_LNK LNK WHERE CODPART = RECID and not exists (SELECT CODPARTTRLNK FROM TMP_NPARTTR_LNK WHERE CODPARTTRLNK = LNK.CODPARTTRLNK ) )
    LOOP
      DELETE FROM NPARTTR_LNK  WHERE CODPARTTRLNK = V_REC.CODPARTTRLNK;
      DELETE FROM NPARTTR_LNK1 WHERE CODPARTTRLNK = V_REC.CODPARTTRLNK;
    END LOOP;

    FOR V_REC IN (SELECT LNK.CODPARTTRLNK, LNK1.CODPARTTRLNK1
                  FROM NPARTTR_LNK LNK, NPARTTR_LNK1 LNK1
                  WHERE LNK.CODPART = RECID
                        and LNK1.CODPARTTRLNK = LNK.CODPARTTRLNK
                        and not exists (SELECT CODPARTTRLNK1 FROM TMP_NPARTTR_LNK1 WHERE CODPARTTRLNK1 = LNK1.CODPARTTRLNK1 ) )
    LOOP
      DELETE FROM NPARTTR_LNK1 WHERE CODPARTTRLNK1 = V_REC.CODPARTTRLNK1;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_NPARTTR_LNK ) LOOP
      if V_REC.CODPARTTRLNK &gt; 0 then
        UPDATE NPARTTR_LNK
        SET
          CODPARTTR = V_REC.CODPARTTR,
          SEDII = V_REC.SEDII,
          CODPART = RECID
        WHERE CODPARTTRLNK = V_REC.CODPARTTRLNK ;
      else
        SELECT nextval('SEQ_NPARTTR_LNK_CODPARTTRLNK') INTO VCOD;

        UPDATE TMP_NPARTTR_LNK1 SET CODPARTTRLNK = VCOD WHERE CODPARTTRLNK = V_REC.CODPARTTRLNK ;

        INSERT INTO NPARTTR_LNK (CODPARTTRLNK, CODPARTTR, CODPART, SEDII)
        VALUES (VCOD, V_REC.CODPARTTR, RECID, V_REC.SEDII );
      end if;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_NPARTTR_LNK1 ) LOOP
      if V_REC.CODPARTTRLNK1 &gt; 0 then
        UPDATE NPARTTR_LNK1
        SET
          CODPARTTRLNK = V_REC.CODPARTTRLNK,
          CODAGENDA = V_REC.CODAGENDA
        WHERE CODPARTTRLNK1 = V_REC.CODPARTTRLNK1 ;
      else
        INSERT INTO NPARTTR_LNK1 ( CODPARTTRLNK1, CODPARTTRLNK, CODAGENDA )
        VALUES ( nextval('SEQ_NPARTTR_LNK1_CODPARTTRLNK1'), V_REC.CODPARTTRLNK, V_REC.CODAGENDA );
      end if;
    END LOOP;

    DELETE FROM NPERSCONTACT WHERE ( codpart = RecId and codpersc not in (SELECT codpersc FROM TMP_NPERSCONTACT WHERE coalesce( codpersc, 0) &lt;&gt; 0 )) ;

    INSERT INTO NPERSCONTACT (codpersc, nume, prenume, telefon, email, functie, datanastere, SERIEBI, NRBI, ELIBERATBI, DATABI, CNP, rzona,
                              id, tip, codbankcont, codpart, implicit, Obs, CODLOCATIE )
    SELECT nextval('SEQ_NPERSCONTACT_CODPERSC'), nume, prenume, telefon, email, functie, datanastere, SERIEBI, NRBI, ELIBERATBI, DATABI, CNP, rzona,
           id, tip, codbankcont, RecId, implicit, Obs, CODLOCATIE
    FROM TMP_NPERSCONTACT WHERE codpersc &lt; 0;

    FOR v_rec IN (SELECT * FROM TMP_NPERSCONTACT WHERE coalesce( codpersc, 0) &gt; 0 ORDER BY codpersc ) LOOP
      SELECT count(*) INTO vRecNo FROM NPERSCONTACT WHERE codpersc = coalesce( v_rec.codpersc, 0);

      if ( vRecNo = 1) then
        UPDATE NPERSCONTACT
        SET
          nume        = v_rec.nume,
          prenume     = v_rec.prenume,
          telefon     = v_rec.telefon,
          email       = v_rec.email,
          functie     = v_rec.functie,
          datanastere = v_rec.datanastere,
          SERIEBI     = V_REC.SERIEBI,
          NRBI        = V_REC.NRBI,
          ELIBERATBI  = V_REC.ELIBERATBI,
          DATABI      = V_REC.DATABI,
          CNP         = V_REC.CNP,
          rzona       = v_rec.rzona,
          id          = v_rec.id,
          tip         = v_rec.tip,
          codbankcont = v_rec.codbankcont,
          codpart     = RecId,
          implicit    = v_rec.implicit,
          Obs         = v_rec.Obs,
          CODLOCATIE  = V_REC.CODLOCATIE
        WHERE codpersc = v_rec.codpersc ;
      end if;
    END LOOP;

    INSERT INTO PARTTOT ( CodPartTot, CodPart, SoldReal, Neoperat, anstart, lunastart )
    SELECT nextval('SEQ_PARTTOT_CODPARTTOT'), RecId, SoldReal, Neoperat, anstart, lunastart
    FROM TMP_PARTTOT WHERE CodPartTot &lt; 0;

    FOR v_rec IN (SELECT * FROM TMP_PARTTOT WHERE coalesce( CodPartTot, 0) &gt; 0 ORDER BY CodPartTot ) LOOP
      SELECT CASE WHEN SoldReal = v_rec.SoldReal THEN 0 ELSE 1 END +
             CASE WHEN Neoperat = v_rec.Neoperat THEN 0 ELSE 1 END ,
             anstart, lunastart
      INTO vRecNo, vAn, vLuna
      FROM PARTTOT WHERE CodPartTot = coalesce( v_rec.CodPartTot, 0);

      if ( vRecNo &gt; 0) then
        if ( v_rec.anstart = vAn) and ( v_rec.lunastart = vLuna) then
          UPDATE PARTTOT
          SET
            SoldReal       = v_rec.SoldReal,
            Neoperat       = v_rec.Neoperat
          WHERE CodPartTot = v_rec.CodPartTot ;
        else
          INSERT INTO PARTTOT (CodPartTot, CodPart, SoldReal, Neoperat, anstart, lunastart )
          VALUES ( nextval('SEQ_PARTTOT_CODPARTTOT'), RecId, v_rec.SoldReal, v_rec.Neoperat, v_rec.anstart, v_rec.lunastart );
        end if;
      end if;
    END LOOP;

    INSERT INTO SOLDPART ( CodSoldPart, CodPart, CodCont, CodMoneda, SoldLei, SoldValuta, anstart, lunastart )
    SELECT nextval('SEQ_SOLDPART_CODSOLDPART'), RecId, CodCont, CodMoneda, SoldLei, SoldValuta, anstart, lunastart
    FROM TMP_SOLDPART WHERE CodSoldPart &lt; 0;

    FOR v_rec IN (SELECT * FROM TMP_SOLDPART WHERE coalesce( CodSoldPart, 0) &gt; 0 ORDER BY CodSoldPart ) LOOP
      SELECT CASE WHEN CodCont = v_rec.CodCont       THEN 0 ELSE 1 END +
             CASE WHEN CodMoneda = v_rec.CodMoneda   THEN 0 ELSE 1 END +
             CASE WHEN SoldLei = v_rec.SoldLei       THEN 0 ELSE 1 END +
             CASE WHEN SoldValuta = v_rec.SoldValuta THEN 0 ELSE 1 END ,
             anstart, lunastart
      INTO vRecNo, vAn, vLuna
      FROM SOLDPART WHERE CodSoldPart = coalesce( v_rec.CodSoldPart, 0);

      if ( vRecNo &gt; 0) then
        if ( v_rec.anstart = vAn) and ( v_rec.lunastart = vLuna) then
          UPDATE SOLDPART
          SET
            CodCont         = v_rec.CodCont,
            CodMoneda       = v_rec.CodMoneda,
            SoldLei         = v_rec.SoldLei,
            SoldValuta      = v_rec.SoldValuta
          WHERE CodSoldPart = v_rec.CodSoldPart ;
        else
          INSERT INTO SOLDPART (CodSoldPart, CodPart, CodCont, CodMoneda, SoldLei, SoldValuta, anstart, lunastart )
          VALUES ( nextval('SEQ_SOLDPART_CODSOLDPART'), RecId, v_rec.CodCont, v_rec.CodMoneda, v_rec.SoldLei, v_rec.SoldValuta, v_rec.anstart, v_rec.lunastart );
        end if;
      end if;
    END LOOP;

    DELETE FROM NPARTDISC WHERE (CodPart = RecId and CodPartDisc not in (SELECT CodPartDisc FROM TMP_NPARTDISC WHERE coalesce( CodPartDisc, 0) &lt;&gt; 0 )) ;

    INSERT INTO NPARTDISC (CodPartDisc, CodPart, CodCategDisc, Indexlocal )
    SELECT nextval('SEQ_NPARTDISC_CODPARTDISC'), RecId, CodCategDisc, Indexlocal
    FROM TMP_NPARTDISC WHERE CodPartDisc &lt; 0;

    FOR v_rec IN (SELECT * FROM TMP_NPARTDISC WHERE coalesce( CodPartDisc, 0) &gt; 0 ORDER BY CodPartDisc ) LOOP
      SELECT count(*) INTO vRecNo FROM NPARTDISC WHERE CodPartDisc = coalesce( v_rec.CodPartDisc, 0);

      if ( vRecNo = 1) then
        UPDATE NPARTDISC
        SET
          CodPart         = RecId,
          CodCategDisc    = v_rec.CodCategDisc,
          Indexlocal      = v_Rec.Indexlocal
        WHERE CodPartDisc = v_rec.CodPartDisc ;
      end if;
    END LOOP;

    if (SELECT pkg_globals_GETSUBUNITATE.WME_RESULT FROM pkg_globals_GETSUBUNITATE(null,null)) &gt; 1 then
      DELETE FROM NPARTSUBUNIT NS WHERE NS.SUBUNITATEA = (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(null,null))
                                        and NS.CODPART = RECID
                                        and not exists (SELECT TMP.CODPARTSUBUNIT FROM TMP_NPARTSUBUNIT TMP WHERE TMP.CODPARTSUBUNIT = NS.CODPARTSUBUNIT );

      FOR V_REC IN (SELECT * FROM TMP_NPARTSUBUNIT ) LOOP
        if V_REC.CODPARTSUBUNIT &gt; 0 then
          UPDATE NPARTSUBUNIT
          SET
            CODPART            = V_REC.CODPART,
            SUBUNITATEA        = V_REC.SUBUNITATEA,
            ZIAPROVIZ          = V_REC.ZIAPROVIZ,
            PERAPROVIZ         = V_REC.PERAPROVIZ
          WHERE CODPARTSUBUNIT = V_REC.CODPARTSUBUNIT ;
        else
          INSERT INTO NPARTSUBUNIT ( CODPARTSUBUNIT, CODPART, SUBUNITATEA, ZIAPROVIZ, PERAPROVIZ )
          VALUES ( nextval('SEQ_NPARTSUBUNIT_CODPARTS'), V_REC.CODPART, V_REC.SUBUNITATEA, V_REC.ZIAPROVIZ, V_REC.PERAPROVIZ );
        end if;
      END LOOP;
    end if;

    INSERT INTO TMP_NPARTSUBUNIT (CODPARTSUBUNIT, CODPART, SUBUNITATEA, ZIAPROVIZ, PERAPROVIZ )
    SELECT CODPARTSUBUNIT, CODPART, SUBUNITATEA, ZIAPROVIZ, PERAPROVIZ
    FROM NPARTSUBUNIT
    WHERE CODPART = RECID
          and coalesce( SUBUNITATEA, 1) = CASE WHEN (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(null,null))= 1 THEN coalesce( SUBUNITATEA, 1)
                                               ELSE (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(null,null))
                                          END ;

    DELETE FROM NPART1CRM WHERE CODPART = RECID and CODPART1CRM not in (SELECT CODPART1CRM FROM TMP_NPART1CRM );

    FOR v_rec IN (SELECT * FROM TMP_NPART1CRM WHERE CODPART1CRM &lt; 0 ) LOOP
      SELECT nextval('SEQ_NPART1CRM_CODPART1CRM') INTO vcod;
      UPDATE tmp_npartconcurenti SET codpart1crm = vcod WHERE codpart1crm = v_rec.codpart1crm ;
      UPDATE tmp_npartdomact     SET codpart1crm = vcod WHERE codpart1crm = v_rec.codpart1crm ;
      UPDATE tmp_npartactivit    SET codpart1crm = vcod WHERE codpart1crm = v_rec.codpart1crm ;

      INSERT INTO NPART1CRM (codpart1crm, codpart, anstart, lunastart, cifraafaceri, nrangajati, lead, sursalead,
                             Stare, codresponsabil, MODPLATA, CIP, DATASTART, DATAEND, Profit )
      VALUES (vcod, RecId, v_rec.anstart, v_rec.lunastart, v_rec.cifraafaceri, v_rec.nrangajati, v_rec.lead, v_rec.sursalead,
              v_rec.Stare, v_rec.codresponsabil, V_REC.MODPLATA, V_REC.CIP, V_REC.DATASTART, V_REC.DATAEND, v_rec.Profit );
    END LOOP;

    FOR v_rec IN (SELECT * FROM TMP_NPART1CRM WHERE coalesce( CodPart1CRM, 0) &gt; 0 ORDER BY CodPart1CRM ) LOOP
      UPDATE NPART1CRM
      SET
        anstart        = v_rec.anstart,
        lunastart      = v_rec.lunastart,
        cifraafaceri   = v_rec.cifraafaceri,
        nrangajati     = v_rec.nrangajati,
        lead           = v_rec.lead,
        sursalead      = v_rec.sursalead,
        Stare          = v_rec.Stare,
        codresponsabil = v_rec.codresponsabil,
        MODPLATA       = v_rec.MODPLATA,
        CIP            = V_REC.CIP,
        DATASTART      = V_REC.DATASTART,
        DATAEND        = V_REC.DATAEND,
        Profit         = v_rec.Profit
      WHERE CodPart1CRM = v_rec.CodPart1CRM ;
    END LOOP;

    DELETE FROM NPARTCONCURENTI WHERE CodPart = RecId and CodPartConcurent not in (SELECT CodPartConcurent FROM TMP_NPARTCONCURENTI );

    INSERT INTO NPARTCONCURENTI ( CodPartConcurent, CodPart, CodConcurent, CODPART1CRM )
    SELECT nextval('SEQ_NPARTCONCURENTI_CPC'), RecId, CodConcurent, CODPART1CRM
    FROM TMP_NPARTCONCURENTI WHERE CodPartConcurent &lt; 0;

    FOR v_Rec IN (SELECT * FROM TMP_NPARTCONCURENTI WHERE coalesce( CodPartConcurent, 0) &gt; 0 ORDER BY CodPartConcurent ) LOOP
      UPDATE NPARTCONCURENTI
      SET
        CodPart      = RecId,
        CodConcurent = v_Rec.CodConcurent
      WHERE CodPartConcurent = v_Rec.CodPartConcurent ;
    END LOOP;

    DELETE FROM NPARTACTIVIT WHERE CodPart = RecId and CodPartActivit not in (SELECT CodPartActivit FROM TMP_NPARTACTIVIT );

    INSERT INTO NPARTACTIVIT ( CodPartActivit, CodPart, Dim, CodActivit, CODPART1CRM )
    SELECT nextval('SEQ_NPARTACTIVIT_CPA'), RecId, Dim, CodActivit, CODPART1CRM
    FROM TMP_NPARTACTIVIT WHERE CodPartActivit &lt; 0;

    FOR v_Rec IN (SELECT * FROM TMP_NPARTACTIVIT WHERE coalesce( CodPartActivit, 0) &gt; 0 ORDER BY CodPartActivit ) LOOP
      UPDATE NPARTACTIVIT
      SET
        CodPart    = RecId,
        CodActivit = v_Rec.CodActivit,
        Dim        = v_rec.Dim
      WHERE CodPartActivit = v_Rec.CodPartActivit ;
    END LOOP;

    DELETE FROM NPARTDOMACT WHERE CODPART = RECID and CODPARTDOMACT not in (SELECT CODPARTDOMACT FROM TMP_NPARTDOMACT );

    FOR V_REC IN (SELECT * FROM TMP_NPARTDOMACT ) LOOP
      if V_REC.CODPARTDOMACT &gt; 0 then
        UPDATE NPARTDOMACT
        SET CODDOMENIUACT = V_REC.CODDOMENIUACT
        WHERE CODPARTDOMACT = V_REC.CODPARTDOMACT ;
      else
        INSERT INTO NPARTDOMACT ( CODPARTDOMACT, CODPART, CODDOMENIUACT, CODPART1CRM )
        VALUES ( nextval('SEQ_NPARTDOMACT_CODPARTDOMACT'), RECID, V_REC.CODDOMENIUACT, V_REC.CODPART1CRM );
      end if;
    END LOOP;

  -- update sus, insert aici
  ELSE
    SELECT TvaLaIncasare INTO vTVAI FROM TMP_NPART;

    if vTVAI is null then
      BEGIN
        SELECT CodFisCal INTO sCui FROM TMP_NPARTCODFISC WHERE PRINCIPAL = 1;
      EXCEPTION when others then sCui := null;
      END;

      if sCui is not null then
        vTVAI := (SELECT pkg_NomPart_TvaLaIncasare.WME_RESULT FROM pkg_NomPart_TvaLaIncasare(null,sCui,null));
      end if;

      if vTVAI is not null then
        UPDATE TMP_NPART SET TvaLaIncasare = vTVAI ;
      end if;
    end if;

    SELECT nextval('SEQ_NPART_CODPART') INTO RecId;
    PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('NPART', RecId);

    INSERT INTO NPART (CodPart, Den_part, CodExtern, CodMoneda, RegCom, EXPIRAREAUTORIZ, CODSTATISTICBNR, Autorizatie, CodIntern, CodClasa,
                       CodCategPret, TipPart, ScadentaC, ScadentaV, Discount, CodCategDisc, Blocat, TIPPARTENER, DATAADAUGARII, OBS, POZA,
                       PERSOANAFIZICA, VERFACT, VERDISPLIVR, COLDISCOUNT, INFOBLOCAT, MusaiColet, STRATEGIC, CifraAfaceri, DomeniuActiv,
                       NrAngajati, SursaLead, lead, TVALAINCASARE, MODAPLICPROCDISC, PROCCURSTRANSF, VERPROFORMA, FIDELIZARE, Majorari,
                       TipBlocaj, SPLITTVA, POPRIRE_ANAF, codresponsabil, CodDomeniuAct, DocDefOnorCom, ModPromoFactCom, ValidarePretOferta,
                       IESCUCOMANDA, VERFACTAVIZ, ZIAPROVIZ, PERAPROVIZ, CODCONTRACTCadru,
                       EF_Item, EF_Party,
                       DATANASTERE, GDPR, ZILELIVRARE, SAFT_EXPORT,
                       FaraPenalizari, INACTIV, preOfeFurnVar, Tipanalizapret, VerAvizIes, ef_ImpArtGen, EF_CUSTOM, EF_PROIECT, EF_Taxe, CategTarif, ZileAchiz, Culoare)
    SELECT RecId, Den_part, CodExtern, CodMoneda, RegCom, EXPIRAREAUTORIZ, CODSTATISTICBNR, Autorizatie, CodIntern, CodClasa, CodCategPret,
           TipPart, ScadentaC, ScadentaV, Discount, CodCategDisc, Blocat, TIPPARTENER, DATAADAUGARII, OBS, POZA, PERSOANAFIZICA, VERFACT,
           VERDISPLIVR, COLDISCOUNT, INFOBLOCAT, MusaiColet, STRATEGIC, CifraAfaceri, DomeniuActiv, NrAngajati, SursaLead, lead, TVALAINCASARE,
           MODAPLICPROCDISC, PROCCURSTRANSF, VERPROFORMA, FIDELIZARE, Majorari, TipBlocaj, SPLITTVA, POPRIRE_ANAF, codresponsabil, CodDomeniuAct,
           DocDefOnorCom, ModPromoFactCom, ValidarePretOferta, IESCUCOMANDA, VERFACTAVIZ, ZIAPROVIZ, PERAPROVIZ, CODCONTRACTCadru,
           EF_Item, EF_Party,
           DATANASTERE,
           GDPR, ZILELIVRARE, SAFT_EXPORT, FaraPenalizari, INACTIV, preOfeFurnVar, Tipanalizapret, VerAvizIes, ef_ImpArtGen, EF_CUSTOM, EF_PROIECT, COALESCE(EF_Taxe, 0), Coalesce(CategTarif,0), ZileAchiz, Culoare
    FROM TMP_NPART;

    if (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(null,to_number(current_setting('PKG_GLOBALS.USERID', true), '999999999999999999'),current_setting('PKG_NOMPART.CT_MONITOR', true))) then
      SELECT 'Partener "' || coalesce(den_part, '') || '"' INTO aDoc FROM npart WHERE codpart = recid;

      perform pkg_userfirme_postlogcucommit('NPART',current_setting('PKG_GLOBALS.USERNAME', true),'A',RECID,
                                    current_setting('PKG_GLOBALS.FIRMANAME', true),
                                    to_number(current_setting('PKG_GLOBALS.SUBUNITATE', true), '999999999999999999'),
                                    null,aDoc,null,
                                    (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(null,null)));
    end if;

    INSERT INTO NPART1 (CodPart, CodIOPART, CodPart1, CreditFurn, VolumTranzC, SCADENTAV, SCADENTAC, CASSBAZAMIN, SimbolCASS, GDPR,
                        DISCOUNT, CreditClient, VolumTranzF, anstart, lunastart )
    SELECT RecId, CodIOPART, nextval('SEQ_NPART1_CODPART1'), CreditFurn, VolumTranzC, SCADENTAV, SCADENTAC, CASSBAZAMIN, SimbolCASS, GDPR,
           DISCOUNT, CreditClient, VolumTranzF, anstart, lunastart
    FROM TMP_NPART1;

    FOR v_rec IN (SELECT * FROM TMP_NPART1CRM ) LOOP
      SELECT nextval('SEQ_NPART1CRM_CODPART1CRM') INTO vcod;

      UPDATE tmp_npartconcurenti SET codpart1crm = vcod WHERE codpart1crm = v_rec.codpart1crm ;
      UPDATE tmp_npartdomact     SET codpart1crm = vcod WHERE codpart1crm = v_rec.codpart1crm ;
      UPDATE tmp_npartactivit    SET codpart1crm = vcod WHERE codpart1crm = v_rec.codpart1crm ;

      INSERT INTO NPART1CRM (codpart1crm, codpart, anstart, lunastart, cifraafaceri, nrangajati, lead, sursalead, Stare,
                             codresponsabil, MODPLATA, CIP, DATASTART, DATAEND, Profit )
      VALUES (vcod, RecId, v_rec.anstart, v_rec.lunastart, v_rec.cifraafaceri, v_rec.nrangajati, v_rec.lead, v_rec.sursalead, v_rec.Stare,
              v_rec.codresponsabil, v_rec.MODPLATA, V_REC.CIP, V_REC.DATASTART, V_REC.DATAEND, v_rec.Profit );
    END LOOP;

    INSERT INTO NPARTB (CodPartB, CodPart, CodBank, implicit, CodLocalit, ContBanca, Sucursala, CODSWIFT, TIPCOMISION, CONTTVA, OBS, CODMONEDA )
    SELECT nextval('SEQ_NPARTB_CODPARTB'), RecId, CodBank, implicit, CodLocalit, ContBanca, Sucursala, CODSWIFT, TIPCOMISION, CONTTVA, OBS, CODMONEDA
    FROM TMP_NPARTB;

    FOR V_REC IN (SELECT * FROM TMP_NPARTCODFISC WHERE COD_CODFISCAL &lt; 0 ) LOOP
      SELECT nextval('SEQ_NPARTCODFISC_COD_CODFISCAL') INTO VCOD;

      UPDATE TMP_NAGENDA SET COD_CODFISCAL = VCOD WHERE COD_CODFISCAL = V_REC.COD_CODFISCAL ;

      INSERT INTO NPARTCODFISC ( COD_CODFISCAL, CODPART, CODFISCAL, PRINCIPAL )
      VALUES (VCOD, RecId, trim(V_REC.CODFISCAL), V_REC.PRINCIPAL );
    END LOOP;

    INSERT INTO NPARTLSTCLASE ( CODNPARTLSTCLASE, CODPART, CODCLASA )
    SELECT nextval('SEQ_NPARTLC_CODNPARTLC'), RecId, CODCLASA FROM TMP_NPARTLSTCLASE;

    FOR V_REC IN (SELECT * FROM TMP_NAGENDA ) LOOP
      SELECT nextval('SEQ_NAGENDA_CODAGENDA') INTO VCOD;

      PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('NAGENDA', VCOD, V_REC.CODAGENDA);
      UPDATE TMP_NPARTTR_LNK1 SET CODAGENDA  = VCOD WHERE CODAGENDA = V_REC.CODAGENDA ;
      UPDATE TMP_NAGENDA      SET CODAGENDA  = VCOD WHERE CODAGENDA = V_REC.CODAGENDA ;
      UPDATE TMP_NAGENDA1     SET CODAGENDA  = VCOD WHERE CODAGENDA = V_REC.CODAGENDA ;
      UPDATE TMP_NAGENDA      SET CODCORESP  = VCOD WHERE CODCORESP = V_REC.CODAGENDA ;
      UPDATE TMP_NPERSCONTACT SET CODLOCATIE = VCOD WHERE CODLOCATIE = V_REC.CODAGENDA ;
    END LOOP;

    INSERT INTO NAGENDA (codagenda, obs, tip, codlocalit, sediusocial, telefon, fax, email, sector, strada, nr1, nr2, bloc, scara, etaj, apart,
                         codpostal, km, codbankcont, codpart, codgest, codsubunit, CODTIPSEDIU, CODFISCAL, CODAGENT, Codclient, COEFUTILAJE,
                         SUPRAFATA, MODSERVIRE, IDSEDIU, COD_CODFISCAL, CODTRASEU, POZTRASEU, CODTRASEU1, POZTRASEU1, Inactiv, Codcoresp,
                         TranspClient, EDI_EXPTIP, EDI_PARTTIP, EDI_PARTID, EDI_OBJTIP, GLN, GESTLIVRARE, LONGITUDINE, LATITUDINE, OBS2, CODANTREPOZIT, ZileTransport,
                         VERFACT, VERDISPLIVR, VERPROFORMA, VERFACTAVIZ, VERAVIZIES)
    SELECT codagenda, obs, tip, codlocalit, sediusocial, telefon, fax, email, sector, strada, nr1, nr2, bloc, scara, etaj, apart,
           codpostal, km, codbankcont, RecID, codgest, codsubunit, CODTIPSEDIU, CODFISCAL, CODAGENT, Codclient, COEFUTILAJE,
           SUPRAFATA, MODSERVIRE, IDSEDIU, COD_CODFISCAL, CODTRASEU, POZTRASEU, CODTRASEU1, POZTRASEU1, Inactiv, Codcoresp,
           TranspClient, EDI_EXPTIP, EDI_PARTTIP, EDI_PARTID, EDI_OBJTIP, GLN, GESTLIVRARE, LONGITUDINE, LATITUDINE, OBS2, CODANTREPOZIT, ZileTransport,
           VERFACT, VERDISPLIVR, VERPROFORMA, VERFACTAVIZ, VERAVIZIES
    FROM TMP_NAGENDA;

    INSERT INTO NAGENDA1 ( CODAGENDA1, CODAGENDA, ANSTART, LUNASTART, CREDITCLIENT, ZILEDEPASIRE, NRFACTSOLD, SCADENTAV )
    SELECT nextval('SEQ_NAGENDA1_CODAGENDA1'), CODAGENDA, ANSTART, LUNASTART, CREDITCLIENT, ZILEDEPASIRE, NRFACTSOLD, SCADENTAV
    FROM TMP_NAGENDA1;

    FOR V_REC IN (SELECT * FROM TMP_NAGENDA1) LOOP
      CALL PRC_AL_REFRESH('nagenda1', V_REC.CODAGENDA);
    END LOOP;

    INSERT INTO NPARTTR (CodPartTr, CodPart, Delegat, cnp, doc, SerieDoc, NrDoc, Eliberat, MijlTransp, NrTransp, ACTIV, DATADOC, implicit, OBS,
                         PERMIS, NRPASS, CODTARA, ADRESA, CODLOCALIT, TELEFON, EMAIL )
    SELECT nextval('SEQ_NPARTTR_CODPARTTR'), RecId, Delegat, cnp, doc, SerieDoc, NrDoc, Eliberat, MijlTransp, NrTransp, ACTIV, DATADOC, implicit, OBS,
           PERMIS, NRPASS, CODTARA, ADRESA, CODLOCALIT, TELEFON, EMAIL
    FROM TMP_NPARTTR;

    FOR V_REC IN (SELECT * FROM TMP_NPARTTR_LNK ) LOOP
      SELECT nextval('SEQ_NPARTTR_LNK_CODPARTTRLNK') INTO VCOD;

      UPDATE TMP_NPARTTR_LNK1 SET CODPARTTRLNK = VCOD WHERE CODPARTTRLNK = V_REC.CODPARTTRLNK ;

      INSERT INTO NPARTTR_LNK ( CODPARTTRLNK, CODPARTTR, CODPART, SEDII )
      VALUES ( VCOD, V_REC.CODPARTTR, RECID, V_REC.SEDII );
    END LOOP;

    INSERT INTO NPARTTR_LNK1 ( CODPARTTRLNK1, CODPARTTRLNK, CODAGENDA )
    SELECT nextval('SEQ_NPARTTR_LNK1_CODPARTTRLNK1'), CODPARTTRLNK, CODAGENDA FROM TMP_NPARTTR_LNK1;

    INSERT INTO NPERSCONTACT (codpersc, nume, prenume, telefon, email, functie, datanastere, SERIEBI, NRBI, ELIBERATBI, DATABI, CNP,
                              rzona, id, tip, codbankcont, codpart, implicit, Obs, CODLOCATIE )
    SELECT nextval('SEQ_NPERSCONTACT_CODPERSC'), nume, prenume, telefon, email, functie, datanastere, SERIEBI, NRBI, ELIBERATBI, DATABI, CNP,
           rzona, id, tip, codbankcont, RecId, implicit, Obs, CODLOCATIE
    FROM TMP_NPERSCONTACT;

    INSERT INTO PARTTOT ( CodPartTot, CodPart, SoldReal, Neoperat, anstart, lunastart )
    SELECT nextval('SEQ_PARTTOT_CODPARTTOT'), RecId, SoldReal, Neoperat, anstart, lunastart
    FROM TMP_PARTTOT;

    INSERT INTO SOLDPART ( CodSoldPart, CodPart, CodCont, CodMoneda, SoldLei, SoldValuta, anstart, lunastart )
    SELECT nextval('SEQ_SOLDPART_CODSOLDPART'), RecId, CodCont, CodMoneda, SoldLei, SoldValuta, anstart, lunastart
    FROM TMP_SOLDPART;

    INSERT INTO NPARTDISC ( CodPartDisc, CodPart, CodCategDisc, Indexlocal )
    SELECT nextval('SEQ_NPARTDISC_CODPARTDISC'), RecId, CodCategDisc, Indexlocal
    FROM TMP_NPARTDISC;

    INSERT INTO NPARTCONCURENTI ( CodPartConcurent, CodPart, CodConcurent, CODPART1CRM )
    SELECT nextval('SEQ_NPARTCONCURENTI_CPC'), RecId, CodConcurent, CODPART1CRM
    FROM TMP_NPARTCONCURENTI;

    INSERT INTO NPARTACTIVIT ( CodPartActivit, CodPart, Dim, CodActivit, CODPART1CRM )
    SELECT nextval('SEQ_NPARTACTIVIT_CPA'), RecId, Dim, CodActivit, CODPART1CRM
    FROM TMP_NPARTACTIVIT;

    INSERT INTO NPARTDOMACT ( CODPARTDOMACT, CODPART, CODDOMENIUACT, CODPART1CRM )
    SELECT nextval('SEQ_NPARTDOMACT_CODPARTDOMACT'), RECID, CODDOMENIUACT, CODPART1CRM
    FROM TMP_NPARTDOMACT;

    INSERT INTO NPARTSUBUNIT ( CODPARTSUBUNIT, CODPART, SUBUNITATEA, ZIAPROVIZ, PERAPROVIZ )
    SELECT nextval('SEQ_NPARTSUBUNIT_CODPARTS'), CODPART, SUBUNITATEA, ZIAPROVIZ, PERAPROVIZ
    FROM tmp_npartsubunit;
  end if;

  perform PKG_NOMPART_CHECKPART1CRM(RECID);

  CALL PRC_AL_REFRESH('npart1'   , RECID);
  CALL PRC_AL_REFRESH('npart1crm', RECID);

  perform NotifyModif( OPERATION,  RECID, 'NPART');

  perform PKG_NOMPART_DOSYNCPARTRETAIL(RECID);

  if fnc_GetValConstanta('IDSEDIUAUTOMAT', getANLUCRU(), getLUNALUCRU()) = '1' then
    UPDATE NAGENDA SET IDSEDIU = CODAGENDA WHERE CODPART = RECID AND IDSEDIU IS NULL;
  end if;
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS(500);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_get_icontpers_curent</obj_name>
  <obj_hashval>7c412b97f364f69e482590881f8ad1fc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_get_icontpers_curent()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 25 septembrie 2020
  RETURN TO_NUMBER(current_setting('PKG_NOMPERS.ICONT_PERS_CURENT',true),'999999999999999999');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nompers_set_password</obj_name>
  <obj_hashval>398af597a496631e35333850208813bb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nompers_set_password(acodpers numeric, apass character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  UPDATE NPERS SET ACCMAS = aPASS WHERE CODPERS = aCodPers;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomsubunit_sp_postrecords</obj_name>
  <obj_hashval>fc8df38ed5c71716789cce5a85ee6179</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomsubunit_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  VRECNO NUMERIC := 0;
  VAN    NUMERIC := 0;
  VLUNA  NUMERIC := 0;
  VCOD   numeric;
  AdOC   varchar;
BEGIN
  --Florin 07.07.2025 - sinc. Oracle
  --Florin 20.09.2024 - fixat 63417
  --Stef 28.05.2024 - sinc. Oracle
  perform pkg_nomsubunit_setct_monitor('MON_7');
  IF  OPERATION = 0 THEN
    SELECT CODSUBUNIT INTO RECID FROM TMP_NSUBUNIT;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999'), current_setting('PKG_NOMSUBUNIT.CT_MONITOR', true)))
    THEN
      SELECT 'subunitate "' || coalesce(n.DEN_SUBUNIT,'') || '"'
      INTO aDoc
      FROM TMP_NSUBUNIT n
      WHERE
         N.CODSUBUNIT = RECID;
      PERFORM pkg_userfirme_postlogcucommit( 'NSUBUNIT', current_setting('PKG_GLOBALS.USERNAME', true), 'M', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), TO_NUMBER(current_setting('PKG_GLOBALS.SUBUNITATE', true),'999999999999999999'), null, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    UPDATE NSUBUNIT
    SET (        DEN_SUBUNIT, CIF, SATELITWM, ANPORNIRE, LUNAPORNIRE, NUMEPRESC, REGCOM, CODBANKCONT, CODBANKCONTTREZ, CODCATPRET, NoEconomicActiv, CODSIUI, CODCASA, CodPers, CAPITAL_SOCIAL, EFACT, TIPUNITJURIDICA ) =
        ( SELECT DEN_SUBUNIT, CIF, SATELITWM, ANPORNIRE, LUNAPORNIRE, NUMEPRESC, REGCOM, CODBANKCONT, CODBANKCONTTREZ, CODCATPRET, NoEconomicActiv, CODSIUI, CODCASA, CodPers, CAPITAL_SOCIAL, EFACT, TIPUNITJURIDICA FROM TMP_NSUBUNIT )
    WHERE CODSUBUNIT = RECID;

    DELETE FROM NAGENDA WHERE (CODSUBUNIT = RECID AND CODAGENDA NOT IN (SELECT CODAGENDA FROM TMP_NAGENDA WHERE COALESCE( CODAGENDA, 0) &lt;&gt; 0)) ;

    INSERT INTO NAGENDA(OBS, CODAGENDA, TIP, CODLOCALIT, SEDIUSOCIAL, TELEFON, FAX, EMAIL, SECTOR, STRADA, NR1, NR2, BLOC, SCARA, ETAJ, APART, CODPOSTAL, KM, CODBANKCONT, CODPART, CODGEST, CODSUBUNIT, GLN, LONGITUDINE, LATITUDINE, OBS2)
    SELECT OBS, NEXTVAL('SEQ_NAGENDA_CODAGENDA'), TIP, CODLOCALIT, SEDIUSOCIAL, TELEFON, FAX, EMAIL, SECTOR, STRADA, NR1, NR2, BLOC, SCARA, ETAJ, APART, CODPOSTAL, KM, CODBANKCONT, CODPART, CODGEST, RECID, GLN, LONGITUDINE, LATITUDINE, OBS2
    FROM TMP_NAGENDA WHERE CODAGENDA &lt; 0;

    FOR V_REC IN (SELECT * FROM TMP_NAGENDA WHERE COALESCE( CODAGENDA, -1) &gt; 0 ORDER BY CODAGENDA) LOOP
      SELECT COUNT( *) INTO VRECNO FROM NAGENDA WHERE CODAGENDA = COALESCE( V_REC.CODAGENDA, 0);

      IF (VRECNO = 1) THEN
        UPDATE NAGENDA
        SET
        OBS         = V_REC.OBS,
        TIP         = V_REC.TIP,
        CODLOCALIT  = V_REC.CODLOCALIT,
        SEDIUSOCIAL = V_REC.SEDIUSOCIAL,
        TELEFON     = V_REC.TELEFON,
        FAX         = V_REC.FAX,
        EMAIL       = V_REC.EMAIL,
        SECTOR      = V_REC.SECTOR,
        STRADA      = V_REC.STRADA,
        NR1         = V_REC.NR1,
        NR2         = V_REC.NR2,
        BLOC        = V_REC.BLOC,
        SCARA       = V_REC.SCARA,
        ETAJ        = V_REC.ETAJ,
        APART       = V_REC.APART,
        CODPOSTAL   = V_REC.CODPOSTAL,
        KM          = V_REC.KM,
        CODBANKCONT = V_REC.CODBANKCONT,
        CODPART     = V_REC.CODPART,
        CODGEST     = V_REC.CODGEST,
        CODSUBUNIT  = RECID,
        GLN         = V_REC.GLN,
        LONGITUDINE = V_REC.LONGITUDINE,
        LATITUDINE  = V_REC.LATITUDINE,
        OBS2        = V_REC.OBS2
        WHERE
         CODAGENDA = V_REC.CODAGENDA;
      END IF;
    END LOOP;

    DELETE FROM NSUBUNIT1 WHERE CODSUBUNIT = RECID AND CODSUBUNIT1 NOT IN (SELECT CODSUBUNIT1 FROM TMP_NSUBUNIT1);

    FOR V_REC IN (SELECT * FROM TMP_NSUBUNIT1 ORDER BY CODSUBUNIT1) LOOP
      IF (V_REC.CODSUBUNIT1 &gt; 0) THEN
        UPDATE NSUBUNIT1
        SET
        CODIOFILIAL      = V_REC.CODIOFILIAL,
        CODCATPRET       = V_REC.CODCATPRET,
        TVALAINCASARE    = V_REC.TVALAINCASARE,
        CAEN             = V_REC.CAEN,
        CodTVA           = V_REC.CodTVA,
        IsFirma          = V_REC.IsFirma,
        GrDeclaratie     = V_REC.Grdeclaratie,
        ModEditareJurnal = V_REC.ModEditareJurnal,
        PrelCantBCAR     = V_REC.PrelCantBCAR
        WHERE
         CODSUBUNIT1 = V_REC.CODSUBUNIT1;
      ELSE
        INSERT INTO NSUBUNIT1(CODSUBUNIT1, CODSUBUNIT, CODIOFILIAL, CODCATPRET, ANSTART, LUNASTART, TVALAINCASARE, CAEN, CODTVA, ISFIRMA, GRDECLARATIE, MODEDITAREJURNAL)
        VALUES(NEXTVAL('SEQ_NSUBUNIT1_CODSUBUNIT1'), RECID, V_REC.CODIOFILIAL, V_REC.CODCATPRET, V_REC.ANSTART, V_REC.LUNASTART, V_REC.TVALAINCASARE, V_REC.CAEN, V_REC.CODTVA, V_REC.ISFIRMA, V_REC.GRDECLARATIE, V_REC.MODEDITAREJURNAL);
      END IF;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_NSUBUNIT_CODSUBUNIT') INTO RECID;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999'), current_setting('PKG_NOMSUBUNIT.CT_MONITOR', true)))
    THEN
      SELECT 'subunitate "' || coalesce(n.DEN_SUBUNIT,'') || '"'
      INTO aDoc
      FROM TMP_NSUBUNIT n;
      PERFORM pkg_userfirme_postlogcucommit( 'NSUBUNIT', current_setting('PKG_GLOBALS.USERNAME', true), 'A', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), TO_NUMBER(current_setting('PKG_GLOBALS.SUBUNITATE', true),'999999999999999999'), null, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    INSERT INTO  NSUBUNIT (
      CODSUBUNIT,DEN_SUBUNIT, CIF, SATELITWM, ANPORNIRE, LUNAPORNIRE, NUMEPRESC, REGCOM, CODBANKCONT, CODBANKCONTTREZ, CODCATPRET, NoEconomicActiv, CODSIUI, CODCASA, CodPers, CAPITAL_SOCIAL, EFACT, TIPUNITJURIDICA )
    SELECT
      RECID,     DEN_SUBUNIT, CIF, SATELITWM, ANPORNIRE, LUNAPORNIRE, NUMEPRESC, REGCOM, CODBANKCONT, CODBANKCONTTREZ, CODCATPRET, NoEconomicActiv, CODSIUI, CODCASA, CodPers, CAPITAL_SOCIAL, EFACT, TIPUNITJURIDICA
    FROM TMP_NSUBUNIT;

    INSERT INTO NAGENDA(OBS, CODAGENDA, TIP, CODLOCALIT, SEDIUSOCIAL, TELEFON, FAX, EMAIL, SECTOR, STRADA, NR1, NR2, BLOC, SCARA, ETAJ, APART, CODPOSTAL, KM, CODBANKCONT, CODPART, CODGEST, CODSUBUNIT, GLN, LONGITUDINE, LATITUDINE, OBS2)
    SELECT OBS, NEXTVAL('SEQ_NAGENDA_CODAGENDA'), TIP, CODLOCALIT, SEDIUSOCIAL, TELEFON, FAX, EMAIL, SECTOR, STRADA, NR1, NR2, BLOC, SCARA, ETAJ, APART, CODPOSTAL, KM, CODBANKCONT, CODPART, CODGEST, RECID, GLN, LONGITUDINE, LATITUDINE, OBS2
    FROM TMP_NAGENDA;

    INSERT INTO NSUBUNIT1(CODSUBUNIT1, CODSUBUNIT, CODIOFILIAL, CODCATPRET, CAEN, IsFirma, GrDeclaratie, CodTVA, ANSTART, LUNASTART, PRELCANTBCAR)
    SELECT NEXTVAL('SEQ_NSUBUNIT1_CODSUBUNIT1'), RECID, CODIOFILIAL, CODCATPRET, CAEN, IsFirma, GrDeclaratie, CodTVA, ANSTART, LUNASTART, PRELCANTBCAR
    FROM TMP_NSUBUNIT1;
  END IF;

  CALL PRC_AL_REFRESH('nsubunit1', RECID);
  PERFORM NotifyModif( OPERATION, RECID, 'NSUBUNIT');

  FOR V_REC IN (SELECT A.CODARTICOL FROM NART A WHERE NOT EXISTS (SELECT CODARTICOL FROM NARTIMPLICITE WHERE CODARTICOL = A.CODARTICOL AND  codsubunit = RECID))
  LOOP
    INSERT INTO NARTIMPLICITE(CODIMPLICIT, CODARTICOL, CODSUBUNIT)
    VALUES(NEXTVAL('SEQ_NARTIMPLICITE_CODIMPLICIT'), V_REC.CODARTICOL, RECID);
  END LOOP;

  FOR V_REC IN (SELECT O.CODOBIECT FROM NARTOBJ O WHERE NOT EXISTS (SELECT CODOBIECT FROM NARTOBJIMP WHERE CODOBIECT = O.CODOBIECT AND  codsubunit = RECID))
  LOOP
    INSERT INTO NARTOBJIMP(CODOBJIMP, CODOBIECT, CODSUBUNIT)
    VALUES(NEXTVAL('SEQ_NARTOBJIMP_CODOBJIMP'), V_REC.CODOBIECT, RECID);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nomtva_sp_lockrecord</obj_name>
  <obj_hashval>4694a0a8b1ddadcf5de6b0ccf440adb5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nomtva_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodTva INTO Tmp FROM NTVA WHERE CodTva = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_kartdiscaccant</obj_name>
  <obj_hashval>a2149f6cc4db8c7d97d758769d5ccd17</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_kartdiscaccant(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_NOTECREDIT.KArtDiscAcCant', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_notecredit_setkartdiscprimvol</obj_name>
  <obj_hashval>183bcacb5764814c22309f1a84d6cc99</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_notecredit_setkartdiscprimvol(akartdiscprimvol numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_NOTECREDIT.KArtDiscPrimVol',aKArtDiscPrimVol::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_npartretail_do_post_newpart_onbaza</obj_name>
  <obj_hashval>9c93404ece0816e0893108983c016bd2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_npartretail_do_post_newpart_onbaza()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  V_REC_D RECORD;
  aANINI           numeric;
  aLUNAINI         numeric;
  CODNOUPART       numeric;
  CODNOUAGENDA     numeric;
  COD_CODFISCALNOU numeric;
  CODPARTDISCNOU   numeric;
  CODPARTTRNOU     numeric;
  CODPARTBNOU      numeric;
  aCODLOCALIT      numeric;
  aCODBANCA        numeric;
  aCODIO           numeric;
BEGIN
  --Florin 07.11.2025 - fixat 67188
  --Florin 02.10.2025 - sinc. Oracle
  --Florin 18.11.2022 - sinc. Oracle
  --Adina 13.03.2021 - alstart, alstop
  --Bogdan 23.02.2021
  BEGIN
    SELECT ANINITIAL, LUNAINITIALA INTO aANINI, aLUNAINI FROM FIRMALUNI;
  EXCEPTION
  WHEN OTHERS THEN
    aANINI   := 0;
    aLUNAINI := 0;
  END;

  FOR V_REC IN (SELECT * FROM TMP_NPARTRETAIL) LOOP
    CODNOUPART := NEXTVAL ('SEQ_NPART_CODPART');
    INSERT INTO NPART (CODPART, DEN_PART, REGCOM, CODEXTERN,
        CODINTERN, COLDISCOUNT, CODCLASA, FIDELIZARE,
        DATANASTERE, BLOCAT, INFOBLOCAT, CODCATEGPRET, PERSOANAFIZICA,
        OBS, DATAADAUGARII)
      VALUES (CODNOUPART, V_REC.DENUMIRE, V_REC.REGCOM, V_REC.CODEXTERN,
        V_REC.CODINTERN, V_REC.COLDISCOUNT, V_REC.CODCLASA, V_REC.FIDELIZARE,
        V_REC.DATANASTERE, V_REC.BLOCAT, V_REC.INFOBLOCAT, V_REC.CODCATEGPRET, V_REC.TIPPART,
        V_REC.OBS, V_REC.DATACREARE);

    perform NotifyModif(-11, CODNOUPART, 'NPART');

    aCODIO := fnc_GetValConstanta('IOPARTPJ', getanlucru(), getlunalucru())::numeric;

    IF V_REC.TIPPART = 1 THEN
      aCODIO := COALESCE ( fnc_GetValConstanta ('IOPARTPF', getanlucru(), getlunalucru())::numeric
                         , fnc_GetValConstanta ('IOPARTPJ', getanlucru(), getlunalucru())::numeric);
    END IF;

    INSERT INTO NPART1 (CODPART1, CODPART, CODIOPART, ANSTART, LUNASTART, ALSTART, ALSTOP)
    VALUES (NEXTVAL ('SEQ_NPART1_CODPART1') , CODNOUPART, aCODIO, aANINI, aLUNAINI, 0, 99999);

    INSERT INTO NPART1CRM (CODPART1CRM, CODPART, ANSTART, LUNASTART, ALSTART, ALSTOP)
    VALUES (NEXTVAL ('SEQ_NPART1CRM_CODPART1CRM') , CODNOUPART, aANINI, aLUNAINI, 0, 99999);

    UPDATE TMP_NPARTRETAIL
    SET CODPART = CODNOUPART
    WHERE
      CODPARTRETAIL = V_REC.CODPARTRETAIL;

    FOR V_REC_D IN (SELECT * FROM TMP_NSEDIIPARTRETAIL D WHERE D.CODPARTRETAIL = V_REC.CODPARTRETAIL) LOOP
      CODNOUAGENDA := NEXTVAL ('SEQ_NAGENDA_CODAGENDA');
      aCODLOCALIT  := (SELECT PKG_NPARTRETAIL_GET_COD_LOCALIT.WME_RESULT
                       FROM PKG_NPARTRETAIL_GET_COD_LOCALIT (NULL, V_REC_D.CODLOCALIT, V_REC_D.DENLOCALIT, V_REC_D.CODJUDET::varchar, V_REC_D.CODTARA::varchar));
      INSERT INTO NAGENDA (CODAGENDA, TIP, CODLOCALIT, SEDIUSOCIAL,
          TELEFON, FAX, EMAIL, SECTOR,
          STRADA, NR1, NR2, BLOC,
          SCARA, ETAJ, APART, CODPOSTAL,
          OBS, CODPART)
        VALUES (CODNOUAGENDA, 0, aCODLOCALIT, V_REC_D.SEDIUSOCIAL,
          V_REC_D.TELEFON, V_REC_D.FAX, V_REC_D.EMAIL, V_REC_D.SECTOR,
          V_REC_D.STRADA, V_REC_D.NR1, V_REC_D.NR2, V_REC_D.BLOC,
          V_REC_D.SCARA, V_REC_D.ETAJ, V_REC_D.APART, V_REC_D.CODPOSTAL,
          V_REC_D.DENUMIRE, CODNOUPART);

      UPDATE TMP_NSEDIIPARTRETAIL
      SET CODAGENDA = CODNOUAGENDA, CODLOCALIT = aCODLOCALIT
      WHERE
        CODSEDIU = V_REC_D.CODSEDIU;
    END LOOP;

    FOR V_REC_D IN (SELECT * FROM TMP_NCODFISCRETAIL D WHERE D.CODPARTRETAIL = V_REC.CODPARTRETAIL) LOOP
      COD_CODFISCALNOU := NEXTVAL ('SEQ_NPARTCODFISC_COD_CODFISCAL');
      INSERT INTO NPARTCODFISC (COD_CODFISCAL, CODPART, CODFISCAL, PRINCIPAL)
        VALUES (COD_CODFISCALNOU, CODNOUPART, V_REC_D.CODFISCAL, V_REC_D.PRINCIPAL);

      UPDATE TMP_NCODFISCRETAIL
      SET COD_CODFISCAL = COD_CODFISCALNOU
      WHERE
        COD = V_REC_D.COD;
    END LOOP;

    FOR V_REC_D IN (SELECT * FROM TMP_NPARTDISCRETAIL D WHERE D.CODPARTRETAIL = V_REC.CODPARTRETAIL) LOOP
      CODPARTDISCNOU := NEXTVAL ('SEQ_NPARTDISC_CODPARTDISC');
      INSERT INTO NPARTDISC (CODPARTDISC, CODPART, CODCATEGDISC, INDEXLOCAL)
      VALUES (CODPARTDISCNOU, CODNOUPART, V_REC_D.CODCATEGDISC, V_REC_D.INDEXLOCAL);

      UPDATE TMP_NPARTDISCRETAIL
      SET CODPARTDISC = CODPARTDISCNOU
      WHERE
        COD = V_REC_D.COD;
    END LOOP;

    FOR V_REC_D IN (SELECT * FROM TMP_NDELEGATRETAIL D WHERE D.CODPARTRETAIL = V_REC.CODPARTRETAIL) LOOP
      CODPARTTRNOU := NEXTVAL ('SEQ_NPARTTR_CODPARTTR');
      INSERT INTO NPARTTR (CODPARTTR, CODPART, DELEGAT, CNP,
          DOC, SERIEDOC, NRDOC, ELIBERAT,
          MIJLTRANSP, NRTRANSP, ACTIV, DATADOC,
          IMPLICIT, OBS)
        VALUES (CODPARTTRNOU, CODNOUPART, V_REC_D.DELEGAT, V_REC_D.CNP,
          V_REC_D.DOC, V_REC_D.SERIEDOC, V_REC_D.NRDOC, V_REC_D.ELIBERAT,
          V_REC_D.MIJLTRANSP, V_REC_D.NRTRANSP, V_REC_D.ACTIV, V_REC_D.DATADOC,
          V_REC_D.IMPLICIT, V_REC_D.OBS);

      UPDATE TMP_NDELEGATRETAIL
      SET CODPARTTR = CODPARTTRNOU
      WHERE
        COD = V_REC_D.COD;
    END LOOP;

    FOR V_REC_D IN (SELECT * FROM TMP_NBANCIRETAIL D WHERE D.CODPARTRETAIL = V_REC.CODPARTRETAIL) LOOP
      CODPARTBNOU := NEXTVAL ('SEQ_NPARTB_CODPARTB');
      aCODLOCALIT := (SELECT PKG_NPARTRETAIL_GET_COD_LOCALIT.WME_RESULT
                      FROM PKG_NPARTRETAIL_GET_COD_LOCALIT (NULL, V_REC_D.CODLOCALIT, V_REC_D.DENLOCALIT, V_REC_D.CODJUDET::varchar, V_REC_D.CODTARA::varchar));
      aCODBANCA := (select WME_RESULT from PKG_NPARTRETAIL_GET_COD_BANCA  (null,V_REC_D.CODBANK, V_REC_D.DENBANCA));
      INSERT INTO NPARTB (CODPARTB, CODPART, CODBANK, IMPLICIT,
          CODLOCALIT, CONTBANCA, SUCURSALA, CODMONEDA)
      VALUES (CODPARTBNOU, CODNOUPART, aCODBANCA, V_REC_D.IMPLICIT,
          aCODLOCALIT, V_REC_D.CONTBANCA, V_REC_D.SUCURSALA, V_REC_D.CODMONEDA);

      UPDATE TMP_NBANCIRETAIL
      SET CODPARTB = CODPARTBNOU, CODLOCALIT = aCODLOCALIT, CODBANK = aCODBANCA
      WHERE
        COD = V_REC_D.COD;
    END LOOP;

  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_npartretail_make_partretail_from_npart</obj_name>
  <obj_hashval>541c51521fad179d2b2c7e8802d21a53</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_npartretail_make_partretail_from_npart()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
  DECLARE
    V_REC RECORD;
    V_REC_R RECORD;
    P RECORD;
    SP RECORD;
    CFP RECORD;
    PDB RECORD;
    DB RECORD;
    BB RECORD;
    NR             numeric;
    aCODIOPART     numeric;
    aCOD           numeric;
    aCODPARTRETAIL numeric;
  BEGIN
    --Florin 05.11.2024 - sinc. Oracle
    --Florin 18.11.2022 - sinc. Oracle
    FOR V_REC IN (SELECT CODPART, COUNT (*) AS NR FROM NPARTRETAIL GROUP BY CODPART) LOOP
      SELECT MIN (CODPARTRETAIL) INTO aCODPARTRETAIL FROM NPARTRETAIL WHERE CODPART = V_REC.CODPART;

      FOR V_REC_R IN (SELECT * FROM NPARTRETAIL WHERE CODPART = V_REC.CODPART AND CODPARTRETAIL &lt;&gt; aCODPARTRETAIL)
      LOOP
        UPDATE IESIRIRETAIL SET CODPARTRETAIL = aCODPARTRETAIL      WHERE CODPARTRETAIL = V_REC_R.CODPARTRETAIL;
        UPDATE EMULARE      SET CODPARTRETAIL = aCODPARTRETAIL      WHERE CODPARTRETAIL = V_REC_R.CODPARTRETAIL;
        UPDATE RESTNP       SET CODPARTRETAIL = aCODPARTRETAIL      WHERE CODPARTRETAIL = V_REC_R.CODPARTRETAIL;
        UPDATE EMULARE      SET CODPARTRETAILCOMIS = aCODPARTRETAIL WHERE CODPARTRETAILCOMIS = V_REC_R.CODPARTRETAIL;

        DELETE FROM NCODFISCRETAIL   WHERE CODPARTRETAIL = V_REC_R.CODPARTRETAIL;
        DELETE FROM NSEDIIPARTRETAIL WHERE CODPARTRETAIL = V_REC_R.CODPARTRETAIL;
        DELETE FROM NBANCIRETAIL     WHERE CODPARTRETAIL = V_REC_R.CODPARTRETAIL;
        DELETE FROM NDELEGATRETAIL   WHERE CODPARTRETAIL = V_REC_R.CODPARTRETAIL;
        DELETE FROM NPARTDISCRETAIL  WHERE CODPARTRETAIL = V_REC_R.CODPARTRETAIL;
        DELETE FROM NPARTRETAIL      WHERE CODPARTRETAIL = V_REC_R.CODPARTRETAIL;
      END LOOP;
    END LOOP;

    FOR P IN (SELECT * FROM NPART WHERE CODPART &gt; 0) LOOP
      UPDATE NPARTRETAIL PR
      SET
        DENUMIRE    = P.DEN_PART,
        REGCOM      = P.REGCOM,
        OBS         = P.OBS,
        CODEXTERN   = P.CODEXTERN,
        CODINTERN   = P.CODINTERN,
        TIPPART     = COALESCE (P.PERSOANAFIZICA, 0) ,
        COLDISCOUNT = P.COLDISCOUNT,
        CODCLASA    = P.CODCLASA,
        BLOCAT      = P.BLOCAT,
        INFOBLOCAT  = P.INFOBLOCAT,
        CODCATEGPRET = P.CODCATEGPRET
      WHERE
        PR.CODPART = P.CODPART;

      IF NOT FOUND THEN
        INSERT INTO NPARTRETAIL AS PR (CODPARTRETAIL, CODPART, DENUMIRE, REGCOM,
            OBS, CODEXTERN, CODINTERN, TIPPART,
            COLDISCOUNT, CODCLASA, FIDELIZARE, DATANASTERE,
            BLOCAT, INFOBLOCAT, CODCATEGPRET)
        VALUES (NEXTVAL ('SEQ_NPARTRETAIL_CODPARTRETAIL') , P.CODPART, P.DEN_PART, P.REGCOM,
            P.OBS, P.CODEXTERN, P.CODINTERN, COALESCE (P.PERSOANAFIZICA, 0) ,
            P.COLDISCOUNT, P.CODCLASA, P.FIDELIZARE, P.DATANASTERE,
            P.BLOCAT, P.INFOBLOCAT, P.CODCATEGPRET);
      END IF;
    END LOOP;

    SELECT COUNT (*) INTO NR FROM NPARTRETAIL WHERE CODPARTRETAIL = 0;

    IF NR = 0 THEN
      INSERT INTO NPARTRETAIL (CODPARTRETAIL, CODPART, DENUMIRE)
      VALUES (0, 0, '... nedefinit ...');
    END IF;

    FOR SP IN (SELECT A.*, PR.CODPARTRETAIL, L.DEN_LOCALIT, L.CODJUDET, L.CODTARA, PR.TIPMODIF
               FROM NAGENDA A LEFT JOIN NLOCALIT L ON A.CODLOCALIT = L.CODLOCALIT, NPARTRETAIL PR
               WHERE PR.CODPART = A.CODPART
              )
    LOOP
      UPDATE NSEDIIPARTRETAIL SR
      SET
        DENUMIRE    = SP.OBS,
        CODLOCALIT  = SP.CODLOCALIT,
        DENLOCALIT  = SP.DEN_LOCALIT,
        CODJUDET    = SP.CODJUDET,
        CODTARA     = SP.CODTARA,
        TELEFON     = SP.TELEFON,
        FAX         = SP.FAX,
        EMAIL       = SP.EMAIL,
        STRADA      = SP.STRADA,
        NR1         = SP.NR1,
        NR2         = SP.NR2,
        BLOC        = SP.BLOC,
        SCARA       = SP.SCARA,
        ETAJ        = SP.ETAJ,
        APART       = SP.APART,
        SECTOR      = SP.SECTOR,
        CODPOSTAL   = SP.CODPOSTAL,
        SEDIUSOCIAL = SP.SEDIUSOCIAL
      WHERE
        SP.CODAGENDA = SR.CODAGENDA;

      IF NOT FOUND THEN
        INSERT INTO NSEDIIPARTRETAIL AS SR (CODSEDIU, CODPARTRETAIL, DENUMIRE, CODLOCALIT,
            DENLOCALIT, CODJUDET, CODTARA, TELEFON,
            FAX, EMAIL, STRADA, NR1,
            NR2, BLOC, SCARA, ETAJ,
            APART, SECTOR, CODPOSTAL, SEDIUSOCIAL,
            CODAGENDA)
        VALUES (NEXTVAL ('SEQ_NSEDIIPARTRETAIL_CODSEDIU') , SP.CODPARTRETAIL, SP.OBS, SP.CODLOCALIT,
            SP.DEN_LOCALIT, SP.CODJUDET, SP.CODTARA, SP.TELEFON,
            SP.FAX, SP.EMAIL, SP.STRADA, SP.NR1,
            SP.NR2, SP.BLOC, SP.SCARA, SP.ETAJ,
            SP.APART, SP.SECTOR, SP.CODPOSTAL, SP.SEDIUSOCIAL,
            SP.CODAGENDA);
      END IF;
    END LOOP;

    FOR CFP IN (SELECT CF.*, PR.CODPARTRETAIL, PR.TIPMODIF FROM NPARTCODFISC CF, NPARTRETAIL PR WHERE CF.CODPART = PR.CODPART)
    LOOP
      UPDATE NCODFISCRETAIL CFR
      SET CODFISCAL = CFP.CODFISCAL, PRINCIPAL = CFP.PRINCIPAL
      WHERE
        CFR.COD_CODFISCAL = CFP.COD_CODFISCAL;

      IF NOT FOUND THEN
        INSERT INTO NCODFISCRETAIL AS CFR (COD, CODPARTRETAIL, CODFISCAL, PRINCIPAL,
            COD_CODFISCAL)
        VALUES (NEXTVAL ('SEQ_NCODFISCRETAIL_COD') , CFP.CODPARTRETAIL, CFP.CODFISCAL, CFP.PRINCIPAL,
            CFP.COD_CODFISCAL);
      END IF;
    END LOOP;

    FOR PDB IN (SELECT PD.*, PR.CODPARTRETAIL, PR.TIPMODIF FROM NPARTDISC PD, NPARTRETAIL PR WHERE PD.CODPART = PR.CODPART)
    LOOP
      UPDATE NPARTDISCRETAIL PDR
      SET CODCATEGDISC = PDB.CODCATEGDISC
      WHERE
        PDR.CODPARTDISC = PDB.CODPARTDISC;

      IF NOT FOUND THEN
        INSERT INTO NPARTDISCRETAIL AS PDR (COD, CODPARTRETAIL, CODCATEGDISC, INDEXLOCAL,
            CODPARTDISC)
        VALUES (NEXTVAL ('SEQ_NPARTDISCRETAIL_COD') , PDB.CODPARTRETAIL, PDB.CODCATEGDISC, PDB.INDEXLOCAL,
            PDB.CODPARTDISC);
      END IF;
    END LOOP;

    FOR V_REC IN (SELECT PDR.COD, PR.CODPART, PDR.CODCATEGDISC FROM NPARTDISCRETAIL PDR, NPARTRETAIL PR WHERE PDR.CODPARTRETAIL = PR.CODPARTRETAIL)
    LOOP
      SELECT COUNT (*) INTO NR FROM NPARTDISC WHERE CODPART = V_REC.CODPART AND CODCATEGDISC = V_REC.CODCATEGDISC;

      IF NR = 0 THEN
        DELETE FROM NPARTDISCRETAIL WHERE COD = V_REC.COD;
      END IF;
    END LOOP;

    FOR DB IN (SELECT PT.*, PR.CODPARTRETAIL, PR.TIPMODIF
               FROM NPARTTR PT, NPARTRETAIL PR
               WHERE PT.CODPART = PR.CODPART
              )
    LOOP
      UPDATE NDELEGATRETAIL DR
      SET DELEGAT = DB.DELEGAT, CNP = DB.CNP, DOC = DB.DOC, SERIEDOC = DB.SERIEDOC,
        NRDOC = DB.NRDOC, ELIBERAT = DB.ELIBERAT, MIJLTRANSP = DB.MIJLTRANSP, NRTRANSP = DB.NRTRANSP,
        ACTIV = DB.ACTIV, DATADOC = DB.DATADOC, IMPLICIT = DB.IMPLICIT, OBS = DB.OBS
      WHERE
        DR.CODPARTTR = DB.CODPARTTR;

      IF NOT FOUND THEN
        INSERT INTO NDELEGATRETAIL AS DR (COD, CODPARTRETAIL, DELEGAT, CNP,
            DOC, SERIEDOC, NRDOC, ELIBERAT,
            MIJLTRANSP, NRTRANSP, ACTIV, DATADOC,
            IMPLICIT, OBS, CODPARTTR)
        VALUES (NEXTVAL ('SEQ_NDELEGATRETAIL_COD') , DB.CODPARTRETAIL, DB.DELEGAT, DB.CNP,
            DB.DOC, DB.SERIEDOC, DB.NRDOC, DB.ELIBERAT,
            DB.MIJLTRANSP, DB.NRTRANSP, DB.ACTIV, DB.DATADOC,
            DB.IMPLICIT, DB.OBS, DB.CODPARTTR);
      END IF;
    END LOOP;

    FOR BB IN (SELECT PB.*, PR.CODPARTRETAIL, L.DEN_LOCALIT AS DENLOCALIT, L.CODJUDET, L.CODTARA, K.DENUMIRE                              AS DENBANCA, PR.TIPMODIF
               FROM NPARTB             PB
                    LEFT JOIN NLOCALIT L ON L.CODLOCALIT = PB.CODLOCALIT
                    LEFT JOIN NBANK    K ON K.CODBANK = PB.CODBANK, NPARTRETAIL PR
               WHERE PB.CODPART = PR.CODPART)
    LOOP
      UPDATE NBANCIRETAIL BR
      SET
        CODBANK    = BB.CODBANK,
        IMPLICIT   = BB.IMPLICIT,
        CODLOCALIT = BB.CODLOCALIT,
        CONTBANCA  = BB.CONTBANCA,
        SUCURSALA  = BB.SUCURSALA,
        CODMONEDA  = BB.CODMONEDA,
        DENBANCA   = BB.DENBANCA,
        DENLOCALIT = BB.DENLOCALIT,
        CODJUDET   = BB.CODJUDET,
        CODTARA    = BB.CODTARA
      WHERE
        BR.CODPARTB = BB.CODPARTB;

      IF NOT FOUND THEN
        INSERT INTO NBANCIRETAIL AS BR (COD, CODPARTRETAIL, CODBANK, IMPLICIT,
            CODLOCALIT, CONTBANCA, SUCURSALA, CODMONEDA,
            DENBANCA, DENLOCALIT, CODPARTB, CODJUDET,
            CODTARA)
        VALUES (NEXTVAL ('SEQ_NBANCIRETAIL_COD') , BB.CODPARTRETAIL, BB.CODBANK, BB.IMPLICIT,
            BB.CODLOCALIT, BB.CONTBANCA, BB.SUCURSALA, BB.CODMONEDA,
            BB.DENBANCA, BB.DENLOCALIT, BB.CODPARTB, BB.CODJUDET,
            BB.CODTARA);
      END IF;
    END LOOP;

    UPDATE EMULARE E
    SET CODPARTRETAIL = (SELECT CODPARTRETAIL FROM NPARTRETAIL WHERE CODPART = E.CODPART limit 1 )
    WHERE
      COALESCE (CODPART, 0) &lt;&gt; 0;

    UPDATE RESTNP NP
    SET
        CODPARTRETAIL = (SELECT CODPARTRETAIL FROM NPARTRETAIL WHERE CODPART = NP.CODPART LIMIT 1)
    WHERE
       NVL(CODPART, 0) &lt;&gt; 0;

    UPDATE EMULARERETAIL E
    SET CODSEDIURETAIL = (SELECT CODSEDIU FROM NSEDIIPARTRETAIL SR WHERE SR.CODAGENDA = E.CODLOCATIE)
    WHERE
      COALESCE (E.CODLOCATIE, 0) &lt;&gt; 0;

    UPDATE IESIRIRETAIL I
    SET CODPARTRETAIL = (SELECT CODPARTRETAIL FROM NPARTRETAIL WHERE CODPART = I.PARTENER LIMIT 1)
    WHERE
      COALESCE (PARTENER, 0) &lt;&gt; 0;

    UPDATE IESIRIRETAIL I
    SET CODSEDIURETAIL = (SELECT CODSEDIU FROM NSEDIIPARTRETAIL SR WHERE SR.CODAGENDA = I.CODLOCATIE)
    WHERE
      COALESCE (CODLOCATIE, 0) &lt;&gt; 0;

    UPDATE IESIRIRETAIL I
    SET DELEGATRETAIL = (SELECT COD FROM NDELEGATRETAIL DR WHERE DR.CODPARTTR = I.DELEGAT)
    WHERE
      COALESCE (DELEGAT, 0) &lt;&gt; 0;

    UPDATE IESIRIRETAIL I
    SET CODFISCALRETAIL = (SELECT COD FROM NCODFISCRETAIL FR WHERE FR.COD_CODFISCAL = I.CODFISCAL)
    WHERE
      COALESCE (I.CODFISCAL, 0) &lt;&gt; 0;
  end;
  $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_npartretail_make_partretail_from_tmpnpart</obj_name>
  <obj_hashval>5bd3f7080db4d36d097298c93308ea2f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_npartretail_make_partretail_from_tmpnpart()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  VREC RECORD;
--  P   RECORD;
  SP  RECORD;
  CFP RECORD;
  PDB RECORD;
  DB  RECORD;
  BB  RECORD;
  NR         numeric;
  aCODIOPART numeric;
  aCOD       numeric;
BEGIN
  --Florin 18.11.2022 - sinc. Oracle
  --Florin 14.11.2022 - sinc. Oracle
  FOR VREC IN (SELECT P.* FROM NPART P, TMP_NPART TP WHERE P.CODPART = TP.CODPART) LOOP
    UPDATE  NPARTRETAIL PR
     SET
       DENUMIRE = VREC.DEN_PART,
       REGCOM = VREC.REGCOM,
       OBS = VREC.OBS,
       CODEXTERN = VREC.CODEXTERN,
       CODINTERN = VREC.CODINTERN,
       TIPPART = COALESCE( VREC.PERSOANAFIZICA, 0),
       COLDISCOUNT = VREC.COLDISCOUNT,
       CODCLASA = VREC.CODCLASA,
       BLOCAT = VREC.BLOCAT,
       INFOBLOCAT = VREC.INFOBLOCAT,
       CODCATEGPRET  = VREC.CODCATEGPRET
    WHERE
     PR.CODPART = VREC.CODPART;

    IF NOT FOUND THEN
      INSERT INTO NPARTRETAIL(CODPARTRETAIL, CODPART, DENUMIRE, REGCOM, OBS, CODEXTERN, CODINTERN, TIPPART, COLDISCOUNT, CODCLASA, FIDELIZARE, DATANASTERE, BLOCAT, INFOBLOCAT, CODCATEGPRET)
      VALUES (NEXTVAL('SEQ_NPARTRETAIL_CODPARTRETAIL'), VREC.CODPART, VREC.DEN_PART, VREC.REGCOM, VREC.OBS, VREC.CODEXTERN, VREC.CODINTERN, COALESCE( VREC.PERSOANAFIZICA, 0), VREC.COLDISCOUNT, VREC.CODCLASA, VREC.FIDELIZARE, VREC.DATANASTERE, VREC.BLOCAT, VREC.INFOBLOCAT, VREC.CODCATEGPRET) ;
    END IF;
  END LOOP;

  FOR SP IN (SELECT A.*, PR.CODPARTRETAIL, L.DEN_LOCALIT, L.CODJUDET, L.CODTARA, PR.TIPMODIF
             FROM NAGENDA A
                  LEFT JOIN NLOCALIT L ON  A.CODLOCALIT = L.CODLOCALIT, NPARTRETAIL PR, TMP_NPART TP
             WHERE TP.CODPART = PR.CODPART AND  PR.CODPART = A.CODPART
            )
  LOOP
    UPDATE  NSEDIIPARTRETAIL SR
     SET DENUMIRE = SP.OBS, CODLOCALIT = SP.CODLOCALIT, DENLOCALIT = SP.DEN_LOCALIT, CODJUDET = SP.CODJUDET, CODTARA = SP.CODTARA, TELEFON = SP.TELEFON, FAX = SP.FAX, EMAIL = SP.EMAIL, STRADA = SP.STRADA, NR1 = SP.NR1, NR2 = SP.NR2, BLOC = SP.BLOC, SCARA = SP.SCARA, ETAJ = SP.ETAJ, APART = SP.APART, SECTOR = SP.SECTOR, CODPOSTAL = SP.CODPOSTAL, SEDIUSOCIAL = SP.SEDIUSOCIAL
    WHERE
     SP.CODAGENDA = SR.CODAGENDA;

    IF NOT FOUND THEN
      INSERT INTO NSEDIIPARTRETAIL(CODSEDIU, CODPARTRETAIL, DENUMIRE, CODLOCALIT, DENLOCALIT, CODJUDET, CODTARA, TELEFON, FAX, EMAIL, STRADA, NR1, NR2, BLOC, SCARA, ETAJ, APART, SECTOR, CODPOSTAL, SEDIUSOCIAL, CODAGENDA)
      VALUES (NEXTVAL('SEQ_NSEDIIPARTRETAIL_CODSEDIU'), SP.CODPARTRETAIL, SP.OBS, SP.CODLOCALIT, SP.DEN_LOCALIT, SP.CODJUDET, SP.CODTARA, SP.TELEFON, SP.FAX, SP.EMAIL, SP.STRADA, SP.NR1, SP.NR2, SP.BLOC, SP.SCARA, SP.ETAJ, SP.APART, SP.SECTOR, SP.CODPOSTAL, SP.SEDIUSOCIAL, SP.CODAGENDA) ;
    END IF;
  END LOOP;

  FOR CFP IN (SELECT CF.*, PR.CODPARTRETAIL, PR.TIPMODIF
              FROM NPARTCODFISC CF, NPARTRETAIL PR, TMP_NPART TP
              WHERE TP.CODPART = PR.CODPART AND  CF.CODPART = PR.CODPART
             )
  LOOP
    UPDATE  NCODFISCRETAIL CFR
     SET CODFISCAL = CFP.CODFISCAL, PRINCIPAL = CFP.PRINCIPAL
    WHERE
     CFR.COD_CODFISCAL = CFP.COD_CODFISCAL;

    IF NOT FOUND THEN
      INSERT INTO NCODFISCRETAIL(COD, CODPARTRETAIL, CODFISCAL, PRINCIPAL, COD_CODFISCAL)
      VALUES (NEXTVAL('SEQ_NCODFISCRETAIL_COD'), CFP.CODPARTRETAIL, CFP.CODFISCAL, CFP.PRINCIPAL, CFP.COD_CODFISCAL) ;
    END IF;
  END LOOP;

  FOR PDB IN (SELECT PD.*, PR.CODPARTRETAIL, PR.TIPMODIF
              FROM NPARTDISC PD, NPARTRETAIL PR, TMP_NPART TP
              WHERE PR.CODPART = TP.CODPART AND  PD.CODPART = PR.CODPART
             )
  LOOP
    UPDATE  NPARTDISCRETAIL PDR
     SET CODCATEGDISC = PDB.CODCATEGDISC
    WHERE
     PDR.CODPARTDISC = PDB.CODPARTDISC;

    IF NOT FOUND THEN
      INSERT INTO NPARTDISCRETAIL(COD, CODPARTRETAIL, CODCATEGDISC, INDEXLOCAL, CODPARTDISC)
      VALUES (NEXTVAL('SEQ_NPARTDISCRETAIL_COD'), PDB.CODPARTRETAIL, PDB.CODCATEGDISC, PDB.INDEXLOCAL, PDB.CODPARTDISC) ;
    END IF;
  END LOOP;

  DELETE FROM NPARTDISCRETAIL
  WHERE
      CODPARTDISC NOT IN (SELECT CODPARTDISC FROM NPARTDISC);

  FOR DB IN (SELECT PT.*, PR.CODPARTRETAIL, PR.TIPMODIF
             FROM NPARTTR PT, NPARTRETAIL PR, TMP_NPART TP
             WHERE TP.CODPART = PR.CODPART AND  PT.CODPART = PR.CODPART
            )
  LOOP
    UPDATE  NDELEGATRETAIL DR
     SET DELEGAT = DB.DELEGAT, CNP = DB.CNP, DOC = DB.DOC, SERIEDOC = DB.SERIEDOC, NRDOC = DB.NRDOC, ELIBERAT = DB.ELIBERAT, MIJLTRANSP = DB.MIJLTRANSP, NRTRANSP = DB.NRTRANSP, ACTIV = DB.ACTIV, DATADOC = DB.DATADOC, IMPLICIT = DB.IMPLICIT, OBS = DB.OBS
    WHERE
     DR.CODPARTTR = DB.CODPARTTR;

    IF NOT FOUND THEN
      INSERT INTO NDELEGATRETAIL(COD, CODPARTRETAIL, DELEGAT, CNP, DOC, SERIEDOC, NRDOC, ELIBERAT, MIJLTRANSP, NRTRANSP, ACTIV, DATADOC, IMPLICIT, OBS, CODPARTTR)
      VALUES (NEXTVAL('SEQ_NDELEGATRETAIL_COD'), DB.CODPARTRETAIL, DB.DELEGAT, DB.CNP, DB.DOC, DB.SERIEDOC, DB.NRDOC, DB.ELIBERAT, DB.MIJLTRANSP, DB.NRTRANSP, DB.ACTIV, DB.DATADOC, DB.IMPLICIT, DB.OBS, DB.CODPARTTR) ;
    END IF;
  END LOOP;

  FOR BB IN (SELECT PB.*, PR.CODPARTRETAIL, L.DEN_LOCALIT AS DENLOCALIT, L.CODJUDET, L.CODTARA, K.DENUMIRE AS DENBANCA, PR.TIPMODIF
             FROM NPARTB PB
                  LEFT JOIN NLOCALIT L ON  L.CODLOCALIT = PB.CODLOCALIT
                  LEFT JOIN NBANK K ON  K.CODBANK = PB.CODBANK, NPARTRETAIL PR, TMP_NPART TP
             WHERE TP.CODPART = PR.CODPART AND  PB.CODPART = PR.CODPART
            )
  LOOP
    UPDATE  NBANCIRETAIL BR
     SET CODBANK = BB.CODBANK, IMPLICIT = BB.IMPLICIT, CODLOCALIT = BB.CODLOCALIT, CONTBANCA = BB.CONTBANCA, SUCURSALA = BB.SUCURSALA, CODMONEDA = BB.CODMONEDA, DENBANCA = BB.DENBANCA, DENLOCALIT = BB.DENLOCALIT, CODJUDET = BB.CODJUDET, CODTARA = BB.CODTARA
    WHERE
     BR.CODPARTB = BB.CODPARTB;

    IF NOT FOUND THEN
      INSERT INTO NBANCIRETAIL(COD, CODPARTRETAIL, CODBANK, IMPLICIT, CODLOCALIT, CONTBANCA, SUCURSALA, CODMONEDA, DENBANCA, DENLOCALIT, CODPARTB, CODJUDET, CODTARA)
      VALUES (NEXTVAL('SEQ_NBANCIRETAIL_COD'), BB.CODPARTRETAIL, BB.CODBANK, BB.IMPLICIT, BB.CODLOCALIT, BB.CONTBANCA, BB.SUCURSALA, BB.CODMONEDA, BB.DENBANCA, BB.DENLOCALIT, BB.CODPARTB, BB.CODJUDET, BB.CODTARA) ;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_npartretail_muta_codificari_pe_retail</obj_name>
  <obj_hashval>f6e89b7cca4a11b89f40dceae8b2d35f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_npartretail_muta_codificari_pe_retail()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TL    RECORD;
  TB    RECORD;
  PREC  RECORD;
  V_REC RECORD;
  S     RECORD;
  CFREC RECORD;
  PDREC RECORD;
  DR    RECORD;
  PBR   RECORD;
BEGIN
  --Florin 03.02.2023 - sinc. Oracle
  FOR TL IN (SELECT * FROM TMP_NLOCALIT TL) LOOP
    INSERT INTO NLOCALIT (CODLOCALIT, DEN_LOCALIT, CODJUDET, CODTARA)
    VALUES (TL.CODLOCALIT, TL.DEN_LOCALIT, TL.CODJUDET, TL.CODTARA);
  END LOOP;

  FOR TB IN (SELECT * FROM TMP_NBANK TB) LOOP
    INSERT INTO NBANK (CODBANK, DENUMIRE, SIMBOL)
    VALUES (TB.CODBANK, TB.DENUMIRE, SUBSTR (TB.DENUMIRE, 1, 30));
  END LOOP;

  FOR PREC IN (SELECT * FROM TMP_NPARTRETAIL PR) LOOP
    UPDATE NPART P
    SET
      DEN_PART       = PREC.DENUMIRE,
      REGCOM         = PREC.REGCOM,
      OBS            = PREC.OBS,
      CODEXTERN      = PREC.CODEXTERN,
      CODINTERN      = PREC.CODINTERN,
      PERSOANAFIZICA = PREC.TIPPART,
      COLDISCOUNT    = PREC.COLDISCOUNT,
      FIDELIZARE     = PREC.FIDELIZARE,
      DATANASTERE    = PREC.DATANASTERE,
      BLOCAT         = PREC.BLOCAT,
      INFOBLOCAT     = PREC.INFOBLOCAT,
      CODCLASA       = PREC.CODCLASA
    WHERE
      P.CODPART = PREC.CODPART;

    IF NOT FOUND THEN
      INSERT INTO NPART AS P (CODPART, DEN_PART, REGCOM, OBS,
          CODEXTERN, CODINTERN, TIPPART, COLDISCOUNT,
          CODCLASA, FIDELIZARE, DATANASTERE, BLOCAT,
          INFOBLOCAT)
      VALUES (PREC.CODPART, PREC.DENUMIRE, PREC.REGCOM, PREC.OBS,
          PREC.CODEXTERN, PREC.CODINTERN, PREC.TIPPART, PREC.COLDISCOUNT,
          PREC.CODCLASA, PREC.FIDELIZARE, PREC.DATANASTERE, PREC.BLOCAT,
          PREC.INFOBLOCAT);
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_NPARTRETAIL) LOOP
    UPDATE NPARTRETAIL
    SET CODPART = V_REC.CODPART, TIPMODIF = NULL
    WHERE
      CODPARTRETAIL = V_REC.CODPARTRETAIL;

    UPDATE EMULARE
    SET CODPART = V_REC.CODPART
    WHERE
      CODPARTRETAIL = V_REC.CODPARTRETAIL;

    UPDATE EMULARE
    SET CODPARTCOMIS = V_REC.CODPART
    WHERE
      CODPARTRETAILCOMIS = V_REC.CODPARTRETAIL;

    UPDATE IESIRIRETAIL
    SET PARTENER = V_REC.CODPART
    WHERE
      CODPARTRETAIL = V_REC.CODPARTRETAIL;

    UPDATE IESIRIRETAIL
    SET
      CODPARTCOMIS   = V_REC.CODPART
    WHERE
      CODPARTRETAILCOMIS = V_REC.CODPARTRETAIL;

    UPDATE DETALIIET
    SET
      CODPARTTR   = V_REC.CODPART
    WHERE
      CODPARTRETAILTR = V_REC.CODPARTRETAIL;
  END LOOP;

  FOR S IN (SELECT SR.*, PR.CODPART
            FROM TMP_NSEDIIPARTRETAIL SR, NPARTRETAIL PR
            WHERE SR.CODPARTRETAIL = PR.CODPARTRETAIL
           )
  LOOP
    UPDATE NAGENDA A
    SET CODLOCALIT = S.CODLOCALIT, SEDIUSOCIAL = S.SEDIUSOCIAL, TELEFON = S.TELEFON, FAX = S.FAX,
      EMAIL = S.EMAIL, SECTOR = S.SECTOR, STRADA = S.STRADA, NR1 = S.NR1,
      NR2 = S.NR2, BLOC = S.BLOC, SCARA = S.SCARA, ETAJ = S.ETAJ,
      APART = S.APART, CODPOSTAL = S.CODPOSTAL, OBS = S.DENUMIRE
    WHERE
      A.CODAGENDA = S.CODAGENDA;

    IF NOT FOUND THEN
      INSERT INTO NAGENDA AS A (CODAGENDA, TIP, CODLOCALIT, SEDIUSOCIAL,
          TELEFON, FAX, EMAIL, SECTOR,
          STRADA, NR1, NR2, BLOC,
          SCARA, ETAJ, APART, CODPOSTAL,
          OBS, CODPART)
      VALUES (S.CODAGENDA, 0, S.CODLOCALIT, S.SEDIUSOCIAL,
          S.TELEFON, S.FAX, S.EMAIL, S.SECTOR,
          S.STRADA, S.NR1, S.NR2, S.BLOC,
          S.SCARA, S.ETAJ, S.APART, S.CODPOSTAL,
          S.DENUMIRE, S.CODPART);
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_NSEDIIPARTRETAIL) LOOP
    UPDATE NSEDIIPARTRETAIL
    SET CODAGENDA = V_REC.CODAGENDA, CODLOCALIT = V_REC.CODLOCALIT
    WHERE
      CODSEDIU = V_REC.CODSEDIU;

    UPDATE EMULARE
    SET CODLOCATIE = V_REC.CODAGENDA
    WHERE
      CODSEDIURETAIL = V_REC.CODSEDIU;

    UPDATE IESIRIRETAIL
    SET CODLOCATIE = V_REC.CODAGENDA
    WHERE
      CODSEDIURETAIL = V_REC.CODSEDIU;
  END LOOP;

  FOR CFREC IN (SELECT CFR.*, PR.CODPART
                FROM TMP_NCODFISCRETAIL CFR, NPARTRETAIL PR
                WHERE PR.CODPARTRETAIL = CFR.CODPARTRETAIL
               )
  LOOP
    UPDATE NPARTCODFISC CF
    SET CODFISCAL = CFREC.CODFISCAL, PRINCIPAL = CFREC.PRINCIPAL
    WHERE
      CF.COD_CODFISCAL = CFREC.COD_CODFISCAL;

    IF NOT FOUND THEN
      INSERT INTO NPARTCODFISC AS CF (COD_CODFISCAL, CODPART, CODFISCAL, PRINCIPAL)
      VALUES (CFREC.COD_CODFISCAL, CFREC.CODPART, CFREC.CODFISCAL, CFREC.PRINCIPAL);
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_NCODFISCRETAIL) LOOP
    UPDATE NCODFISCRETAIL
    SET COD_CODFISCAL = V_REC.COD_CODFISCAL
    WHERE
      COD = V_REC.COD;

    UPDATE IESIRIRETAIL
    SET CODFISCAL = V_REC.COD_CODFISCAL
    WHERE
      CODFISCALRETAIL = V_REC.COD;
  END LOOP;

  FOR PDREC IN (SELECT PDR.*, PR.CODPART
                FROM TMP_NPARTDISCRETAIL PDR, NPARTRETAIL PR
                WHERE PR.CODPARTRETAIL = PDR.CODPARTRETAIL
               )
  LOOP
    UPDATE NPARTDISC PD
    SET CODCATEGDISC = PDREC.CODCATEGDISC, INDEXLOCAL = PDREC.INDEXLOCAL
    WHERE
      PD.CODPARTDISC = PDREC.CODPARTDISC;

    IF NOT FOUND THEN
      INSERT INTO NPARTDISC AS PD (CODPARTDISC, CODPART, CODCATEGDISC, INDEXLOCAL)
        VALUES (PDREC.CODPARTDISC, PDREC.CODPART, PDREC.CODCATEGDISC, PDREC.INDEXLOCAL);
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_NPARTDISCRETAIL) LOOP
    UPDATE NPARTDISCRETAIL
    SET CODPARTDISC = V_REC.CODPARTDISC
    WHERE
      COD = V_REC.COD;
  END LOOP;

  FOR DR IN (SELECT D.*, PR.CODPART
             FROM TMP_NDELEGATRETAIL D, NPARTRETAIL PR
             WHERE PR.CODPARTRETAIL = D.CODPARTRETAIL
            )
  LOOP
    UPDATE NPARTTR TR
    SET DELEGAT = DR.DELEGAT, CNP = DR.CNP, DOC = DR.DOC, SERIEDOC = DR.SERIEDOC,
      NRDOC = DR.NRDOC, ELIBERAT = DR.ELIBERAT, MIJLTRANSP = DR.MIJLTRANSP, NRTRANSP = DR.NRTRANSP,
      ACTIV = DR.ACTIV, DATADOC = DR.DATADOC, IMPLICIT = DR.IMPLICIT, OBS = DR.OBS
    WHERE
      TR.CODPARTTR = DR.CODPARTTR;

    IF NOT FOUND THEN
      INSERT INTO NPARTTR AS TR (CODPARTTR, CODPART, DELEGAT, CNP,
          DOC, SERIEDOC, NRDOC, ELIBERAT,
          MIJLTRANSP, NRTRANSP, ACTIV, DATADOC,
          IMPLICIT, OBS)
      VALUES (DR.CODPARTTR, DR.CODPART, DR.DELEGAT, DR.CNP,
          DR.DOC, DR.SERIEDOC, DR.NRDOC, DR.ELIBERAT,
          DR.MIJLTRANSP, DR.NRTRANSP, DR.ACTIV, DR.DATADOC,
          DR.IMPLICIT, DR.OBS);
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_NDELEGATRETAIL)
  LOOP
    UPDATE NDELEGATRETAIL
    SET CODPARTTR = V_REC.CODPARTTR
    WHERE
      COD = V_REC.COD;

    UPDATE IESIRIRETAIL
    SET DELEGAT = V_REC.CODPARTTR
    WHERE
      DELEGATRETAIL = V_REC.COD;
  END LOOP;

  FOR PBR IN (SELECT BR.*, PR.CODPART
              FROM TMP_NBANCIRETAIL BR, NPARTRETAIL PR
              WHERE PR.CODPARTRETAIL = BR.CODPARTRETAIL
             )
  LOOP
    UPDATE NPARTB PB
    SET
      CODBANK    = PBR.CODBANK,
      IMPLICIT   = PBR.IMPLICIT,
      CODLOCALIT = PBR.CODLOCALIT,
      CONTBANCA  = PBR.CONTBANCA,
      SUCURSALA  = PBR.SUCURSALA,
      CODMONEDA  = PBR.CODMONEDA
    WHERE
      PB.CODPARTB = PBR.CODPARTB;

    IF NOT FOUND THEN
      INSERT INTO NPARTB AS PB (CODPARTB, CODPART, CODBANK, IMPLICIT, CODLOCALIT, CONTBANCA, SUCURSALA, CODMONEDA)
      VALUES (PBR.CODPARTB, PBR.CODPART, PBR.CODBANK, PBR.IMPLICIT, PBR.CODLOCALIT, PBR.CONTBANCA, PBR.SUCURSALA, PBR.CODMONEDA);
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_NBANCIRETAIL) LOOP
    UPDATE NBANCIRETAIL
    SET
      CODPARTB   = V_REC.CODPARTB,
      CODLOCALIT = V_REC.CODLOCALIT,
      CODBANK    = V_REC.CODBANK
    WHERE
      COD = V_REC.COD;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_npartretail_set_flag_sincronizat</obj_name>
  <obj_hashval>41031c1a04317a931653497bf6a923b4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_npartretail_set_flag_sincronizat()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN (SELECT * FROM TMP_MANEVRA) LOOP
    UPDATE SYNCPARTRETAIL SET SINCRONIZAT = 1 WHERE CODSYNCPART = V_REC.CODUNIC;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_npartretail_syncron_partbaza_on_retail</obj_name>
  <obj_hashval>35620e314fea583b62da49e40535ef85</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_npartretail_syncron_partbaza_on_retail()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TL  RECORD;
  TP  RECORD;
  TP1 RECORD;
  TA  RECORD;
  V_REC record;
BEGIN
  --Florin 23.11.2022 - sinc. Oracle
  --Florin 14.11.2022 - sinc. Oracle
  --Adina 13.03.2021 - prc_al_refresh, alstart, alstop
  CALL PRC_AL_REFRESH('tmp_npart1', 0);

  FOR TL IN ( SELECT * FROM TMP_NLOCALIT TL) LOOP
    UPDATE  NLOCALIT L
     SET DEN_LOCALIT = TL.DEN_LOCALIT, CODJUDET = TL.CODJUDET, CODTARA = TL.CODTARA
    WHERE
     TL.CODLOCALIT = L.CODLOCALIT;

    IF NOT FOUND THEN
      INSERT INTO NLOCALIT(CODLOCALIT, DEN_LOCALIT, CODJUDET, CODTARA)
      VALUES (TL.CODLOCALIT, TL.DEN_LOCALIT, TL.CODJUDET, TL.CODTARA) ;
    END IF;
  END LOOP;

  FOR TP IN ( SELECT * FROM TMP_NPART TP) LOOP
    UPDATE  NPART P
     SET DEN_PART = TP.DEN_PART, REGCOM = TP.REGCOM, CODEXTERN = TP.CODEXTERN, CODMONEDA = TP.CODMONEDA, AUTORIZATIE = TP.AUTORIZATIE, CODINTERN = TP.CODINTERN, CODCLASA = TP.CODCLASA, CODCATEGPRET = TP.CODCATEGPRET, TIPPART = TP.TIPPART, SCADENTAC = TP.SCADENTAC, SCADENTAV = TP.SCADENTAV, DISCOUNT = TP.DISCOUNT, CODCATEGDISC = TP.CODCATEGDISC, BLOCAT = TP.BLOCAT, TIPPARTENER = TP.TIPPARTENER, DATAADAUGARII = TP.DATAADAUGARII, OBS = TP.OBS, POZA = TP.POZA, PERSOANAFIZICA = TP.PERSOANAFIZICA, COLDISCOUNT = TP.COLDISCOUNT, INFOBLOCAT = TP.INFOBLOCAT, EXPIRAREAUTORIZ = TP.EXPIRAREAUTORIZ, CODSTATISTICBNR = TP.CODSTATISTICBNR, MUSAICOLET = TP.MUSAICOLET, STRATEGIC = TP.STRATEGIC, CIFRAAFACERI = TP.CIFRAAFACERI, DOMENIUACTIV = TP.DOMENIUACTIV, NRANGAJATI = TP.NRANGAJATI, SURSALEAD = TP.SURSALEAD, LEAD = TP.LEAD, TVALAINCASARE = TP.TVALAINCASARE, MODAPLICPROCDISC = TP.MODAPLICPROCDISC, PROCCURSTRANSF = TP.PROCCURSTRANSF, FIDELIZARE = TP.FIDELIZARE, DATANASTERE = TP.DATANASTERE, MAJORARI = TP.MAJORARI, TIPBLOCAJ = TP.TIPBLOCAJ, POPRIRE_ANAF = TP.POPRIRE_ANAF, CODRESPONSABIL = TP.CODRESPONSABIL, CODDOMENIUACT = TP.CODDOMENIUACT, DOCDEFONORCOM = TP.DOCDEFONORCOM, MODPROMOFACTCOM = TP.MODPROMOFACTCOM, VALIDAREPRETOFERTA = TP.VALIDAREPRETOFERTA, IESCUCOMANDA = TP.IESCUCOMANDA, CANTMINCMD = TP.CANTMINCMD, ZIAPROVIZ = TP.CANTMINCMD, PERAPROVIZ = TP.PERAPROVIZ
    WHERE
     TP.CODPART = P.CODPART;

    IF NOT FOUND THEN
      INSERT INTO NPART(CODPART, DEN_PART, REGCOM, CODEXTERN, CODMONEDA, AUTORIZATIE, CODINTERN, CODCLASA, CODCATEGPRET, TIPPART, SCADENTAC, SCADENTAV, DISCOUNT, CODCATEGDISC, BLOCAT, TIPPARTENER, DATAADAUGARII, OBS, POZA, PERSOANAFIZICA, COLDISCOUNT, INFOBLOCAT, EXPIRAREAUTORIZ, CODSTATISTICBNR, MUSAICOLET, STRATEGIC, CIFRAAFACERI, DOMENIUACTIV, NRANGAJATI, SURSALEAD, LEAD, TVALAINCASARE, MODAPLICPROCDISC, PROCCURSTRANSF, FIDELIZARE, DATANASTERE, MAJORARI, TIPBLOCAJ, POPRIRE_ANAF, CODRESPONSABIL, CODDOMENIUACT, DOCDEFONORCOM, MODPROMOFACTCOM, VALIDAREPRETOFERTA, IESCUCOMANDA, CANTMINCMD, ZIAPROVIZ, PERAPROVIZ)
      VALUES (TP.CODPART, TP.DEN_PART, TP.REGCOM, TP.CODEXTERN, TP.CODMONEDA, TP.AUTORIZATIE, TP.CODINTERN, TP.CODCLASA, TP.CODCATEGPRET, TP.TIPPART, TP.SCADENTAC, TP.SCADENTAV, TP.DISCOUNT, TP.CODCATEGDISC, TP.BLOCAT, TP.TIPPARTENER, TP.DATAADAUGARII, TP.OBS, TP.POZA, TP.PERSOANAFIZICA, TP.COLDISCOUNT, TP.INFOBLOCAT, TP.EXPIRAREAUTORIZ, TP.CODSTATISTICBNR, TP.MUSAICOLET, TP.STRATEGIC, TP.CIFRAAFACERI, TP.DOMENIUACTIV, TP.NRANGAJATI, TP.SURSALEAD, TP.LEAD, TP.TVALAINCASARE, TP.MODAPLICPROCDISC, TP.PROCCURSTRANSF, TP.FIDELIZARE, TP.DATANASTERE, TP.MAJORARI, TP.TIPBLOCAJ, TP.POPRIRE_ANAF, TP.CODRESPONSABIL, TP.CODDOMENIUACT, TP.DOCDEFONORCOM, TP.MODPROMOFACTCOM, TP.VALIDAREPRETOFERTA, TP.IESCUCOMANDA, TP.CANTMINCMD, TP.ZIAPROVIZ, TP.PERAPROVIZ) ;
    END IF;
  END LOOP;



FOR TP1 IN (
SELECT TPP1.*
FROM
  TMP_NPART1 TPP1
  LEFT JOIN NPART1 P1 ON P1.CODPART = TPP1.CODPART AND P1.ANSTART = TPP1.ANSTART AND P1.LUNASTART = TPP1.LUNASTART
WHERE
  COALESCE(P1.CODPART1, 0) = 0
) LOOP
  INSERT INTO NPART1
 (CODPART1, CODPART, CODIOPART, CREDITCLIENT, VOLUMTRANZC, CREDITFURN, VOLUMTRANZF, ANSTART, LUNASTART, SCADENTAV, SCADENTAC, DISCOUNT, CASSBAZAMIN, SIMBOLCASS, ALSTART, ALSTOP)
 VALUES (TP1.CODPART1, TP1.CODPART, TP1.CODIOPART, TP1.CREDITCLIENT, TP1.VOLUMTRANZC, TP1.CREDITFURN, TP1.VOLUMTRANZF, TP1.ANSTART, TP1.LUNASTART, TP1.SCADENTAV, TP1.SCADENTAC, TP1.DISCOUNT, TP1.CASSBAZAMIN, TP1.SIMBOLCASS, TP1.ALSTART, TP1.ALSTOP) ;
END LOOP;




--  FOR TP1 IN ( SELECT * FROM TMP_NPART1 TP1) LOOP
--   INSERT INTO NPART1(CODPART1, CODPART, CODIOPART, CREDITCLIENT, VOLUMTRANZC, CREDITFURN, VOLUMTRANZF, ANSTART, LUNASTART, SCADENTAV, SCADENTAC, DISCOUNT, CASSBAZAMIN, SIMBOLCASS, ALSTART, ALSTOP)
--    VALUES (TP1.CODPART1, TP1.CODPART, TP1.CODIOPART, TP1.CREDITCLIENT, TP1.VOLUMTRANZC, TP1.CREDITFURN, TP1.VOLUMTRANZF, TP1.ANSTART, TP1.LUNASTART, TP1.SCADENTAV, TP1.SCADENTAC, TP1.DISCOUNT, TP1.CASSBAZAMIN, TP1.SIMBOLCASS, TP1.ALSTART, TP1.ALSTOP) ;
--  END LOOP;

  FOR TP IN ( SELECT * FROM TMP_NPARTCODFISC TP) LOOP
    UPDATE  NPARTCODFISC
     SET CODFISCAL = TP.CODFISCAL, PRINCIPAL = TP.PRINCIPAL
    WHERE
      COD_CODFISCAL = TP.COD_CODFISCAL;

    IF NOT FOUND THEN
      INSERT INTO NPARTCODFISC(COD_CODFISCAL, CODPART, CODFISCAL, PRINCIPAL)
      VALUES (TP.COD_CODFISCAL, TP.CODPART, TP.CODFISCAL, TP.PRINCIPAL) ;
    END IF;
  END LOOP;

  FOR TP IN ( SELECT * FROM TMP_NPARTTR TP) LOOP
    UPDATE  NPARTTR
     SET DELEGAT = TP.DELEGAT, CNP = TP.CNP, DOC = TP.DOC, SERIEDOC = TP. SERIEDOC, NRDOC = TP.NRDOC, ELIBERAT = TP.ELIBERAT, MIJLTRANSP = TP.MIJLTRANSP, NRTRANSP = TP.NRTRANSP, ACTIV = TP.ACTIV, DATADOC = TP.DATADOC, CODPERS = TP.CODPERS, CODAUTO = TP.CODAUTO, IMPLICIT = TP.IMPLICIT, OBS = TP.OBS, PERMIS = TP.PERMIS, NRPASS = TP.NRPASS, CODTARA = TP.CODTARA, ADRESA = TP.ADRESA, CODLOCALIT = TP.CODLOCALIT, TELEFON = TP.TELEFON, EMAIL = TP.EMAIL
    WHERE
       CODPARTTR = TP.CODPARTTR;

    IF NOT FOUND THEN
      INSERT INTO NPARTTR(CODPARTTR, CODPART, DELEGAT, CNP, DOC, SERIEDOC, NRDOC, ELIBERAT, MIJLTRANSP, NRTRANSP, ACTIV, DATADOC, CODPERS, CODAUTO, IMPLICIT, OBS, PERMIS, NRPASS, CODTARA, ADRESA, CODLOCALIT, TELEFON, EMAIL)
      VALUES (TP.CODPARTTR, TP.CODPART, TP.DELEGAT, TP.CNP, TP.DOC, TP.SERIEDOC, TP.NRDOC, TP.ELIBERAT, TP.MIJLTRANSP, TP.NRTRANSP, TP.ACTIV, TP.DATADOC, TP.CODPERS, TP.CODAUTO, TP.IMPLICIT, TP.OBS, TP.PERMIS, TP.NRPASS, TP.CODTARA, TP.ADRESA, TP.CODLOCALIT, TP.TELEFON, TP.EMAIL) ;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT CODPART FROM TMP_NPART)
  LOOP
    DELETE FROM NPARTDISC
  WHERE
    CODPART = V_REC.CODPART;
  END LOOP;


  FOR TP IN ( SELECT * FROM TMP_NPARTDISC TP) LOOP
    UPDATE  NPARTDISC
     SET CODCATEGDISC = TP.CODCATEGDISC, INDEXLOCAL = TP.INDEXLOCAL
    WHERE
      CODPARTDISC = TP.CODPARTDISC;

    IF NOT FOUND THEN
      INSERT INTO NPARTDISC(CODPARTDISC, CODPART, CODCATEGDISC, INDEXLOCAL)
      VALUES (TP.CODPARTDISC, TP.CODPART, TP.CODCATEGDISC, TP.INDEXLOCAL) ;
    END IF;
  END LOOP;

  DELETE FROM NPARTDISCRETAIL
  WHERE
    CODPARTDISC NOT IN (SELECT CODPARTDISC FROM NPARTDISC);

  FOR TP IN ( SELECT * FROM TMP_NPARTB TP) LOOP
    UPDATE  NPARTB
     SET CODBANK = TP.CODBANK, IMPLICIT = TP.IMPLICIT, CODLOCALIT = TP.CODLOCALIT, CONTBANCA = TP.CONTBANCA, SUCURSALA = TP.SUCURSALA, CODSWIFT = TP.CODSWIFT, CODMONEDA = TP.CODMONEDA, TIPCOMISION = TP.TIPCOMISION, OBS = TP.OBS
    WHERE
     TP.CODPARTB = CODPARTB;

    IF NOT FOUND THEN
      INSERT INTO NPARTB(CODPARTB, CODPART, CODBANK, IMPLICIT, CODLOCALIT, CONTBANCA, SUCURSALA, CODSWIFT, CODMONEDA, TIPCOMISION, OBS)
      VALUES (TP.CODPARTB, TP.CODPART, TP.CODBANK, TP.IMPLICIT, TP.CODLOCALIT, TP.CONTBANCA, TP.SUCURSALA, TP.CODSWIFT, TP.CODMONEDA, TP.TIPCOMISION, TP.OBS) ;
    END IF;
  END LOOP;

  FOR TA IN ( SELECT * FROM TMP_NAGENDA TA) LOOP
    UPDATE  NAGENDA
     SET TIP = TA.TIP, CODLOCALIT = TA.CODLOCALIT, SEDIUSOCIAL = TA.SEDIUSOCIAL, TELEFON = TA.TELEFON, FAX = TA.FAX, EMAIL = TA.EMAIL, SECTOR = TA.SECTOR, STRADA = TA.STRADA, NR1 = TA.NR1, NR2 = TA.NR2, BLOC = TA.BLOC, SCARA = TA.SCARA, ETAJ = TA.ETAJ, APART = TA.APART, CODPOSTAL = TA.CODPOSTAL, KM = TA.KM, OBS = TA.OBS, CODBANKCONT = TA.CODBANKCONT, CODPART = TA.CODPART, CODGEST = TA.CODGEST, CODSUBUNIT = TA.CODSUBUNIT, CODTIPSEDIU = TA.CODTIPSEDIU, CODFISCAL = TA.CODFISCAL, CODAGENT = TA.CODAGENT, CODCLIENT = TA.CODCLIENT, CODTRASEU = TA.CODTRASEU, POZTRASEU = TA.POZTRASEU, INACTIV = TA.INACTIV, CODCORESP = TA.CODCORESP, TRANSPCLIENT = TA.TRANSPCLIENT, COEFUTILAJE = TA.COEFUTILAJE, SUPRAFATA = TA.SUPRAFATA, MODSERVIRE = TA.MODSERVIRE, IDSEDIU = TA.IDSEDIU, COD_CODFISCAL = TA.COD_CODFISCAL, TELEFONP = TA.TELEFONP, EDI_EXPTIP = TA.EDI_EXPTIP, EDI_PARTTIP = TA.EDI_PARTTIP, EDI_PARTID = TA.EDI_PARTID, EDI_OBJTIP = TA.EDI_OBJTIP, GLN = TA.GLN, GESTLIVRARE = TA.GESTLIVRARE, LONGITUDINE = TA.LONGITUDINE, LATITUDINE = TA.LATITUDINE, OBS2 = TA.OBS2, EDI_IMPTIP = TA.EDI_IMPTIP, EDI_FURNTIP = TA.EDI_FURNTIP, EDI_FURNID = TA.EDI_FURNID, EDI_OBJTIPIMP = TA.EDI_OBJTIPIMP, EDI_EXPCUMUL = TA.EDI_EXPCUMUL, EDI_EXPEAN = TA.EDI_EXPEAN
    WHERE
      CODAGENDA = TA.CODAGENDA;

    IF NOT FOUND THEN
      INSERT INTO NAGENDA(CODAGENDA, TIP, CODLOCALIT, SEDIUSOCIAL, TELEFON, FAX, EMAIL, SECTOR, STRADA, NR1, NR2, BLOC, SCARA, ETAJ, APART, CODPOSTAL, KM, OBS, CODBANKCONT, CODPART, CODGEST, CODSUBUNIT, CODTIPSEDIU, CODFISCAL, CODAGENT, CODCLIENT, CODTRASEU, POZTRASEU, CODTRASEU1, POZTRASEU1, INACTIV, CODCORESP, TRANSPCLIENT, COEFUTILAJE, SUPRAFATA, MODSERVIRE, IDSEDIU, COD_CODFISCAL, TELEFONP, EDI_EXPTIP, EDI_PARTTIP, EDI_PARTID, EDI_OBJTIP, GLN, GESTLIVRARE, LONGITUDINE, LATITUDINE, OBS2, EDI_IMPTIP, EDI_FURNTIP, EDI_FURNID, EDI_OBJTIPIMP, EDI_EXPCUMUL, EDI_EXPEAN)
      VALUES (TA.CODAGENDA, TA.TIP, TA.CODLOCALIT, TA.SEDIUSOCIAL, TA.TELEFON, TA.FAX, TA.EMAIL, TA.SECTOR, TA.STRADA, TA.NR1, TA.NR2, TA.BLOC, TA.SCARA, TA.ETAJ, TA.APART, TA.CODPOSTAL, TA.KM, TA.OBS, TA.CODBANKCONT, TA.CODPART, TA.CODGEST, TA.CODSUBUNIT, TA.CODTIPSEDIU, TA.CODFISCAL, TA.CODAGENT, TA.CODCLIENT, TA.CODTRASEU, TA.POZTRASEU, TA.CODTRASEU1, TA.POZTRASEU1, TA.INACTIV, TA.CODCORESP, TA.TRANSPCLIENT, TA.COEFUTILAJE, TA.SUPRAFATA, TA.MODSERVIRE, TA.IDSEDIU, TA.COD_CODFISCAL, TA.TELEFONP, TA.EDI_EXPTIP, TA.EDI_PARTTIP, TA.EDI_PARTID, TA.EDI_OBJTIP, TA.GLN, TA.GESTLIVRARE, TA.LONGITUDINE, TA.LATITUDINE, TA.OBS2, TA.EDI_IMPTIP, TA.EDI_FURNTIP, TA.EDI_FURNID, TA.EDI_OBJTIPIMP, TA.EDI_EXPCUMUL, TA.EDI_EXPEAN) ;
    END IF;
  END LOOP;

  PERFORM PKG_NPARTRETAIL_MAKE_PARTRETAIL_FROM_TMPNPART();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_nzone_sp_insertrecord</obj_name>
  <obj_hashval>295ab229ac89b5edff151d41c09efcb3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_nzone_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_Nzone(codzona) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oferta_getct_monitor</obj_name>
  <obj_hashval>d5e29586d3f1db9350dcb8bf518b775b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oferta_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_OFERTA.CT_MONITOR', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_28';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_oferta_getpretofertapartlocobj</obj_name>
  <obj_hashval>4211dc93642e1aa0a895369396f3b6f9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_oferta_getpretofertapartlocobj(INOUT wme_result numeric, INOUT acodpart numeric, INOUT acodlocatie numeric, INOUT acodobiect numeric, INOUT adataref character varying, INOUT atipdoc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aPret double precision;
begin
  BEGIN
    SELECT o1.pret
    INTO aPret
    FROM oferta1 o1
        INNER JOIN oferta o ON  o1.codoferta = o.codoferta
    WHERE
       o1.codobiect = aCodObiect
       AND (o.codlocatie = aCodLocatie or  Coalesce( o.codlocatie, 0) = 0)
       AND to_date( aDataRef, 'dd.mm.yyyy') BETWEEN o.datastart AND o.dataend
       AND  o.partener = aCodpart
       AND  o.tipdoc   = aTipDoc;
  EXCEPTION WHEN OTHERS THEN
    aPret := 0;
  END;

  WME_Result :=  aPret;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_onorarecomenzi_getpdatasys</obj_name>
  <obj_hashval>a30f732150a40da3c623ad1332555745</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_onorarecomenzi_getpdatasys(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_ONORARECOMENZI.pDataSys', true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_onorarecomenzi_settermen_old</obj_name>
  <obj_hashval>16f8a7d510c51e7aef797bbc1628624c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_onorarecomenzi_settermen_old(atermen character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_ONORARECOMENZI.pDataSys'     ,DATE_TRUNC('DAY', CURRENT_TIMESTAMP)           ,false);
  perform set_config('PKG_ONORARECOMENZI.pDataTermLivr',To_Date( COALESCE( aTermen, 'X'), 'DD.MM.YYYY'),false);
  perform set_config('PKG_ONORARECOMENZI.pFlagTermLivr',to_char(1,'999999999999999999')                ,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_onorarecomenzi_ulck_comanda</obj_name>
  <obj_hashval>8c547d2698bcc360321fb1a25c37263e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_onorarecomenzi_ulck_comanda(acodcomanda numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  UPDATE Comanda SET UserIDBlocaj = NULL WHERE CodComanda = aCodComanda;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_opper_sp_insertrecord</obj_name>
  <obj_hashval>090e6f24631df01aa1e8afc911cbde2d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_opper_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_OPPER(CodOpper) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_getjob_codjob1</obj_name>
  <obj_hashval>59447deda4b2235b452ef8c65be079a9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_getjob_codjob1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_ORA_LISTS.JOB_CodJob1', true),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ora_lists_set_interval_listare</obj_name>
  <obj_hashval>ed1cbc2608113e25f9bfbe247d485fc7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ora_lists_set_interval_listare(adataini date, adatafin date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  -- Stef 27.07.2020
  perform set_config('PKG_ORA_LISTS.JOB_DATAIni', To_Char(aDataIni,'dd.mm.yyyy'), false);
  perform set_config('PKG_ORA_LISTS.JOB_DATAFin', To_Char(aDataFin,'dd.mm.yyyy'), false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_orar_g_codjob</obj_name>
  <obj_hashval>de7dbb26d0a4333d6665632871700250</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_orar_g_codjob(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_ORAR.g_CodJob', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_orar_sp_postrecords</obj_name>
  <obj_hashval>42780994b5c730dcb9045146d4c32d4f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_orar_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  OPERATION = 0 THEN
    SELECT CODORAR INTO RECID FROM TMP_ORAR;

    UPDATE ORAR O
    SET
    (DENUMIRE, OBS, REPETARE, INTERVAL, ORA, MIN, ZILE_SAPT, ZILE_LUNA, DATA_START, DATA_FIN)
    =
    (SELECT OBS,--DENUMIRE,
            OBS, REPETARE, INTERVAL, ORA, MIN, ZILE_SAPT, ZILE_LUNA, DATE_TRUNC('DAY',DATA_START), DATE_TRUNC('DAY',DATA_FIN)
     FROM TMP_ORAR
    )
    WHERE O.CODORAR = RECID;
  ELSE
    SELECT NEXTVAL('SEQ_ORAR_CODORAR') INTO RECID;

    INSERT INTO ORAR(CODORAR, DENUMIRE, OBS, REPETARE, INTERVAL, ORA, MIN, ZILE_SAPT, ZILE_LUNA, DATA_START, DATA_FIN, USERID, DATACREARE)
    SELECT RECID, OBS,
          --DENUMIRE,
           OBS, REPETARE, INTERVAL, ORA, MIN, ZILE_SAPT, ZILE_LUNA, DATE_TRUNC('DAY',DATA_START), DATE_TRUNC('DAY',DATA_FIN), current_setting('PKG_GLOBALS.USERID', true)::numeric, CURRENT_TIMESTAMP
      FROM TMP_ORAR;
  END IF;
  --PERFORM CREAZA_ORAR(RecId, Operation);
  PERFORM NotifyModif(OPERATION, RECID, 'ORAR');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pachete_sp_postrecords</obj_name>
  <obj_hashval>a2a04eb3a7a93c497dae8dab1dc66161</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pachete_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aCarnetDoc numeric;
  aNumarDoc  numeric;
  aDataDoc   date;
  aDoc       varchar;
  aSubunit   numeric;
BEGIN
  --Florin 01.06.2023 - monitor
  --Florin 15.05.2023 - fixat 58265
  --Florin 12.04.2023 - sinc. Oracle (10.04.2023)
  --Florin 05.05.2022 - sinc. Oracle (04.05.2022)
  --Florin 28.01.2022 - sinc. Orcale (25.01.2022)
  --Florin 29.12.2021 - sinc. Oracle (28.12.2021)
  perform pkg_pachete_setct_monitor('MON_61');
  SELECT CarnetDoc, NrDoc, DataP, SerieDoc || NrDoc || '/' || DataP, Subunitate
  INTO aCarnetDoc, aNumarDoc, aDataDoc, aDoc, aSubunit
  FROM TMP_PACHETE;

  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT (77);
  IF Operation = 0 THEN
    SELECT codpachete INTO RecId FROM TMP_PACHETE;

    IF (SELECT WME_RESULT
        FROM WINMADMIN.PKG_USERFIRME_ValidPostLog (NULL, TO_NUMBER ((current_setting ('PKG_GLOBALS.USERID', true)) ,'999999999999999999') , (current_setting ('PKG_PACHETE.CT_MONITOR', true))))
    THEN
      PERFORM WINMADMIN.pkg_userfirme_postlogcucommit ('PACHETE', (current_setting ('PKG_GLOBALS.USERNAME', true)) , 'M', RECID,
                                                       (current_setting ('PKG_GLOBALS.FIRMANAME', true)) , aSubunit, aDataDoc, aDoc, null,
                                                       (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION (NULL,NULL)));
    END IF;

    UPDATE PACHETE
    SET
      (
        DataP, UserId, DataCreare, Subunitate,
        Gestiune, CarnetDoc, NrDoc, Colector,
        DataColectare, Verificator, DataVerificare, Transportator,
        DataTransport, NrPachete, Operat, Blocat,
        Anulat, IdentificatorP, Listat, An,
        Luna, CodPart, TipPart, Sediu,
        Delegat, TipLivrare, TipPachet, Sponsorizare
      )
      = (SELECT DataP, UserId, DataCreare, Subunitate,
          Gestiune, CarnetDoc, NrDoc, Colector,
          DataColectare, Verificator, DataVerificare, Transportator,
          DataTransport, NrPachete, Operat, Blocat,
          Anulat, Identificatorp, Listat, An,
          Luna, CodPart, TipPart, Sediu,
          Delegat, COALESCE (TipLivrare, 3) , COALESCE (tippachet, 0), COALESCE(Sponsorizare, 0)
        FROM TMP_PACHETE)
    WHERE
      codpachete = RecId;

    DELETE FROM PACHETE1 WHERE CodPachete = RecId and CodPachete1 NOT IN (SELECT CodPachete1 FROM TMP_PACHETE1);

    FOR V_REC IN (SELECT * FROM TMP_PACHETE1) LOOP
      IF V_REC.CODPACHETE1 &gt; 0 THEN
        UPDATE PACHETE1
        SET CODDOC = V_REC.CODDOC, TIPDOC = V_REC.TIPDOC
        WHERE
          CODPACHETE1 = V_REC.CODPACHETE1;
      ELSE
        INSERT INTO PACHETE1 (CODPACHETE1, CODPACHETE, CODDOC, TIPDOC)
        VALUES (NEXTVAL ('SEQ_PACHETE1_CODPACHETE1') , RECID, V_REC.CODDOC, V_REC.TIPDOC);
      END IF;
    END LOOP;

    DELETE FROM PACHETEOBJ WHERE CODPACHETE = RECID AND CODPACHETEOBJ NOT IN (SELECT CODPACHETEOBJ FROM TMP_PACHETEOBJ);

    FOR V_REC IN (SELECT * FROM TMP_PACHETEOBJ) LOOP
      IF V_REC.CODPACHETEOBJ &gt; 0 THEN
        UPDATE PACHETEOBJ
        SET CODNIRSTOC = V_REC.CODNIRSTOC, CANT = V_REC.CANT, REST = V_REC.REST, CANTUM1 = V_REC.CANTUM1
        WHERE
          CODPACHETEOBJ = V_REC.CODPACHETEOBJ;
      ELSE
        INSERT INTO PACHETEOBJ (CODPACHETEOBJ, CODPACHETE, CODNIRSTOC, CANT, REST, CANTUM1)
        VALUES (NEXTVAL ('SEQ_PACHETEOBJ_CODPACHETEOBJ') , RECID, V_REC.CODNIRSTOC, V_REC.CANT, V_REC.REST, V_REC.CANTUM1);
      END IF;
    END LOOP;

    DELETE FROM PACHETEOBJL WHERE CODPACHETE = RECID AND CODPACHETEOBJL NOT IN (SELECT CODPACHETEOBJL FROM TMP_PACHETEOBJL);

    FOR V_REC IN (SELECT * FROM TMP_PACHETEOBJL) LOOP
      IF V_REC.CODPACHETEOBJL &gt; 0 THEN
        UPDATE PACHETEOBJL
        SET CODLIVR1 = V_REC.CODLIVR1, CANT = V_REC.CANT, REST = V_REC.REST, CANTUM1 = V_REC.CANTUM1, PACHET = V_REC.PACHET, CODREZERVATS = V_REC.CODREZERVATS
        WHERE
          CODPACHETEOBJL = V_REC.CODPACHETEOBJL;
      ELSE
        INSERT INTO PACHETEOBJL (CODPACHETEOBJL, CODPACHETE, CODLIVR1, CANT, REST, CANTUM1, PACHET, CODREZERVATS)
        VALUES (NEXTVAL ('SEQ_PACHETEOBJL_CODPACHETEOBJL') , RECID, V_REC.CODLIVR1, V_REC.CANT, V_REC.REST, V_REC.CANTUM1, V_REC.PACHET, V_REC.CODREZERVATS);
      END IF;
    END LOOP;
  ELSE
    SELECT NEXTVAL ('SEQ_PACHETE_CODPACHETE') INTO RecId;
    PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('PACHETE', RecId);

    IF (SELECT WME_RESULT
        FROM WINMADMIN.PKG_USERFIRME_ValidPostLog (NULL, TO_NUMBER ( (current_setting ('PKG_GLOBALS.USERID', true)) ,'999999999999999999') , (current_setting ('PKG_PACHETE.CT_MONITOR', true))))
    THEN
      PERFORM WINMADMIN.pkg_userfirme_postlogcucommit ('PACHETE', (current_setting ('PKG_GLOBALS.USERNAME', true)) , 'A', RECID,
                                                       (current_setting ('PKG_GLOBALS.FIRMANAME', true)) , aSubunit, aDataDoc, aDoc, null,
                                                       (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION (NULL,NULL)));
    END IF;

    INSERT INTO PACHETE (CodPachete, DataP, Subunitate, Gestiune, CarnetDoc, NrDoc, Colector, DataColectare, Verificator, DataVerificare, Transportator, DataTransport,
                         NrPachete, Operat, Blocat, Anulat, IdentificatorP, Listat, An, Luna, CodPart, TipPart, Sediu, Delegat, TipLivrare, TipPachet, UserID, DataCreare, Sponsorizare)
    (SELECT RecId, DataP, Subunitate, Gestiune, CarnetDoc, NrDoc, Colector, DataColectare, Verificator, DataVerificare, Transportator, DataTransport, NrPachete,
            Operat, Blocat, Anulat, IdentificatorP, Listat, An, Luna, CodPart, TipPart, Sediu, Delegat, COALESCE (TipLivrare, 3) , COALESCE (tippachet, 0) ,
            (SELECT pkg_globals_GETUSERID.WME_RESULT FROM pkg_globals_GETUSERID (NULL,NULL)) , CURRENT_TIMESTAMP, Sponsorizare
     FROM TMP_PACHETE);

    INSERT INTO PACHETE1 (CodPachete1, CodPachete, CodDoc, TipDoc)
    (SELECT NEXTVAL ('SEQ_PACHETE1_CODPACHETE1') , RecId, CodDoc, TipDoc FROM TMP_PACHETE1);

    INSERT INTO PACHETEOBJ (CODPACHETEOBJ, CODPACHETE, CODNIRSTOC, CANT, REST)
    SELECT NEXTVAL ('SEQ_PACHETEOBJ_CODPACHETEOBJ') , RECID, CODNIRSTOC, CANT, REST FROM TMP_PACHETEOBJ;

    INSERT INTO PACHETEOBJL (CODPACHETEOBJL, CODPACHETE, CODLIVR1, CANT, REST, CANTUM1, PACHET, CODREZERVATS)
    SELECT NEXTVAL ('SEQ_PACHETEOBJL_CODPACHETEOBJL') , RECID, CODLIVR1, CANT, REST, CANTUM1, PACHET, CODREZERVATS FROM TMP_PACHETEOBJL;
  END IF;

  UPDATE PACHETEOBJ POBJ
  SET
  REST = CANT - (SELECT COALESCE (SUM (PL.CANT) , 0) FROM PACHETELINK   PL WHERE PL.CODPACHETEOBJ = POBJ.CODPACHETEOBJ)
              - (SELECT COALESCE (SUM (PL.CANT) , 0) FROM PACHETEDLLINK PL WHERE PL.CODPACHETEOBJ = POBJ.CODPACHETEOBJ)
  WHERE
    POBJ.CODPACHETE = RECID;

  IF    (TO_NUMBER ( (current_setting ('PKG_PACHETE.CARNETDOC_I', true)) ,'999999999999999999') &lt;&gt; 0)
    AND (TO_NUMBER ( (current_setting ('PKG_PACHETE.NRDOC_I'    , true)) ,'999999999999999999') &lt;&gt; 0)
    AND (ACARNETDOC &lt;&gt; TO_NUMBER ( (current_setting ('PKG_PACHETE.CARNETDOC_I', true)) ,'999999999999999999')
          OR
         ANUMARDOC &lt;&gt; TO_NUMBER ( (current_setting ('PKG_PACHETE.NRDOC_I', true)) ,'999999999999999999')
        )
  THEN
    PERFORM PKG_CARNETEDOC_RELEASENUMARDOC (TO_NUMBER ( (current_setting ('PKG_PACHETE.CARNETDOC_I', true)) ,'999999999999999999') , TO_NUMBER ( (current_setting ('PKG_PACHETE.NRDOC_I', true)) ,'999999999999999999'));
    PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE (TO_NUMBER ( (current_setting ('PKG_PACHETE.CARNETDOC_I', true)) ,'999999999999999999'));
  END IF;

  PERFORM PKG_CARNETEDOC_SOLVENUMARDOC (aCarnetDoc, aNumarDoc::varchar);
  PERFORM NotifyModif (Operation, RecId, 'PACHETE');
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS(77);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_packing_sp_insertrecord</obj_name>
  <obj_hashval>f3d99529ac875e8c3462a58f0f5efc5e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_packing_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 10.07.2024
  INSERT INTO tmp_packing(codpacking) VALUES (0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_echiv_contserv_nart</obj_name>
  <obj_hashval>ea29ddc2b5287a3eace28e9bb50f29e8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_echiv_contserv_nart()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN (SELECT E.CONTVECHI, A.CODARTICOL, MIN( E.CONTNOU) AS CONTNOU
                FROM NCONTECHIV E, NART A
                WHERE E.AN = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') AND  A.CONTSERVICIU = E.CONTVECHI
                GROUP BY E.CONTVECHI, A.CODARTICOL
               )
  LOOP
    UPDATE NART SET CONTSERVICIU = V_REC.CONTNOU WHERE CODARTICOL = V_REC.CODARTICOL;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planconturi_set_flag_initializari</obj_name>
  <obj_hashval>005cb82e5cad81026f17745107cc47df</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planconturi_set_flag_initializari(flag numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANCONTURI.INITIALIZARI',to_char(FLAG,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_plancurs_sp_deleterecord</obj_name>
  <obj_hashval>12dff3c5401ac41c5cc8247f052ccd6e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_plancurs_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_PLANCURS_SP_LOCKRECORD( RecId);
  DELETE FROM PlanCurs1 WHERE CodPlanCurs = RecId;
  DELETE FROM PlanCurs  WHERE CodPlanCurs = RecId;
  PERFORM NotifyModif( 2, RecId, 'PlanCurs');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_modificastare</obj_name>
  <obj_hashval>490e5e120b3192498c6f54aabfac09d3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_modificastare(INOUT wme_result numeric, INOUT acodstare2 numeric, INOUT atermen character varying, INOUT acodcomanda1 numeric, INOUT acodstare numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aNewTermen    date;
  aCodComanda   numeric;
  aNewCodStare1 numeric;
  aNewCodStare  numeric;
  aAn           numeric;
  aSet          numeric;
  vAn           numeric;
  vSet          numeric;
  vData         date;
  aObs          varchar;
  aCodSubunit   numeric(20);
  aDataDoc      date;
  aOldTermen    varchar(100);
BEGIN
  --Florin 08.08.2022 - sinc. Oracle
  --Florin 10.03.2022 - sinc. Oracle
  aNewTermen := to_date( aTermen, 'DD.MM.YYYY');
  aAn        := to_number( to_char( aNewTermen, 'iyyy'));
  aSet       := to_number( to_char( aNewTermen, 'iw'));

  BEGIN
    DELETE FROM tmp_comanda;
    select c1.codcomanda, c.subunitatea, c.datadoc, c.nrdoc||'/'||to_char(c.datadoc)||' : modificare termen : '||c1.indexlocal||'.'||obj.denumire||' '||to_char(c1.termen,'dd.mm.yyyy')||' -&gt; '||aNewTermen,
    to_char(c1.termen,'dd.mm.yyyy')
    INTO aCodComanda, aCodSubunit, aDataDoc, aObs, aOldTermen
    FROM comanda1 c1
        INNER JOIN comanda c   ON  c1.codcomanda = c.codcomanda
        INNER JOIN nartobj obj ON  c1.codobiect  = obj.codobiect
    WHERE c1.CodComanda1 = aCodComanda1;

    PERFORM pkg_comanda_SP_LOCKRECORD( aCodComanda);

    UPDATE comanda1 SET termen = aNewTermen WHERE CodComanda1 = aCodComanda1;
    --IF (SELECT WINMADMIN.PKG_USERFIRME_ValidPostLog.WME_RESULT FROM WINMADMIN.PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), 'MON_14'))
    --THEN
      PERFORM WINMADMIN.PKG_USERFIRME_PostLogCuCommit( 'COMANDA', (current_setting('PKG_GLOBALS.USERNAME', true)), 'M', aCodComanda, (current_setting('PKG_GLOBALS.FIRMANAME', true)), aCodSubunit, aDataDoc, aObs, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    --END IF;
    INSERT INTO trigar_modif (CodModif, DatAmodif, UserModif, Cod, CodMaster, TableName, FieldName, OldValue, NewValue)
    VALUES(nextval('SEQ_TRIGAR_MODIF'), current_date, GETUSERID(), aCodComanda1,aCodComanda, 'COMANDA', 'TERMEN', Substr(aOldTERMEN,1,100), SubstrB(aTermen,1,100));
    BEGIN
      SELECT se.an, se.saptamana, se.datacreare
      INTO vAn, vSet, vData
      FROM stareestimari se
      WHERE
         se.codstare = aCodStare;
    EXCEPTION WHEN others THEN
      vAn  := 0;
      vSet := 0;
    END;

    IF (SELECT WINMADMIN.PKG_USERFIRME_ValidPostLog.WME_RESULT FROM WINMADMIN.PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_PLANIFCMD.CT_MONITOR', true))))
    THEN
      PERFORM WINMADMIN.PKG_USERFIRME_PostLogCuCommit( 'STAREESTIMARI', (current_setting('PKG_GLOBALS.USERNAME', true)), 'M', vAn * (SELECT PKG_PLANIFCMD_Multip.WME_RESULT FROM PKG_PLANIFCMD_Multip(NULL, vAn)) + vSet, (current_setting('PKG_GLOBALS.FIRMANAME', true)), (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL)), vData, vSet || '/' || vAn, aObs, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;
  EXCEPTION WHEN others THEN
    WME_Result :=  -1;
    RETURN;
  END;

  IF  aCodStare2 &gt; 0 THEN
    UPDATE stareestimari2 SET termen = aNewTermen WHERE codstare2 = aCodStare2;

    BEGIN
      SELECT se1n.codstare1, se1n.codstare
      INTO aNewCodStare1, aNewCodStare
      FROM stareestimari2 se2
          INNER JOIN stareestimari1 se1  ON  se1.codstare1 = se2.codstare1
          INNER JOIN stareestimari  se   ON  se.codstare   = se1.codstare
          INNER JOIN stareestimari  sen  ON  se.an = sen.an and  se.saptamana = sen.saptamana and  se.subunitatea = sen.subunitatea and  sen.ang = aAn and  sen.saptamanag = aSet
          INNER JOIN stareestimari1 se1n ON  se1n.codstare = sen.codstare and  se1n.codobiect = se1.codobiect
      WHERE
         se2.codstare2 = aCodStare2;
    EXCEPTION WHEN others THEN
      aNewCodStare1 := 0;
    END;

    IF  aNewCodStare1 &gt; 0 THEN
      UPDATE stareestimari2
      SET
      termen    = aTermen,
      codstare1 = aNewCodStare1,
      codstare  = aNewCodStare
      WHERE
       codcomanda1 = aCodComanda1;
    END IF;
  END IF;

  BEGIN
    SELECT se1n.codstare1, se1n.codstare
    INTO aNewCodStare1, aNewCodStare
    FROM planiflink l
        INNER JOIN stareestimari1 se1  ON  se1.codstare1 = l.codstare1
        INNER JOIN stareestimari  se   ON  se.codstare   = se1.codstare
        INNER JOIN stareestimari  sen  ON  se.an = sen.an and  se.saptamana = sen.saptamana and  se.subunitatea = sen.subunitatea and  sen.ang = aAn and  sen.saptamanag = aSet
        INNER JOIN stareestimari1 se1n ON  se1n.codstare = sen.codstare and  se1n.codobiect = se1.codobiect
    WHERE
       l.codcomanda1 = aCodComanda1;
  EXCEPTION WHEN others THEN
    aNewCodStare1 := 0;
  END;

  IF  aNewCodStare1 &gt; 0 THEN
    UPDATE planiflink SET codstare1 = aNewCodStare1 WHERE codcomanda1 = aCodComanda1;
  END IF;

  WME_Result :=  1;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_multip</obj_name>
  <obj_hashval>ff0dd026d6c9cdc1082adf43485de093</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_multip(INOUT wme_result numeric, INOUT aan numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vWeeks numeric;
begin
  SELECT to_char( to_date( '01.01.' || to_char( aAn + 1,'9999999999'), 'dd.mm.yyyy'), 'iw')::numeric
  INTO vWeeks;

  IF  vWeeks = 1 THEN
    WME_Result :=  52;
    RETURN;
  ELSE
    WME_Result :=  vWeeks;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_setct_monitor</obj_name>
  <obj_hashval>179f7b780103d788e1a75d768e0ea1e0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANIFCMD.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_setvallclss</obj_name>
  <obj_hashval>3dab0ab5dfe3a17e1e39efe79bfd88b2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_setvallclss(avallclss numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANIFCMD.vAllClsS',to_char(avAllClsS,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_setvallprod</obj_name>
  <obj_hashval>34bff458abb20a2412ed684beaf13351</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_setvallprod(avallprod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANIFCMD.vAllProd',to_char(avAllProd,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifcmd_updatetermenpeprecmd</obj_name>
  <obj_hashval>0f0b5aeadec9cae907592b3c721d8485</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifcmd_updatetermenpeprecmd(INOUT wme_result numeric, INOUT acodprecomanda1 numeric, INOUT atermen character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodPreComanda numeric;
begin
  BEGIN
    SELECT codprecomanda INTO aCodPreComanda FROM precomanda1 WHERE codprecomanda1 = aCodPreComanda1;
  EXCEPTION WHEN others THEN
    aCodPreComanda := 0;
  END;

  IF  aCodPreComanda = 0 THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  UPDATE precomanda1 SET termen = aTermen WHERE CodPreComanda1 = aCodPreComanda1;

  WME_Result :=  1;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprod_sp_insertrecord</obj_name>
  <obj_hashval>d62e136d538697ce44c3ddcd66bc9679</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprod_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 22.12.2020 - inlocuit to_number cu ::numeric
  INSERT INTO TMP_PLANIFPROD(CodPLANIFPROD, SAPTAMANA, INSAPTAMANA)
  VALUES(0, TO_CHAR(CURRENT_TIMESTAMP, 'IW')::NUMERIC, 1);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_planifprodlun_setvallcls</obj_name>
  <obj_hashval>db363cb9cb665f7e51741d60e5b0b116</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_planifprodlun_setvallcls(avallcls numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PLANIFPRODLUN.vAllCls',to_char(avAllCls,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pmp_get_pmp_prec_valuta_from_var</obj_name>
  <obj_hashval>7e5cd58e1002bea2d792386d351407a4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pmp_get_pmp_prec_valuta_from_var(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 31.03.2022 - fixat 53531
WME_Result := CASE WHEN current_setting('PKG_PMP.G_PMP_PREC_VAL', true) = '' THEN -1 ELSE current_setting('PKG_PMP.G_PMP_PREC_VAL', true)::NUMERIC END;
RETURN;
perform set_config('PKG_PMP.G_PMP_PREC_VAL',to_char(-1,'99999999999.9999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_postcalcul_get_pcsectii_1</obj_name>
  <obj_hashval>f095eacf322a5862022bd4413b0839ea</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_postcalcul_get_pcsectii_1(anluna numeric, subunit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  INSERT INTO TMP_PCSECTII2_1 (CODPCSECTII2_1, CODPC, CODNEST, VAL, CODD, CODC, CODCC, CODGEST, DENGEST, CENTRU, DEBIT, CREDIT)
  SELECT row_number() over(), 0, - JJ.INDEXLOCAL, JJ.VALOARE, NS.CODCONTD, NS.CODCONTC, NS.CODCENTRU, NS.CODGEST,
         Substr (G.DEN_GEST, 1, 30) , CC.Simbol, Substr (DEBIT.SIMBOL, 1, 20) , Substr (CREDIT.SIMBOL, 1, 20)
  FROM JURNAL               JJ
    INNER JOIN NESTJURNAL   NS     ON NS.CODNESTJURNAL   = - JJ.INDEXLOCAL
    INNER JOIN Distribchelt DS     ON DS.CODDISTRIBCHELT = JJ.CODDOC
    LEFT JOIN NGEST         G      ON G.CODGEST          = JJ.GEST
    LEFT JOIN CENTRECOST    CC     ON CC.CODCENTRU       = JJ.CODCENTRU
    LEFT JOIN NCONT         DEBIT  ON JJ.CONTD           = DEBIT.CODCONT
    LEFT JOIN NCONT         CREDIT ON JJ.CONTC           = CREDIT.CODCONT
  WHERE
    JJ.IndexLocal &lt; 0
    AND JJ.Tipdoc = 76
    AND (Subunit = 1 or JJ.SUBUNITATEA = Subunit)
    AND (JJ.An * 12 + JJ.Luna = ANLUNA)
    AND DS.FAZA &lt; 3;

  FOR v_rec IN (SELECT CodNest, Sum (Val) TOTAL FROM TMP_PCSECTII2_1 GROUP BY CodNest) LOOP
    UPDATE TMP_PCSECTII2 SET Total = v_rec.Total WHERE CodNest = v_rec.CodNest;
  END LOOP;

  INSERT INTO TMP_PCSECTII3_1 (CODPCSECTII3_1, CODPC, CODNEST, VAL, CODD, CODC, CODCC, CODGEST, DENGEST, CENTRU, DEBIT, CREDIT)
  SELECT row_number() over(), 0, - JJ.INDEXLOCAL, JJ.VALOARE, NS.CODCONTD, NS.CODCONTC, NS.CODCENTRU, NS.CODGEST,
         Substr (G.DEN_GEST, 1, 30) , CC.Simbol, Substr (DEBIT.SIMBOL, 1, 20) , Substr (CREDIT.SIMBOL, 1, 20)
  FROM JURNAL               JJ
    INNER JOIN NESTJURNAL   NS     ON NS.CODNESTJURNAL   = - JJ.INDEXLOCAL
    INNER JOIN Distribchelt DS     ON DS.CODDISTRIBCHELT = JJ.CODDOC
    LEFT JOIN NGEST         G      ON G.CODGEST          = JJ.GEST
    LEFT JOIN CENTRECOST    CC     ON CC.CODCENTRU       = JJ.CODCENTRU
    LEFT JOIN NCONT         DEBIT  ON JJ.CONTD           = DEBIT.CODCONT
    LEFT JOIN NCONT         CREDIT ON JJ.CONTC           = CREDIT.CODCONT
  WHERE
    JJ.IndexLocal &lt; 0
    AND JJ.Tipdoc = 76
    AND (Subunit = 1 or JJ.SUBUNITATEA = Subunit)
    AND (JJ.An * 12 + JJ.Luna = ANLUNA)
    AND DS.FAZA = 4;

  FOR v_rec IN (SELECT CodNest, Sum (Val) TOTAL FROM TMP_PCSECTII3_1 GROUP BY CodNest) LOOP
    UPDATE TMP_PCSECTII3 SET Total = v_rec.Total WHERE CodNest = v_rec.CodNest;
  END LOOP;

  INSERT INTO TMP_PCSECTII5_1 (CODPCSECTII5_1, CODPC, CODNEST, VAL, CODD, CODC, CODCC, CODGEST, DENGEST, CENTRU, DEBIT, CREDIT)
  SELECT row_number() over(), 0, - JJ.INDEXLOCAL, JJ.VALOARE, NS.CODCONTD, NS.CODCONTC, NS.CODCENTRU, NS.CODGEST,
         Substr (G.DEN_GEST, 1, 30) , CC.Simbol, Substr (DEBIT.SIMBOL, 1, 20) , Substr (CREDIT.SIMBOL, 1, 20)
  FROM JURNAL               JJ
    INNER JOIN NESTJURNAL   NS     ON NS.CODNESTJURNAL   = - JJ.INDEXLOCAL
    INNER JOIN Distribchelt DS     ON DS.CODDISTRIBCHELT = JJ.CODDOC
    LEFT JOIN NGEST         G      ON G.CODGEST          = JJ.GEST
    LEFT JOIN CENTRECOST    CC     ON CC.CODCENTRU       = JJ.CODCENTRU
    LEFT JOIN NCONT         DEBIT  ON JJ.CONTD           = DEBIT.CODCONT
    LEFT JOIN NCONT         CREDIT ON JJ.CONTC           = CREDIT.CODCONT
  WHERE
    JJ.IndexLocal &lt; 0
    AND JJ.Tipdoc = 76
    AND (Subunit = 1 or JJ.SUBUNITATEA = Subunit)
    AND (JJ.An * 12 + JJ.Luna = ANLUNA)
    AND DS.FAZA = 3;

  FOR v_rec IN (SELECT CodNest, Sum (Val) TOTAL FROM TMP_PCSECTII5_1 GROUP BY CodNest) LOOP
    UPDATE TMP_PCSECTII5 SET Total = v_rec.Total WHERE CodNest = v_rec.CodNest;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_precomanda_getct_monitor</obj_name>
  <obj_hashval>ddc6509d2349a460727dd7c8e8857024</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_precomanda_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_PRECOMANDA.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_70';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_precomanda_getnrdoc_i</obj_name>
  <obj_hashval>566aa9a4a7c5b1a81b112201d63a5268</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_precomanda_getnrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_PRECOMANDA.NRDOC_I', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_precomanda_sterge</obj_name>
  <obj_hashval>4c7b29a24e1750f51fa95fa387af46d4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_precomanda_sterge(aan numeric, aset numeric, aang numeric, asetg numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR v_rec IN (SELECT codprecomanda FROM precomanda
                WHERE anc = aan and  saptamanac = aset and  ang = aang and  saptamanag = asetg and  userid = (SELECT pkg_globals_GETUSERID.WME_RESULT FROM pkg_globals_GETUSERID(NULL,NULL))
               )
  LOOP
    DELETE FROM precmdlink  WHERE codprecomanda1 IN (SELECT codprecomanda1 FROM precomanda1 WHERE codprecomanda = v_rec.codprecomanda);
    DELETE FROM precomanda1 WHERE codprecomanda = v_rec.codprecomanda;
    DELETE FROM precomanda  WHERE codprecomanda = v_rec.codprecomanda;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_getvalbonconsum</obj_name>
  <obj_hashval>024e9dff6d3849609d7227fbd4774fe7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_getvalbonconsum(INOUT wme_result numeric, INOUT acodcomanda1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  aValMat numeric;
BEGIN
  --Florin 16.03.2023 - sinc. Oracle(14/15.03.2023)
  aValMat := 0;
  FOR v_rec IN (SELECT i1.pu * i1.cant VALOARE
                FROM iesiri1 i1 INNER JOIN iesiri i ON  i.codies = i1.codies
                WHERE i.operat = 1 and  i.anulat = 0 and  i1.codcmdint1 = aCodComanda1
                UNION ALL
                    SELECT
                      i1.cant*i1.pu * case when coalesce(i.moneda,0) &gt; 0 then i.curs else 1 end valoare
                    from intrari1 i1
                    inner join intrari i on i.codintr = i1.codintr
                    where COALESCE(i.anulat,0) = 0 and nvl(i.operat, 0) = 1 and i1.tiplinie = 'S'
                      and i1.codcmdint1 = aCodComanda1 and exists (
                        select mat.codobiect
                        from prodmat mat
                        inner join cmdprodmat cmd on cmd.codprodmat = mat.codmat
                        inner join comanda1 c1 on c1.codcomanda1 = cmd.codcomanda1
                        where c1.codcomanda1 = aCodComanda1 and mat.tip = 6 and mat.codobiect = i1.codobiect
                        )
               )
  LOOP
    aValMat := aValMat + v_rec.valoare;
  END LOOP;

  WME_Result :=  aValMat;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_pregatirecalcul</obj_name>
  <obj_hashval>1e4b6406a47f4f2b20a8e9059b6786e7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_pregatirecalcul(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  total numeric;
  nr    numeric;
  aCod  numeric;
begin
  total := 0;
  UPDATE nirstoc1 ns1 SET dirty = 1 WHERE EXISTS (SELECT bs.codobiect FROM tmp_balanta_stoc bs WHERE bs.Codobiect = ns1.codnirstoc);

  SELECT count(*) INTO Total FROM TMP_BALANTA_STOC tmp;

  WME_Result :=  Total;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_pretprod_updatenirstoc1inluna</obj_name>
  <obj_hashval>81cc9183662a8be4fe09283ed55a53e2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_pretprod_updatenirstoc1inluna(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  Rez numeric;
  Nr  numeric;
begin
  PERFORM PKG_PRETPROD_GetDateCursorLuna();
  SELECT count(*) INTO nr FROM tmp_balanta_stoc;
  Rez := (SELECT PKG_PRETPROD_UpdatePretNS1Partial.WME_RESULT FROM PKG_PRETPROD_UpdatePretNS1Partial(NULL,nr));
  WME_Result :=  Rez;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proc_act_date_gdefaultname</obj_name>
  <obj_hashval>480cf2770a7f8ba9212246a8dbaa290c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proc_act_date_gdefaultname(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PROC_ACT_DATE.gDefaultName', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'WMJOB';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proc_act_date_getgdefaultname</obj_name>
  <obj_hashval>6b657ee970cd81b3cb9dbfffe79f49cd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proc_act_date_getgdefaultname(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PROC_ACT_DATE.gDefaultName', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'WMJOB';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proc_act_date_run_now</obj_name>
  <obj_hashval>36a0777b4dec0912885d3cb0930da052</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proc_act_date_run_now(acodproc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
aName varchar;
begin
null;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_checkretcentr</obj_name>
  <obj_hashval>d95527ae203ceebdfea1d0e143f6ac05</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_checkretcentr(acod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCount NUMERIC(10);
  acount1 NUMERIC(10);
BEGIN
  --Florin 05.12.2023 - sinc. Oracle
  select count(*) into aCount from tmp_prodmat;
  select count(*) into aCount1
  from prodmat m
  inner join tmp_prodmat tm on tm.codobiect = m.codobiect and tm.cant = m.cant
    where m.codprodcomp = acod;
  if aCount &lt;&gt; aCount1 then
    update prodcomp pc
    set codproiect = NULL
      where pc.codproiect &gt; 0 AND
        exists (select pn.codreteta from proiectnod pn where pn.codreteta = aCod and pn.codproiect = pc.codproiect);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_exec_debug</obj_name>
  <obj_hashval>b52e9c85cfd26b5569254d22cd8aaea3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_exec_debug()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_GLOBALS_SetLunaLucru(2016, 1,NULL);
  PERFORM PKG_GLOBALS_SETSUBUNITATE(2);
  DELETE FROM tmp_manevra_liste;
  INSERT INTO tmp_manevra_liste(filtru, valoare) SELECT 'CODPRODCOMP', codprodcomp FROM prodcomp;
  PERFORM PKG_PRODCOMP_ArmeazaTmps(0, true);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_getretetagenerica</obj_name>
  <obj_hashval>a6e59cfcbfb7b17d5b01b5e342d5d9a7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_getretetagenerica(INOUT wme_result numeric, INOUT acodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodReteta numeric;
begin
  aCodReteta := 0;
  BEGIN
    SELECT codprodcomp INTO aCodReteta FROM prodcomp WHERE generic = 1 and  codobiect = acodobiect;
  EXCEPTION WHEN others THEN
    aCodReteta := 0;
  END;

  WME_Result :=  aCodReteta;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_setvdatamin</obj_name>
  <obj_hashval>98e249da1980372b928ed9df9e43a31f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_setvdatamin(avdatamin character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PRODCOMP.vDataMin',avDataMin,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_setvdatastart</obj_name>
  <obj_hashval>0b15d1690769366fa5e6f311756b7f0c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_setvdatastart(avdatastart character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PRODCOMP.vDataStart',avDataStart,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_setvdatastop</obj_name>
  <obj_hashval>3558ca3c965f6835194f7db35720b4a2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_setvdatastop(avdatastop character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PRODCOMP.vDataStop',avDataStop,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_prodcomp_updatecantcuparitate</obj_name>
  <obj_hashval>d32c32df56f478fe66cafc72e69ce4c5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_prodcomp_updatecantcuparitate(acodproiectnod numeric, aparitate numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  UPDATE proiectnod SET cant = aParitate * cant WHERE nodoriginal = aCodProiectnod;

  FOR v_rec IN (SELECT codproiectnod FROM proiectnod WHERE nodoriginal = aCodProiectNod and  Tip = 1) LOOP
    PERFORM PKG_PRODCOMP_UpdateCantCuParitate(v_rec.codproiectnod, aParitate);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_insertpfmanop</obj_name>
  <obj_hashval>a117c8923c5c9783045171344b734e0e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_insertpfmanop(vcodprogramf numeric, vcantprogramat numeric, vcodcmdprodman numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO tmp_programfman_manevra(codprogramf, cant, codcmdprodman)
  VALUES(vcodprogramf, vCantProgramat, vCodCmdProdMan);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_sp_lockrecord</obj_name>
  <obj_hashval>70148635e3f57e54bc4cc2cf43ff2ad8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMP numeric;
begin
  SELECT CODPROGRAMF INTO TMP FROM PROGRAMF WHERE CODPROGRAMF = RECID FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_programf_sp_postrecords</obj_name>
  <obj_hashval>bd540b51c10b0f7cfa2b5ff09cf3a58e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_programf_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  aCARNETDOC  numeric;
  aNRDOC      numeric;
  aCodSubunit numeric;
  aDataDoc    date;
  aDoc        varchar;
BEGIN
  --Florin 01.06.2023 - monitor
  --Adina 16.08.2021 - sinc.Oracle din 14.08.2021
  --Adina 09.07.2021 - sinc.Oracle din 09.07.2021
  --Florin 2303.2021 - pkg_userfirme_postlogcucommit
  perform pkg_programf_setct_monitor('MON_39');
  SELECT COALESCE(CARNETDOC, 0), NRDOC, Subunitatea, DataInreg, coalesce(PREFIXDOC,'') || coalesce(NRDOC::varchar ,'') || '/' || coalesce(To_Char(DATAINREG,'dd.mm.yyyy'),'')
  INTO aCARNETDOC, aNRDOC, aCodSubunit, aDataDoc, aDoc
  FROM TMP_PROGRAMF;

  IF  OPERATION = 0 THEN
    SELECT CODPROGRAMF INTO RECID FROM TMP_PROGRAMF;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_PROGRAMF.CT_MONITOR', true)))
    THEN
      PERFORM pkg_userfirme_postlogcucommit('PROGRAMF', current_setting('PKG_GLOBALS.USERNAME', true), 'M', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), aCodSubunit, aDataDoc, aDoc, null, current_setting('PKG_GLOBALS.EXE_VERSION', true));
    END IF;

    UPDATE PROGRAMF
    SET
    (DATAINREG, VDELA, VPANALA, OPERAT, BLOCAT, ANULAT, TIP, CODFORMATIE, TIPDURATA, NRDOC, CARNETDOC, PREFIXDOC, SERIADOC, ALLGEST, ALLTIPCONT)
    =
    (
    SELECT DATAINREG, VDELA, VPANALA, OPERAT, BLOCAT, ANULAT, TIP, CODFORMATIE, TIPDURATA, NRDOC, CARNETDOC, PREFIXDOC, SERIADOC, ALLGEST, ALLTIPCONT
    FROM TMP_PROGRAMF
    )
    WHERE CODPROGRAMF = RECID;

    FOR V_REC IN (SELECT P1.CODPROGRAMF1 FROM PROGRAMF1 P1
                  WHERE NOT  EXISTS (SELECT CODPROGRAMF1 FROM TMP_PROGRAMF1 WHERE CODPROGRAMF1 = P1.CODPROGRAMF1) AND  CODPROGRAMF = RECID
                 )
    LOOP
      DELETE FROM PROGRAMF1 P1 WHERE P1.CODPROGRAMF1 = V_REC.CODPROGRAMF1;

      UPDATE intrprodlink SET codprogramf1 = NULL WHERE codprogramf1 = v_rec.codprogramf1;
      UPDATE iesprodlink  SET codprogramf1 = NULL WHERE codprogramf1 = v_rec.codprogramf1;
    END LOOP;

    INSERT INTO PROGRAMF1(CODPROGRAMF1, CODPROGRAMF, CODCOMANDA1, CODGEST, PRIORITATE, TERMEN, CANTPROGRAMAT, SCHIMB, CODFORMATIE)
    SELECT NEXTVAL('SEQ_PROGRAMF1_CODPROGRAMF1'), RECID, CODCOMANDA1, CODGEST, PRIORITATE, TERMENEXEC, CANTPROGRAMAT, SCHIMB, CODFORMATIE
    FROM TMP_PROGRAMF1 WHERE CODPROGRAMF1 &lt;= 0;

    FOR V_REC IN (SELECT * FROM TMP_PROGRAMF1 WHERE codprogramf1 &gt; 0) LOOP
      UPDATE PROGRAMF1
      SET
      CODCOMANDA1   = V_REC.CODCOMANDA1,
      CODGEST       = V_REC.CODGEST,
      PRIORITATE    = V_REC.PRIORITATE,
      TERMEN        = V_REC.TERMENEXEC,
      CANTPROGRAMAT = V_REC.CANTPROGRAMAT,
      SCHIMB        = V_REC.SCHIMB,
      CODFORMATIE   = V_REC.CODFORMATIE
      WHERE
       CODPROGRAMF1 = V_REC.CODPROGRAMF1;
    END LOOP;

    DELETE FROM PROGRAMFSDV PSDV WHERE NOT EXISTS (SELECT CODPROGRAMFSDV FROM TMP_PF_SDV_GEST WHERE CODPROGRAMFSDV = PSDV.CODPROGRAMFSDV) AND  CODPROGRAMF = RECID;
    INSERT INTO PROGRAMFSDV(CODPROGRAMFSDV, CODPROGRAMF, CODGEST, CODOBIECT, CANT)
    SELECT NEXTVAL('SEQ_PROGRAMFSDV_CODPROGRAMFSDV'), RECID, CODGEST, CODOBIECT, CANT FROM TMP_PF_SDV_GEST WHERE CODPROGRAMFSDV &lt;= 0;

    FOR V_REC IN (SELECT * FROM TMP_PF_SDV_GEST) LOOP
      UPDATE PROGRAMFSDV SET CANT = V_REC.CANT WHERE CODPROGRAMFSDV = V_REC.CODPROGRAMFSDV;
    END LOOP;

    DELETE FROM LOCURIMUNCAOBS L WHERE NOT EXISTS (SELECT IDOBS FROM TMP_LOCURIMUNCAOBS WHERE IDOBS = L.IDOBS)
                                      AND  EXISTS (SELECT CODPROGRAMF1 FROM TMP_PROGRAMF1 WHERE L.CODPROGRAMF1 = CODPROGRAMF1);

    INSERT INTO LOCURIMUNCAOBS(IDOBS, CODPROGRAMF1, CODLOCMUNCA, OBS)
    SELECT NEXTVAL('SEQ_LOCURIMUNCAOBS_ID'), CODPROGRAMF1, CODLOCMUNCA, OBS FROM TMP_LOCURIMUNCAOBS WHERE IDOBS &lt;= 0;

    FOR V_REC IN (SELECT * FROM TMP_LOCURIMUNCAOBS) LOOP
      UPDATE LOCURIMUNCAOBS SET OBS = V_REC.OBS WHERE IDOBS = V_REC.IDOBS;
    END LOOP;

    DELETE FROM PROGRAMFLMC PLMC WHERE NOT EXISTS (SELECT TMP.CODLMC FROM TMP_PF_LOCM_CMD TMP WHERE TMP.CODLMC = PLMC.CODLMC) AND  PLMC.CODPROGRAMF = RECID;

    FOR V_REC IN (SELECT * FROM TMP_PF_LOCM_CMD) LOOP
      IF  V_REC.CODLMC &gt; 0 THEN
        UPDATE PROGRAMFLMC
        SET
        codgest        = V_REC.CODGEST,
        codloc         = V_REC.CODLOC,
        codcomanda1    = V_REC.CODCOMANDA1,
        dataprogramare = V_REC.DATAPROGRAMARE,
        CODOP          = V_REC.CODOP
        WHERE
         CODLMC = V_REC.CODLMC;
      ELSE
        INSERT INTO PROGRAMFLMC(CODLMC, CODPROGRAMF, CODGEST, CODLOC, CODCOMANDA1, DATAPROGRAMARE, CODOP)
        VALUES(NEXTVAL('SEQ_PROGRAMFLMC_CODLMC'), RECID, V_REC.CODGEST, V_REC.CODLOC, V_REC.CODCOMANDA1, V_REC.DATAPROGRAMARE, V_REC.CODOP);
      END IF;
    END LOOP;

    DELETE FROM PROGRAMFMAN PFMAN
    WHERE NOT EXISTS (SELECT TMP.CODCMDPRODMAN FROM TMP_PROGRAMFMAN_MANEVRA TMP WHERE TMP.CODCMDPRODMAN = PFMAN.CODCMDPRODMAN) AND PFMAN.CODPROGRAMF = RECID;

    FOR V_REC IN (SELECT * FROM TMP_PROGRAMFMAN_MANEVRA) LOOP
      IF  V_REC.CODPFMAN &gt; 0 THEN
        UPDATE PROGRAMFMAN SET CODCMDPRODMAN = V_REC.CODCMDPRODMAN, CANT = V_REC.CANT WHERE CODPFMAN = V_REC.CODPFMAN;
      ELSE
        INSERT INTO PROGRAMFMAN(CODPFMAN, CODPROGRAMF, CODCMDPRODMAN, CANT)
        VALUES(NEXTVAL('SEQ_PROGRAMFMAN_CODPROGRAMFMAN'), RECID, V_REC.CODCMDPRODMAN, V_REC.CANT);
      END IF;
    END LOOP;

    DELETE FROM PROGRAMFGEST WHERE CODPROGRAMF = RECID;
    INSERT INTO PROGRAMFGEST(CODPROGRAMF, CODGEST)
    SELECT RECID, CODGEST FROM TMP_PROGRAMFGEST;

    DELETE FROM PROGRAMFCONT WHERE CODPROGRAMF = RECID;
    INSERT INTO PROGRAMFCONT(CODPROGRAMF, CODIOART)
    SELECT RECID, CODIOART FROM TMP_PROGRAMFCONT;
  ELSE
    SELECT NEXTVAL('SEQ_PROGRAMF_CODPROGRAMF') INTO RECID;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_PROGRAMF.CT_MONITOR', true)))
    THEN
      PERFORM pkg_userfirme_postlogcucommit('PROGRAMF', current_setting('PKG_GLOBALS.USERNAME', true), 'A', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), aCodSubunit, aDataDoc, aDoc, null, current_setting('PKG_GLOBALS.EXE_VERSION', true));
    END IF;

    INSERT INTO PROGRAMF(CODPROGRAMF, DATAINREG, VDELA, VPANALA, OPERAT, BLOCAT, ANULAT, TIP, CODFORMATIE, SUBUNITATEA, TipDurata,
                         AN, LUNA, NRDOC, CARNETDOC, PREFIXDOC, SERIADOC, ALLGEST, ALLTIPCONT)
    SELECT RECID, DATAINREG, VDELA, VPANALA, OPERAT, BLOCAT, ANULAT, TIP, CODFORMATIE, current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, TipDurata,
           current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric, current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric,
           NRDOC, CARNETDOC, PREFIXDOC, SERIADOC, ALLGEST, ALLTIPCONT
    FROM TMP_PROGRAMF;

    INSERT INTO PROGRAMF1(CODPROGRAMF1, CODPROGRAMF, CODCOMANDA1, CODGEST, PRIORITATE, TERMEN, CANTPROGRAMAT, SCHIMB, CODFORMATIE)
    SELECT NEXTVAL('SEQ_PROGRAMF1_CODPROGRAMF1'), RECID, CODCOMANDA1, CODGEST, PRIORITATE, TERMENEXEC, CANTPROGRAMAT, SCHIMB, CODFORMATIE
    FROM TMP_PROGRAMF1;

    INSERT INTO PROGRAMFSDV(CODPROGRAMFSDV, CODPROGRAMF, CODGEST, CODOBIECT, CANT)
    SELECT NEXTVAL('SEQ_PROGRAMFSDV_CODPROGRAMFSDV'), RECID, CODGEST, CODOBIECT, CANT FROM TMP_PF_SDV_GEST;

    INSERT INTO LOCURIMUNCAOBS(IDOBS, CODPROGRAMF1, CODLOCMUNCA, OBS)
    SELECT NEXTVAL('SEQ_LOCURIMUNCAOBS_ID'), CODPROGRAMF1, CODLOCMUNCA, OBS FROM LOCURIMUNCAOBS;

    INSERT INTO PROGRAMFLMC(CODLMC, CODPROGRAMF, CODGEST, CODLOC, CODCOMANDA1, DATAPROGRAMARE, CODOP)
    SELECT NEXTVAL('SEQ_PROGRAMFLMC_CODLMC'), RECID, CODGEST, CODLOC, CODCOMANDA1, DATAPROGRAMARE, CODOP FROM TMP_PF_LOCM_CMD;

    INSERT INTO PROGRAMFMAN(CODPFMAN, CODPROGRAMF, CODCMDPRODMAN, CANT)
    SELECT NEXTVAL('SEQ_PROGRAMFMAN_CODPROGRAMFMAN'), RECID, CODCMDPRODMAN, CANT FROM TMP_PROGRAMFMAN_MANEVRA;

    INSERT INTO PROGRAMFGEST(CODPROGRAMF, CODGEST)
    SELECT RECID, CODGEST FROM TMP_PROGRAMFGEST;

    INSERT INTO PROGRAMFCONT(CODPROGRAMF, CODIOART)
    SELECT RECID, CODIOART FROM TMP_PROGRAMFCONT;
  END IF;

  IF    (current_setting('PKG_PROGRAMF.CARNETDOC_I', true)::numeric &lt;&gt; 0)  AND (current_setting('PKG_PROGRAMF.NRDOC_I', true)::numeric &lt;&gt; 0)
    AND (aCARNETDOC &lt;&gt; current_setting('PKG_PROGRAMF.CARNETDOC_I', true)::numeric OR  aNRDOC &lt;&gt; current_setting('PKG_PROGRAMF.NRDOC_I', true)::numeric)
  THEN
    PERFORM PKG_CARNETEDOC_RELEASENUMARDOC(current_setting('PKG_PROGRAMF.CARNETDOC_I', true)::numeric, current_setting('PKG_PROGRAMF.NRDOC_I', true)::numeric);
    PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE(current_setting('PKG_PROGRAMF.CARNETDOC_I', true)::numeric);
  END IF;

  PERFORM PKG_CARNETEDOC_SOLVENUMARDOC(aCARNETDOC, (aNRDOC)::character varying);
  PERFORM NotifyModif(Operation, RecId, 'CODPROGRAMF');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_getcodproiect</obj_name>
  <obj_hashval>5fa1cf6db0052a86ee0e1d0f7427432b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_getcodproiect(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  current_setting('PKG_PROIECT.vCodProiect', true)::numeric;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_getct_monitor</obj_name>
  <obj_hashval>476911e5979759963241be5a21a335b3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_PROIECT.CT_MONITOR', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_42';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_set_do_commit</obj_name>
  <obj_hashval>0c77566b52d4e05c459a507090fa205a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_set_do_commit(adocommit boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_PROIECT.DoCommit',(aDoCommit)::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_sp_insertrecord</obj_name>
  <obj_hashval>30b6b152e89b1a007e9b43d048f6b428</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 12.04.2023 - sinc. Oracle (11.04.2023)
  --Florin 23.10.2020
  INSERT INTO TMP_PROIECT(Codproiect) VALUES(0);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(507);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_proiect_sp_postrecords</obj_name>
  <obj_hashval>5379d1eda7c5ecae94582a56bf6e3574</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_proiect_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC           RECORD;
  vCODNOD         numeric := 0;
  vOLDCOD         numeric := 0;
  NR               numeric;
  aDurata         numeric;
  aDataDoc         date;
  aDoc             varchar;
  flgTestGeneric   numeric;
  flgModif         numeric;
  ACODUTILIZARE   numeric;
BEGIN
  --Florin 01.06.2023 - monitor
  --Florin 12.04.2023 - sinc. Oracle (11.04.2023)
  --Adina 09.07.2021 - sinc.Oracle din 08.07.2021
  --Florin 30.06.2021 - fixat 50689
  --Adina 25.06.2021 - sinc.Oracle din 24.06.2021
  --Adina 23.06.2021 - sinc.Oracle din 22.06.2021
  --Adina 10.06.2021 - sinc.Oracle din 09.06.2021
  --Adina 27.10.2020
  --Florin 2303.2021 - pkg_userfirme_postlogcucommit
  perform pkg_proiect_setct_monitor('MON_42');
  SELECT DATAPROIECT, VERSIUNE, CODUTILIZARE
  INTO aDATADOC, ADOC, ACODUTILIZARE
  FROM TMP_PROIECT;

  flgTestGeneric := 0;
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT (507);

  IF  operation = 0 THEN
    SELECT CodProiect INTO RecId FROM tmp_proiect;
    flgModif := PKG_PROIECT_CheckModificari(RecID);
  END IF;

  FOR V_REC IN (SELECT * FROM tmp_proiectnod WHERE CodProiectNod &lt; 0) LOOP
    SELECT NEXTVAL('SEQ_PROIECTNOD_CODPROIECTNOD') INTO vCODNOD;
    vOldCod := V_REC.codproiectnod;
    UPDATE tmp_proiectnod SET nodoriginal   = vCODNOD WHERE nodoriginal   = vOldCod;
    UPDATE tmp_proiectnod SET codproiectnod = vCODNOD WHERE codproiectnod = vOldCod;
    UPDATE tmp_proiectman SET codproiectnod = vCODNOD WHERE codproiectnod = vOldCod;
  END LOOP;

  IF  Operation = 0 THEN  -- UPDATE
    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_PROIECT.CT_MONITOR', true))) THEN
      PERFORM pkg_userfirme_postlogcucommit('PROIECT', current_setting('PKG_GLOBALS.USERNAME', true), 'M', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, aDataDoc, aDoc, null, current_setting('PKG_GLOBALS.EXE_VERSION', true));
    END IF;

    UPDATE proiect
    SET ( codversiune, codobiectprod, versiune, intocmita, dataproiect, clasa,
          procesare, complex, activ, finalizat, blocat, Invizibila, implicit, Durata, MarjaOrdine, Generic,
          Obs1, Obs2, Obs3, Obs4, Obs5, Obs6, codextern)
      = (SELECT p.codversiune, p.codobiectprod, p.versiune, p.intocmita, p.dataproiect, p.clasa,
                p.procesare, p.complex, p.activ, p.finalizat, p.blocat, p.Invizibila, p.implicit, 0, COALESCE(p.MarjaOrdine, 0), p.Generic,
                p.Obs1, p.Obs2, p.Obs3, p.Obs4, p.Obs5, p.Obs6, p.codextern
         FROM tmp_proiect p)
    WHERE codproiect = Recid;

    IF  flgModif &gt; 0 THEN
      UPDATE proiect SET codutilizare    = NULL WHERE codproiect      = RecID;
      update proiect set codidentificare = null where codidentificare = RecID;
    else
      update proiect
      set
      (versiune,intocmita,dataproiect,obs1,codextern,marjaordine)
      =
      (select p.versiune, p.intocmita, p.dataproiect, p.Obs1, p.codextern, p.marjaordine from tmp_proiect p)
      where codidentificare = (select codutilizare from tmp_proiect);
    END IF;

    DELETE FROM proiectnod WHERE codproiect = recid and codproiectnod NOT IN (SELECT codproiectnod FROM tmp_proiectnod);

    FOR v_rec IN (SELECT * FROM tmp_proiectnod) LOOP
      SELECT COALESCE(COUNT(*), 0) INTO NR FROM proiectnod WHERE codproiectnod = V_REC.codproiectnod;
      IF  NR = 0 THEN
        INSERT INTO proiectnod(codproiectnod, codproiect, cant, nodoriginal, pozitie, codreteta, tip, codobiect, INDEXPARINTE,
                               CodProdMat, ordine, NIVEL, DECALAJ)
        VALUES(v_rec.codproiectnod, RecId, v_Rec.cant, v_Rec.nodoriginal, v_Rec.pozitie, v_Rec.codreteta, v_Rec.tip, v_rec.codobiect, v_rec.INDEXPARINTE,
               v_Rec.CodProdMat, v_rec.ordine, v_rec.NIVEL,v_Rec.decalaj);
      ELSE
        UPDATE proiectnod SET
          cant         = v_Rec.Cant,
          nodoriginal  = v_Rec.nodoriginal,
          pozitie      = v_Rec.pozitie,
          codreteta    = v_Rec.Codreteta,
          tip          = v_Rec.Tip,
          INDEXPARINTE = v_rec.INDEXPARINTE,
          codobiect    = v_rec.codobiect,
          CodProdMat   = v_rec.Codprodmat,
          ordine       = v_rec.ordine,
          nivel        = v_Rec.Nivel,
          decalaj      = v_rec.decalaj
        WHERE codproiectnod = v_Rec.codproiectnod;
      END IF;
      IF  v_rec.codreteta &lt; 0 THEN
        flgTestGeneric := 1;
        PERFORM GenRetetaNoua(v_rec.codproiectnod, -v_rec.codreteta, v_rec.codobiect, v_rec.obs);
      END IF;
    END LOOP;
  ELSE  --INSERT
    SELECT NEXTVAL('SEQ_PROIECT_CODPROIECT') INTO RecId;
    PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('proiect', RecId);

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_PROIECT.CT_MONITOR', true))) THEN
      PERFORM pkg_userfirme_postlogcucommit('PROIECT', current_setting('PKG_GLOBALS.USERNAME', true), 'A', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, aDataDoc, aDoc, null, current_setting('PKG_GLOBALS.EXE_VERSION', true));
    END IF;

    INSERT INTO proiect(CodProiect, CodVersiune, CodObiectProd, Versiune, Intocmita, DataProiect, Clasa, Procesare, Complex, activ, Finalizat, Blocat, Invizibila, implicit, Durata, MarjaOrdine, generic, Datacreare, USERID, Obs1, Obs2, Obs3, Obs4, Obs5, Obs6, CodExtern)
    (SELECT RecId, P.CodVersiune, P.CodObiectProd, P.Versiune, P.Intocmita, P.DataProiect, P.Clasa, P.Procesare, P.Complex, P.activ, P.Finalizat, P.Blocat, P.Invizibila, P.implicit, 0, COALESCE(P.MarjaOrdine, 0), P.generic, CURRENT_TIMESTAMP, current_setting('PKG_GLOBALS.USERID', true)::numeric, P.Obs1, P.Obs2, P.Obs3, P.Obs4, P.Obs5, P.Obs6, P.CodExtern
     FROM TMP_PROIECT p
    );

    FOR v_rec IN (SELECT * FROM tmp_proiectnod) LOOP
      INSERT INTO PROIECTNOD(CODPROIECTNOD, CODPROIECT, CANT, NODORIGINAL, POZITIE, CODRETETA, TIP, CODOBIECT, INDEXPARINTE, Codprodmat, ordine, nivel, decalaj)
      VALUES(v_rec.codproiectnod, RecId, v_rec.CANT, v_rec.NODORIGINAL, v_rec.POZITIE, v_rec.CODRETETA, v_rec.TIP, v_rec.codobiect, v_rec.INDEXPARINTE,
             v_rec.CodProdMat, v_rec.ordine, v_rec.nivel, v_rec.decalaj);

      IF v_rec.codreteta &lt; 0 THEN
        PERFORM GenRetetaNoua(v_rec.codproiectnod, -v_rec.codreteta, v_rec.codobiect, v_rec.obs);
      END IF;
    END LOOP;

    flgTestGeneric := 1;
  END IF;

  FOR v_Rec IN (WITH RECURSIVE cr AS
                  (SELECT PN.CODPROIECTNOD, 0 nivel, PN.NODORIGINAL, PM.INCEPERE, pm.decalaj
                   FROM PROIECTNOD PN left join TMP_PROIECTMAN PM on PM.Codproiectnod = PN.CODPROIECTNOD
                   WHERE pn.NODORIGINAL = 0 AND pn.CODPROIECT = RecId
                   UNION ALL
                   SELECT pn.CODPROIECTNOD, cr.nivel+1 nivel, pn.NODORIGINAL, PM.INCEPERE, pm.decalaj
                   FROM PROIECTNOD pn
                        left join TMP_PROIECTMAN PM on PM.Codproiectnod = PN.CODPROIECTNOD
                        JOIN cr ON cr.CODPROIECTNOD = pn.NODORIGINAL
                  )
                SELECT CODPROIECTNOD, INCEPERE, nivel FROM cr
               )
  LOOP
    UPDATE proiectnod SET nivel = v_rec.nivel, Incepere = v_rec.Incepere WHERE codproiectnod = v_Rec.codproiectnod;
  END LOOP;

/*
  DELETE FROM tmp_proiectman;

  INSERT INTO tmp_proiectman(CODPROIECTNOD, CODPROIECT, NODORIGINAL, POZITIE, CODRETETA, DEN_OBIECT, TIP, SIMBOL,
                             DURATA, CANT, NIVEL, ORDINE, INCEPERE, Decalaj, DURATANOD, COPILMAXIM, NODCRITIC, BARA)
  SELECT PN.CODPROIECTNOD, PN.CODPROIECT, PN.NODORIGINAL, PN.POZITIE, PN.CODRETETA, obj.denumire DEN_OBIECT, 0, pn.IndexParinte SIMBOL,
         Round((pn.Cant * COALESCE(pc.Durata, 0) / pc.cant)::numeric, 3) DURATA, pn.Cant, pn.nivel, o.Ordine, INCEPERE, 0, 0, -1, '...' NODCRITIC, '...' BARA
  FROM  proiectnod pn
        INNER JOIN prodcomp pc ON  pn.codreteta = pc.codprodcomp
        INNER JOIN nartobj obj ON  obj.codobiect = pc.codobiect
        INNER JOIN (SELECT  DISTINCT Nivel, (SELECT Max(Nivel) FROM proiectnod WHERE CodProiect = RecId) - Nivel AS ORDINE
                    FROM proiectnod
                    WHERE CodProiect = RecId
                    GROUP BY Nivel
                   ) O ON  O.Nivel = pn.Nivel
  WHERE PN.CodProiect = RecId;

  PERFORM PKG_PROIECT_SetCopilMaxim(RecId);
*/

  aDurata := 0;

  BEGIN
    SELECT DurataNod + Incepere INTO aDurata FROM tmp_proiectman WHERE COALESCE(nodoriginal, 0) = 0;
  EXCEPTION WHEN others THEN
    aDurata := 0;
  END;

  IF  aDurata &lt;&gt; 0 THEN
    UPDATE proiect SET Durata = aDurata WHERE CodProiect = RecId;
  END IF;

  IF  flgTestGeneric = 1 THEN
    PERFORM PKG_PROIECT_TestAndUpdateGeneric(RecID);
  END IF;

  --CheckAndUpdateRetete(RecId);
  PERFORM PKG_PROIECT_PROPAGAGANT(RECID);
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS(507);

  IF current_setting('PKG_PROIECT.DoCommit', true)::boolean THEN
    PERFORM NotifyModif(Operation, RecId, 'PROIECT');
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_rez_clonerez</obj_name>
  <obj_hashval>09233b8ec11b91163975d4593bb535f7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_rez_clonerez(acod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  RECID        numeric;
  vCod         numeric;
  aMIJLTRANSP  numeric;
  aCodSubunit  numeric;
  aDataDoc     date;
  aDataStop    date;
  aDataStart   date;
  aDoc         varchar;
  aValoare     double precision;
  aKmIn        double precision;
  aCombIn      double precision;
  aDataIn      date;
  aAn          numeric;
  aLuna        numeric;
  aAn0         numeric;
  aLuna0       numeric;
  aZile        numeric;
  aTipUM       numeric;
  aTipUM1      numeric;
  aZecimale    numeric;
  aCoef        double precision;
  aPret        double precision;
  aVal         double precision;
  aUM1         numeric;
  aCodRAC      numeric;
  aDataFact    date;
  aFactLunara  numeric;
  avalsofercm  double precision;
  avalsoferf   double precision;
  avalclientcm double precision;
  avalclientf  double precision;
  aCantCM      double precision;
  Clone        numeric;
  CloneIndex   numeric;
  aCodArticol  numeric;
  Cod0         numeric;
  aProcTVA     double precision;
BEGIN
  --Florin 11.12.2023 - fixat 60305
  --Florin 14.11.2023 - sinc. Oracle
  --Florin 27.02.2023 - sinc. Oracle (24.02.2023)
  --Florin 29.06.2022 - fnc_getprocenttvaart
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  SELECT Count( *) INTO Clone FROM Rac_REZ WHERE CodREZERVARE = aCod;
  IF  Clone = 0 THEN
    DELETE FROM comanda  WHERE CodComanda = -aCod;
    DELETE FROM comanda1 WHERE CodComanda = -aCod;
    DELETE FROM Rac_rez  WHERE CodComanda = -aCod;

    INSERT INTO COMANDA(CODCOMANDA, TIPDOC, ANULAT, BLOCAT, OPERAT, PARTENER, CODGEST, SUBUNITSURSA, CARNETDOC, PREFIXDOC, NRDOC, SERIADOC, DATADOC, AN, LUNA, OBS, SCADENTAV, INCHISA, VALOARE, MONEDA, CODCONTRACT, CODCMDPARINTE, DELEGAT, CODTRASEULIVR, ORDINELIVRARE, INSOTITOR, MIJLTRANSP, AGENT, VALDISCOUNT, CODLOCATIE, SUBUNITATEA, CODFISCAL, NRI, userid, datacreare, DISPLIVRARE, Verificat, Facturabil, Curs, FARATRANSPORT, PLATAPELOC, CODIES, SCHIMB, CODFORMATIE, IDIMPORT, FACTURA_APL_EXT, CODPERS_APL_EXT, LOT, NRTRANSP, CODIESAVANS, FARAFACTURA, DINONLINE, PRETCUAMANUNT, CODANALIZA, TIPTRANZACTIE, SUBUNITDEST, NRMAXAPROBARI, STADIUWMS)
    SELECT -CODCOMANDA, -TIPDOC, ANULAT, BLOCAT, OPERAT, PARTENER, CODGEST, SUBUNITSURSA, 0, PREFIXDOC, NRDOC, SERIADOC, DATADOC, AN, LUNA, OBS, SCADENTAV, INCHISA, VALOARE, MONEDA, CODCONTRACT, CODCMDPARINTE, DELEGAT, CODTRASEULIVR, ORDINELIVRARE, INSOTITOR, MIJLTRANSP, AGENT, VALDISCOUNT, CODLOCATIE, SUBUNITATEA, CODFISCAL, NRI, userid, datacreare, DISPLIVRARE, Verificat, Facturabil, Curs, FARATRANSPORT, PLATAPELOC, CODIES, SCHIMB, CODFORMATIE, IDIMPORT, FACTURA_APL_EXT, CODPERS_APL_EXT, LOT, NRTRANSP, CODIESAVANS, FARAFACTURA, DINONLINE, PRETCUAMANUNT, CODANALIZA, TIPTRANZACTIE, SUBUNITDEST, NRMAXAPROBARI, STADIUWMS
    FROM COMANDA WHERE CodComanda = aCod;

    INSERT INTO RAC_REZ(CodRAC_REZ, CodComanda, TipRezervare, DataStart, DataStop, CodDelegat1, CodDelegat2, CodGestSursa, CodGestDest, NR_REF, CodCOMISIONAR, CodSediuComis, CODREZERVARE, CodLocalit_Prel, ADRESA_PREL, CodLocalit_Livr, ADRESA_LIVR, NR_ZBOR, codmodel, codmarca, DataFact, datapred, Predat, CodVoucher, codpartext, ProcCedat, CodContr_PRELIVR, FactLunara, SUMAGARANTIE, NUME_CARD, EXPIRA_CARD, CODCCV, OBS_Contract, CodTIPASIG, Email, codinterventie, kmin, kmout, combin, combout, kmnextrev, valsofercm, valsoferf, valclientcm, valclientf, CodSofer, CODSOFER1, CODSOFER2, FARATVA, Telefon, SursaClient)
    SELECT -CodRAC_REZ, -CodComanda, TipRezervare, DataStart, DataStop, CodDelegat1, CodDelegat2, CodGestSursa, CodGestDest, NR_REF, CodCOMISIONAR, CodSediuComis, CODREZERVARE, CodLocalit_Prel, ADRESA_PREL, CodLocalit_Livr, ADRESA_LIVR, NR_ZBOR, codmodel, codmarca, DataFact, datapred, Predat, CodVoucher, codpartext, ProcCedat, CodContr_PRELIVR, FactLunara, SUMAGARANTIE, NUME_CARD, EXPIRA_CARD, CODCCV, OBS_Contract, CodTIPASIG, Email, codinterventie, 0, kmin, 0, combin, kmnextrev, valsofercm, valsoferf, valclientcm, valclientf, CodSofer, CODSOFER1, CODSOFER2, FARATVA, Telefon, SursaClient
    FROM RAC_REZ WHERE CodComanda = aCod;

    INSERT INTO COMANDA1(CODCOMANDA1, CODCOMANDA, INDEXLOCAL, CODOBIECT, UMSEC, PU, CANTCOMANDAT, CANTACCEPTAT, RESTACCEPTAT, CANTRETURNAT, CULANSARE, UMCorelat, PUCorelat, CODCADOU, RESTLANSAT, DataStart, TERMEN, ANULAT, ADDIM, prioritate, PROCDISC, OBS, PRETORIG, COEFDISCMAJ, CODCATPRET, SCADENTA, CONSUM, REZERVATINI, D1, D2, D3, TipSursa, CodSursa, CantUM1, AcceptUM1, TIPPLATA, CADOU, CADOULINK, PRETPROMO, CoefIndirecte, codreteta, Codproiect, TipLivrare, CODANALIZANOD, nivel, pozitie, EXCEPTIONAL, TAXA, CODCONTRACT1, CODOFERTA1, PRETUM1, GESTACT, CODCENTRU, CODNORMA, MODINCHIDERE, TERMENCONTRACT, CODMIFIX, TipLinieSA)
    SELECT -CODCOMANDA1, -CODCOMANDA, INDEXLOCAL, CODOBIECT, UMSEC, PU, CANTCOMANDAT, CANTACCEPTAT, RESTACCEPTAT, CANTRETURNAT, CULANSARE, UMCorelat, PUCorelat, CODCADOU, RESTLANSAT, DataStart, TERMEN, ANULAT, ADDIM, prioritate, PROCDISC, OBS, PRETORIG, COEFDISCMAJ, CODCATPRET, SCADENTA, CONSUM, REZERVATINI, D1, D2, D3, TipSursa, CodSursa, CantUM1, AcceptUM1, TIPPLATA, CADOU, CADOULINK, PRETPROMO, CoefIndirecte, codreteta, Codproiect, TipLivrare, CODANALIZANOD, nivel, pozitie, EXCEPTIONAL, TAXA, CODCONTRACT1, CODOFERTA1, PRETUM1, GESTACT, CODCENTRU, CODNORMA, MODINCHIDERE, TERMENCONTRACT, CODMIFIX, TipLinieSA
    FROM Comanda1 WHERE CodComanda = aCod;
  END IF;

  SELECT SUBUNITATEA, DATADOC, 'CLONA ' || PREFIXDOC || NRDOC || '/' || DATADOC, VALOARE, An, Luna, MIJLTRANSP
  INTO aCodSubunit, aDATADOC, aDoc, aValoare, aAn, aLUNA, aMIJLTRANSP
  FROM COMANDA WHERE CodComanda = aCod;

  aLuna0 := aLuna;
  aAn0   := aAn;

  IF  aLuna = 12 THEN
    aLuna := 1;
    aAn   := aAn + 1;
  ELSE
    aLuna := aLuna + 1;
  END IF;

  SELECT NEXTVAL('SEQ_COMANDA_CODCOMANDA') INTO RecId;

  IF (SELECT wme_result FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID',true)),'999999999999999999'), (current_setting('PKG_RAC_REZ.CT_MONITOR',true))))
  THEN
    PERFORM pkg_userfirme_postlogcucommit( 'COMANDA', (current_setting('PKG_GLOBALS.USERNAME',true)), 'A', RECID, (current_setting('PKG_GLOBALS.FIRMANAME',true)), aCodSubunit, CURRENT_TIMESTAMP, aDoc, null, (SELECT WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  SELECT DATAStop, DATAStart, DataFact, KmIn, CombIn, COALESCE( FactLunara, 0) FactLunara
  INTO aDATAStop, aDATAStart, aDataFact, aKmIn, aCombIn, aFactLunara
  FROM RAC_REZ WHERE CodComanda = aCod;

  aDataDoc := (SELECT WME_RESULT FROM PKG_RAC_REZ_RAC_DATASTART(NULL,NULL));

  BEGIN
    SELECT COALESCE( LOT, 0) INTO CloneIndex FROM Comanda WHERE CodComanda = aCod;
  EXCEPTION WHEN OTHERS THEN
    CloneIndex := 0;
  END;

  INSERT INTO COMANDA(CODCOMANDA, TIPDOC, ANULAT, BLOCAT, OPERAT, PARTENER, CODGEST, SUBUNITSURSA, CARNETDOC, PREFIXDOC, NRDOC, SERIADOC, DATADOC, AN, LUNA, OBS, SCADENTAV, INCHISA, VALOARE, MONEDA, CODCONTRACT, CODCMDPARINTE, DELEGAT, CODTRASEULIVR, ORDINELIVRARE, INSOTITOR, MIJLTRANSP, AGENT, VALDISCOUNT, CODLOCATIE, SUBUNITATEA, CODFISCAL, NRI, userid, datacreare, DISPLIVRARE, Verificat, Facturabil, Curs, FARATRANSPORT, PLATAPELOC, CODIES, SCHIMB, CODFORMATIE, IDIMPORT, FACTURA_APL_EXT, CODPERS_APL_EXT, LOT, NRTRANSP, CODIESAVANS, FARAFACTURA, DINONLINE, PRETCUAMANUNT, CODANALIZA, TIPTRANZACTIE, SUBUNITDEST, NRMAXAPROBARI, STADIUWMS)
  SELECT RecId, TIPDOC, ANULAT, BLOCAT, OPERAT, PARTENER, CODGEST, SUBUNITSURSA, 0, PREFIXDOC, NRDOC, SERIADOC, aDATADOC, Extract( Year FROM aDataDoc), Extract( Month FROM aDataDoc), OBS, SCADENTAV, INCHISA, VALOARE, MONEDA, CODCONTRACT, CODCMDPARINTE, DELEGAT, CODTRASEULIVR, ORDINELIVRARE, INSOTITOR, MIJLTRANSP, AGENT, VALDISCOUNT, CODLOCATIE, SUBUNITATEA, CODFISCAL, NRI, TO_NUMBER((current_setting('PKG_GLOBALS.USERID',true)),'999999999999999999'), CURRENT_TIMESTAMP, DISPLIVRARE, Verificat, Facturabil, COALESCE( Curs, 1), FARATRANSPORT, PLATAPELOC, CODIES, SCHIMB, CODFORMATIE, IDIMPORT, FACTURA_APL_EXT, CODPERS_APL_EXT, CloneIndex + 1, NRTRANSP, CODIESAVANS, FARAFACTURA, DINONLINE, PRETCUAMANUNT, CODANALIZA, TIPTRANZACTIE, SUBUNITDEST, NRMAXAPROBARI, STADIUWMS
  FROM COMANDA WHERE CodComanda = aCod;

  aCodRAC   := NEXTVAL('SEQ_RAC_REZ_COD');
  aDataFact := ADD_MONTHS( aDataFact, 1);

  INSERT INTO RAC_REZ(CodRAC_REZ, CodComanda, TipRezervare, DataStart, DataStop, CodDelegat1, CodDelegat2, CodGestSursa, CodGestDest, NR_REF, CodCOMISIONAR, CodSediuComis, CODREZERVARE, CodLocalit_Prel, ADRESA_PREL, CodLocalit_Livr, ADRESA_LIVR, NR_ZBOR, codmodel, codmarca, DataFact, datapred, Predat, CodVoucher, codpartext, ProcCedat, CodContr_PRELIVR, FactLunara, SUMAGARANTIE, NUME_CARD, EXPIRA_CARD, CODCCV, OBS_Contract, CodTIPASIG, Email, codinterventie, kmin, kmout, combin, combout, kmnextrev, valsofercm, valsoferf, valclientcm, valclientf, CodSofer, CODSOFER1, CODSOFER2, FARATVA, Telefon, SursaClient)
  SELECT aCodRAC, RECID, TipRezervare, aDatadoc, DataStop, CodDelegat1, CodDelegat2, CodGestDest, CodGestDest, NR_REF, CodCOMISIONAR, CodSediuComis, aCod, CodLocalit_Livr, ADRESA_LIVR, CodLocalit_Livr, ADRESA_LIVR, NR_ZBOR, codmodel, codmarca, aDataFact, datapred, Predat, CodVoucher, codpartext, ProcCedat, CodContr_PRELIVR, FactLunara, SUMAGARANTIE, NUME_CARD, EXPIRA_CARD, CODCCV, OBS_Contract, CodTIPASIG, Email, codinterventie, 0, aKmIn, 0, combout, kmnextrev, valsofercm, valsoferf, valclientcm, valclientf, CodSofer, CODSOFER1, CODSOFER2, FARATVA, Telefon, SursaClient
  FROM RAC_REZ WHERE CodComanda = aCod;

  aDataStop := to_date(current_setting('PKG_RAC_REZ.DATAPORNIRE',true), 'DD.MM.YYYY hh24:mi') - interval '1 seconds';

  BEGIN
    SELECT CodNParc0 INTO Cod0 FROM NParc0 WHERE CODCMD = aCod;
  EXCEPTION WHEN OTHERS THEN
    Cod0 := 0;
  END;

  IF  Cod0 = 0 THEN
    INSERT INTO NPARC0(CODNPARC0, CODNPARCAUT, CodCMD, DATABORD, KMBORD, COMB, AN, LUNA, OBS)
    VALUES(NEXTVAL('SEQ_NPARC0_CODNPARC0'), aMIJLTRANSP, aCod, aDataStop, aKmIn, aCombIn, aAn0, aLuna0, aDoc);
  ELSE
    UPDATE NParc0 SET DataBord = aDataStop WHERE CodNParc0 = Cod0;
  END IF;

  UPDATE RAC_REZ
  SET
  DataStop = aDataStop,
  DataPred = aDataStop,
  Predat   = 1,
  CodCCV   = 1
  WHERE
   CodComanda = aCod;

  UPDATE TMP_RAC_REZ
  SET
  DataStop = aDataStop,
  DataPred = aDataStop,
  Predat   = 1,
  CodCCV   = 1
  WHERE
   CodComanda = aCod;

  avalsofercm  := 0;
  avalsoferf   := 0;
  avalclientcm := 0;
  avalclientf  := 0;

  FOR V_REC IN (SELECT * FROM COMANDA1 WHERE CodComanda = aCod) LOOP
    SELECT NEXTVAL('SEQ_COMANDA1_CODCOMANDA1') INTO VCOD;

    BEGIN
      SELECT COALESCE( e1.Cant, 0)
      INTO aCantCM
      FROM Emulare1 e1 INNER JOIN Emulare e ON  e.CodEmulare = e1.CodEmulare
      WHERE COALESCE( e.CODMONETAR, 0) = 0 and  e1.Codcomanda1 = v_rec.codcomanda1;
    EXCEPTION WHEN OTHERS THEN
      aCantCM := 0;
    END;

    INSERT INTO COMANDA1(CODCOMANDA1, CODCOMANDA, INDEXLOCAL, CODOBIECT, UMSEC, PU, CANTCOMANDAT, CANTACCEPTAT, RESTACCEPTAT, CANTRETURNAT, CULANSARE, UMCorelat, PUCorelat, CODCADOU, RESTLANSAT, DataStart, TERMEN, ANULAT, ADDIM, prioritate, PROCDISC, OBS, PRETORIG, COEFDISCMAJ, CODCATPRET, SCADENTA, CONSUM, REZERVATINI, D1, D2, D3, TipSursa, CodSursa, CantUM1, AcceptUM1, TIPPLATA, CADOU, CADOULINK, PRETPROMO, CoefIndirecte, codreteta, Codproiect, TipLivrare, CODANALIZANOD, nivel, pozitie, EXCEPTIONAL, TAXA, CODCONTRACT1, CODOFERTA1, PRETUM1, GESTACT, CODCENTRU, CODNORMA, MODINCHIDERE, TERMENCONTRACT, CODMIFIX, TipLinieSA)
    VALUES(vCod, RecID, v_rec.INDEXLOCAL, v_rec.CODOBIECT, v_rec.UMSEC, v_rec.PU, v_rec.CANTCOMANDAT, v_rec.CANTACCEPTAT, v_rec.RESTACCEPTAT - aCantCM, v_rec.CANTRETURNAT, v_rec.CULANSARE, v_rec.UMCorelat, v_rec.PUCorelat, V_REC.CODCADOU, v_rec.CANTACCEPTAT, aDataDoc, v_rec.TERMEN, v_rec.ANULAT, V_REC.ADDIM, v_rec.prioritate, V_REC.PROCDISC, V_REC.OBS, V_REC.PRETORIG, V_REC.COEFDISCMAJ, V_REC.CODCATPRET, V_REC.SCADENTA, V_REC.CONSUM, v_rec.REZERVATINI, v_rec.D1, v_rec.D2, v_rec.D3, v_rec.tipSursa, v_rec.CodSursa, v_rec.CantUM1, V_REC.AcceptUM1, V_REC.TIPPLATA, V_REC.CADOU, V_REC.CADOULINK, V_REC.PRETPROMO, v_rec.CoefIndirecte, v_rec.codreteta, v_rec.Codproiect, v_rec.TipLivrare, V_REC.CODANALIZANOD, v_rec.nivel, v_rec.pozitie, v_rec.EXCEPTIONAL, V_REC.TAXA, V_REC.CODCONTRACT1, V_REC.CODOFERTA1, V_REC.PRETUM1, V_REC.GESTACT, V_REC.CODCENTRU, V_REC.CODNORMA, V_REC.MODINCHIDERE, V_REC.TERMENCONTRACT, V_REC.CODMIFIX, V_REC.TipLinieSA);

    SELECT COALESCE( TipUM, 0), COALESCE( u.Zecimale, 0), COALESCE( u.Coef, 1)
    INTO aTipUM, aZecimale, aCoef
    FROM NUM1 u1, num u WHERE u1.Codum1 = v_rec.umsec and  u.codum = u1.codum;

    IF  aTipUM = 6 THEN
      aZile := Round( v_rec.TERMEN - aDataDoc, 0);
      UPDATE COMANDA1     SET Cantacceptat = aZile WHERE CodComanda1 = vCod;
      aZile := v_rec.Cantacceptat - aZile;
      UPDATE COMANDA1     SET Cantacceptat = aZile WHERE CodComanda1 = v_rec.CodComanda1;
      UPDATE TMP_COMANDA1 SET Cantacceptat = aZile WHERE CodComanda1 = v_rec.CodComanda1;
    ELSE
      aTipUM := 0;

      BEGIN
        SELECT UM1 INTO aUM1 FROM NArt a, NArtObj O WHERE O.CodObiect = v_rec.CodObiect and  a.Codarticol = o.Codarticol;
        SELECT COALESCE( TipUM, 0), COALESCE( u.Zecimale, 0), COALESCE( Coef, 1) INTO aTipUM, aZecimale, aCoef FROM num u WHERE u.Codum = aUm1;

        IF  aTipUM = 6 and  COALESCE( v_rec.AcceptUM1, 0) &lt;&gt; 0 and  COALESCE( v_rec.Cantacceptat, 0) &lt;&gt; 0 THEN
          aZile := Round( v_rec.TERMEN - aDataDoc, 0);
          UPDATE COMANDA1
          SET
          AcceptUM1 = aZile,
          PU        = PretUM1 * aZile / v_rec.Cantacceptat,
          Pretorig  = PretUM1 * aZile / v_rec.Cantacceptat
          WHERE CodComanda1 = vCod;

          aZile := v_rec.AcceptUM1 - aZile;
          UPDATE COMANDA1
          SET
          AcceptUM1 = aZile,
          PU        = PretUM1 * aZile / v_rec.Cantacceptat,
          Pretorig  = PretUM1 * aZile / v_rec.Cantacceptat
          WHERE CodComanda1 = v_rec.CodComanda1;

          UPDATE TMP_COMANDA1
          SET
          AcceptUM1 = aZile,
          PU        = PretUM1 * aZile / v_rec.Cantacceptat,
          Pretorig  = PretUM1 * aZile / v_rec.Cantacceptat
          WHERE CodComanda1 = v_rec.CodComanda1;

          UPDATE TMP_COMANDA1 SET Valoare = PU * Cantacceptat WHERE CodComanda1 = v_rec.CodComanda1;
        ELSE
          aTipUM := 0;
        END IF;
      EXCEPTION WHEN others THEN
        aTipUM := 0;
      END;

      IF  aTipUM = 0 THEN
        UPDATE COMANDA1
        SET
        CantAcceptat = 0,
        AcceptUM1    = 0
        WHERE CodComanda1 = vCod;
      END IF;

      UPDATE TMP_COMANDA1 C1
      SET
      VALDISCOUNT = COALESCE( CANTACCEPTAT, 0) * COALESCE( PU, 0) * COALESCE( PROCDISC, 0) / 100,
      TVA         = COALESCE( COALESCE( CANTACCEPTAT, 0) * COALESCE( PU, 0) * COALESCE( PROCTVA, 0) / 100, 0);
    END IF;

    SELECT CodArticol INTO aCodArticol FROM NartObj WHERE CodObiect = v_rec.CodObiect;
    aProcTVA := fnc_getprocenttvaart(aCodArticol, TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU',true)),'999999999999999999'), TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU',true)),'999999999999999999'));

    BEGIN
      SELECT COALESCE( CANTACCEPTAT, 0) * COALESCE( PU, 0) * (  1 + COALESCE( ProcDisc, 0) / 100)  * (  1 + COALESCE( aPROCTVA, 0) / 100)
      INTO aVal
      FROM Comanda1 WHERE CodComanda1 = vCod and  COALESCE( CuLansare, 0) = 2 and  COALESCE( ModInchidere, 0) = 1;
    EXCEPTION WHEN others THEN
      aVal := 0;
    END;

    avalsofercm := avalsofercm + aVal;
    BEGIN
      SELECT COALESCE( CANTACCEPTAT, 0) * COALESCE( PU, 0) * (  1 + COALESCE( ProcDisc, 0) / 100)  * (  1 + COALESCE( aPROCTVA, 0) / 100)
      INTO aVal
      FROM Comanda1 WHERE CodComanda1 = vCod and  COALESCE( CuLansare, 0) = 2 and  COALESCE( ModInchidere, 0) = 0;
    EXCEPTION WHEN others THEN
      aVal := 0;
    END;

    avalsoferf := avalsoferf + aVal;
    BEGIN
      SELECT COALESCE( CANTACCEPTAT, 0) * COALESCE( PU, 0) * (  1 + COALESCE( ProcDisc, 0) / 100)  * (  1 + COALESCE( aPROCTVA, 0) / 100)
      INTO aVal
      FROM Comanda1 WHERE CodComanda1 = vCod and  COALESCE( CuLansare, 0) &lt;&gt; 2 and  COALESCE( ModInchidere, 0) = 1;
    EXCEPTION WHEN others THEN
      aVal := 0;
    END;

    avalclientcm := avalclientcm + aVal;
    BEGIN
      SELECT COALESCE( CANTACCEPTAT, 0) * COALESCE( PU, 0) * (  1 + COALESCE( ProcDisc, 0) / 100)  * (  1 + COALESCE( aPROCTVA, 0) / 100)
      INTO aVal
      FROM Comanda1 WHERE CodComanda1 = vCod and  COALESCE( CuLansare, 0) &lt;&gt; 2 and  COALESCE( ModInchidere, 0) = 0;
    EXCEPTION WHEN others THEN
      aVal := 0;
    END;

    avalclientf := avalclientf + aVal;
  END LOOP;

  UPDATE COMANDA1 SET Termen = aDataStop WHERE CodComanda = aCod;

  UPDATE COMANDA
  SET
  Blocat      = 1,
  Valoare     = (SELECT Sum( COALESCE( CANTACCEPTAT, 0) * COALESCE( PU, 0) * (  1 + COALESCE( PROCDISC, 0) / 100) ) FROM tmp_comanda1),
  VALDISCOUNT = (SELECT Sum( COALESCE( ValDiscount, 0)) FROM tmp_Comanda1)
  WHERE CodComanda = aCod;

  UPDATE TMP_COMANDA
  SET
  Blocat      = 1,
  Valoare     = (SELECT Sum( COALESCE( CANTACCEPTAT, 0) * COALESCE( PU, 0) * (  1 + COALESCE( PROCDISC, 0) / 100) ) FROM tmp_comanda1),
  VALDISCOUNT = (SELECT Sum( COALESCE( ValDiscount, 0)) FROM tmp_Comanda1);

  UPDATE COMANDA
  SET
  Valoare     = (SELECT Sum( COALESCE( Cantacceptat, 0) * COALESCE( PU, 0) * (  1 + COALESCE( PROCDISC, 0) / 100) ) FROM comanda1 WHERE CodComanda = RECID),
  VALDISCOUNT = (SELECT Sum( COALESCE( COALESCE( CANTACCEPTAT, 0) * COALESCE( PU, 0) * COALESCE( PROCDISC, 0) / 100, 0)) FROM Comanda1 WHERE CodComanda = RECID)
  WHERE CodComanda = RECID;

  UPDATE RAC_REZ
  SET
  valsofercm  = avalsofercm,
  valsoferf   = avalsoferf,
  valclientcm = avalclientcm,
  valclientf  = avalclientf
  WHERE CodComanda = RECID;

  UPDATE TMP_COMANDA SET ValTVA = Round( (SELECT Sum( COALESCE( TVA, 0) * (  1 + COALESCE( ProcDisc, 0) / 100) ) FROM tmp_Comanda1), 2);
  UPDATE TMP_COMANDA SET DiscTVA = ValDiscount * ValTVA / Valoare WHERE COALESCE( Valoare, 0) &lt;&gt; 0;
  UPDATE TMP_COMANDA
  SET
  Valoare     = Valoare + ValTVA,
  ValDiscount = ValDiscount + DiscTVA;

  UPDATE TMP_RAC_REZ
  SET
  valsofercm  = COALESCE( (SELECT Sum( (Valoare + TVA) * (1 + COALESCE( ProcDisc, 0) / 100) ) FROM Tmp_Comanda1 WHERE COALESCE( CuLansare, 0)  = 2 and  COALESCE( ModInchidere, 0) = 1), 0),
  valsoferf   = COALESCE( (SELECT Sum( (Valoare + TVA) * (1 + COALESCE( ProcDisc, 0) / 100) ) FROM Tmp_Comanda1 WHERE COALESCE( CuLansare, 0)  = 2 and  COALESCE( ModInchidere, 0) = 0), 0),
  valclientcm = COALESCE( (SELECT Sum( (Valoare + TVA) * (1 + COALESCE( ProcDisc, 0) / 100) ) FROM Tmp_Comanda1 WHERE COALESCE( CuLansare, 0) &lt;&gt; 2 and  COALESCE( ModInchidere, 0) = 1), 0),
  valclientf  = COALESCE( (SELECT Sum( (Valoare + TVA) * (1 + COALESCE( ProcDisc, 0) / 100) ) FROM Tmp_Comanda1 WHERE COALESCE( CuLansare, 0) &lt;&gt; 2 and  COALESCE( ModInchidere, 0) = 0), 0);

  UPDATE RAC_REZ
  SET
  valsofercm  = COALESCE( (SELECT Sum( (Valoare + TVA) * (1 + COALESCE( ProcDisc, 0) / 100) ) FROM Tmp_Comanda1 WHERE COALESCE( CuLansare, 0)  = 2 and  COALESCE( ModInchidere, 0) = 1), 0),
  valsoferf   = COALESCE( (SELECT Sum( (Valoare + TVA) * (1 + COALESCE( ProcDisc, 0) / 100) ) FROM Tmp_Comanda1 WHERE COALESCE( CuLansare, 0)  = 2 and  COALESCE( ModInchidere, 0) = 0), 0),
  valclientcm = COALESCE( (SELECT Sum( (Valoare + TVA) * (1 + COALESCE( ProcDisc, 0) / 100) ) FROM Tmp_Comanda1 WHERE COALESCE( CuLansare, 0) &lt;&gt; 2 and  COALESCE( ModInchidere, 0) = 1), 0),
  valclientf  = COALESCE( (SELECT Sum( (Valoare + TVA) * (1 + COALESCE( ProcDisc, 0) / 100) ) FROM Tmp_Comanda1 WHERE COALESCE( CuLansare, 0) &lt;&gt; 2 and  COALESCE( ModInchidere, 0) = 0), 0)
  WHERE
   CodComanda = aCod;

  PERFORM NotifyModif( 1, RecId, 'COMANDA');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rac_rez_setdatapornire</obj_name>
  <obj_hashval>e50d12531cac629818e690f70c703092</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rac_rez_setdatapornire(adatapornire date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_RAC_REZ.DataPornire',aDataPornire,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_raportp_setct_monitor</obj_name>
  <obj_hashval>babd7db552c7b260c18fb0516a7c2b69</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_raportp_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_RAPORTP.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rapstocmed_getvcodsiui</obj_name>
  <obj_hashval>de5378673722dbd384e574ea4257bc20</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rapstocmed_getvcodsiui(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_RAPSTOCMED.vCodSiui', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_rapstocmed_setvcodsiui</obj_name>
  <obj_hashval>54229a7601e5c997477fdfb5de84c436</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_rapstocmed_setvcodsiui(avcodsiui character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_RAPSTOCMED.vCodSiui',avCodSiui,false);
end;
$function$
</obj_text>
</row>

</table>
